agnes-the-ai-analyst/docs/superpowers/plans/2026-05-11-admin-observability-spec.md
ZdenekSrotyr b4d3c576af
Activity Center: audit log + telemetry + sessions + agnes_* tables (#278)
* docs(spec): admin observability spec + Activity Center MVP plan

Parent spec (480 lines) + executable plan (2295 lines, 14 TDD tasks).
Covers Activity Center rebuild (/admin/activity), with /admin/sessions
and /admin/feedback deferred to follow-up plans.

Already incorporates reviewer-pass revisions across three angles
(security, production resilience, code architecture):
- _get_db import path corrected to app.auth.dependencies
- Test fixtures aligned with seeded_app / admin_user / get_system_db
- All new audit writes wrapped in try/except + logger.exception
- Filename sanitization on session uploads
- DuckDB DESC index behavior documented; upgrade window flagged
- Migration idempotency + evolved-DB test cases
- reveal_raw + shared-cache multi-worker explicitly deferred

Targets schema v40 (audit_log gains params_before, client_ip,
client_kind, correlation_id + 3 indices).

* feat(db): schema v40 — audit_log gains params_before, client_ip, client_kind, correlation_id + 3 indices

* chore(test): clean up Task 1 — drop unused import, rename stale test

* feat(audit): AuditRepository.log() accepts params_before/client_ip/client_kind/correlation_id

* test(audit): strengthen params_before assertion to round-trip JSON content

* feat(audit): AuditRepository.query() rich filters + keyset cursor pagination

* feat(sync): SyncStateRepository.list_recent() cross-table feed

* feat(audit): POST /api/sync/trigger writes audit_log row

* feat(audit): POST /api/scripts/run-due writes audit_log row

* feat(audit): POST /api/upload/sessions writes audit_log row + sanitizes filename

* feat(audit): GET /api/data/{table_id}/download writes audit_log row

* feat(activity): /api/admin/activity timeline + /health + /sync endpoints

* feat(ui): /admin/activity rebuilt — health pulse, timeline, sync grid; /activity-center → 308 redirect

BREAKING: removed demo executive-pulse / maturity-roadmap content from activity_center.html.
The page now reflects real audit_log + sync_history data.

* feat(ui): admin nav + dashboard widget point at /admin/activity

* feat(activity): recursive-audit suppression for AC read endpoints (60s window per actor+filter)

* feat(activity): emit PostHog events when integration enabled (no-op default)

* fix(audit): move v40 indices out of _SYSTEM_SCHEMA + update test_repositories to unpack query() tuple

_SYSTEM_SCHEMA CREATE INDEX on audit_log(timestamp) failed when migration
tests hand-roll a bare audit_log (id, action) without the timestamp column.
Fix: remove indices from _SYSTEM_SCHEMA; add ADD COLUMN IF NOT EXISTS guards
for timestamp and other pre-v40 columns in _v39_to_v40() so the upgrade path
is safe on any hand-rolled schema; call _v39_to_v40 explicitly in the
fresh-install (current==0) path to restore index creation there.

Also unpack the (rows, next_cursor) tuple from AuditRepository.query() in
the three TestAuditRepository tests that still treated it as a list.

* docs: CHANGELOG entry for Activity Center MVP

* chore: refresh stale module docstring in app/api/activity.py

* feat(cli): agnes admin activity — terminal access to Activity Center (timeline + health + sync)

* fix(db): _v39_to_v40 — add IF NOT EXISTS guard for 'action' column

The v39→v40 ladder step adds defensive ADD COLUMN IF NOT EXISTS for
every audit_log column so a hand-rolled bare audit_log (id only) is
safe through the ladder. 'action' was missing from the guard list,
causing CREATE INDEX idx_audit_action_time to fail on tests that
stub audit_log with only an id column (tests/test_e2e_extract.py::
TestSchemaMigration::test_migration_preserves_and_extends).

Local 6/6 schema tests + the previously-failing CI test pass.

* docs(spec): platform telemetry epic — Boss directive + Activity Monitoring plan rebased onto v40 (stacked on zs/spec-activity-center)

* feat(db): schema v41 — 7 usage_* tables for telemetry (events, summary, rollups, attribution)

* chore(db): tighten v41 — usage_session_summary.session_id NOT NULL + upgrade test asserts all 7 tables

* feat(usage): UsageAttributionRepository — replace/delete/lookup over usage_attribution_* tables

* refactor(marketplace): extract list_inner_skills/agents/commands to src/marketplace_listing.py for reuse

* feat(usage): explode plugin attribution on marketplace sync + store entity write; backfill script

* refactor(marketplace): finish src/marketplace_listing.py extraction — drop duplicate _list_inner_* + _parse_frontmatter from app/api/marketplace.py

* feat(usage): promote attribution helpers to src/usage_attribution_helpers.py; hook update_entity rename + bundle-swap; clarify best-effort semantics

* feat(usage): UsageProcessor real extraction + rollup rebuild + 10 fixture-driven tests

* fix(usage): include tool_id in event hash + executemany + rollup transaction (critical multi-tool-turn drop fix)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(marketplace): popularity stats — invocations_30d + trend + sort=most_used|trending + Most Popular section

* feat(admin): /admin/users/<id> Sessions section — list + single-file + bulk-zip downloads (audit-logged)

* feat(usage): admin export endpoint + CLI — csv/json/parquet streaming, filters, audit-logged

* feat(usage): agnes admin ask — LLM Text-to-SQL over usage_events with SELECT-only validator (audit-logged)

* feat(usage): reprocess + prune endpoints + scheduler daily prune job + CLI

* docs: PLATFORM_SETUP.md operator playbook + HOWTO/ cookbook (5 guides + index)

Adds docs/PLATFORM_SETUP.md as a consolidated operator playbook covering
bootstrap, TLS, marketplaces (curated + flea), scheduler env vars, telemetry
extraction/export/ask/prune, privacy posture, and daily routine.

Adds docs/HOWTO/ with 5 analyst cookbook guides: first query, snapshots for
remote tables, private sessions, feedback + admin ask, and customizing skills.

Existing setup docs (QUICKSTART, DEPLOYMENT, ONBOARDING, HEADLESS_USAGE)
get a one-line cross-reference at the top pointing to PLATFORM_SETUP.md.

* docs(changelog): platform telemetry epic — usage_* foundation + surfaces + admin access + docs

Comprehensive [Unreleased] entry covering: usage_events/session_summary/
tool_daily/plugin_daily tables (v41), attribution lookup tables, backfill
script, marketplace Most Popular + invocation chips + sort, admin Sessions
section, export/ask/reprocess/prune endpoints + CLI mirrors, Activity Center
(v40), PLATFORM_SETUP.md + HOWTO/ docs, and operations notes for v41 upgrade.

* fix(security): block DuckDB read_*/http_*/glob functions in usage_ask validator + symlink escape guard in session zip + clarify mark-private semantics

* fix(admin): parquet export tempfile cleanup on COPY failure + correct processed-first sort on /admin/users/<id>/sessions

* feat(audit): close 8 production audit gaps — query (local/remote/hybrid), catalog/schema/sample, snapshot estimate/create, check-access

* feat(ui): /admin/usage summary dashboard + per-user activity tab on /admin/users/<id>

* fix(audit): cap error messages at 200 chars + audit user_activity reads + recursion guard on usage.summary

* fix(audit): catalog.list audits on error path + clean up deferred json import

* fix(ux): client_kind=cli for PAT auth + timeline empty state + email-instead-of-uuid + nav reorder + help text + loading indicators + ask doc

* feat(observability): unify /admin/activity into single page with saved views

- KPI cards (events, users, error rate, p95) clickable as quick-filters
- Faceted filter dropdowns populated from audit_log in the current window
- Sortable audit table, cursor pagination, per-row JSON side panel
- Saved views (schema v43: user_observability_views) — per-user state
- Top bar: window selector + 30s Live toggle + saved views dropdown
- /admin/scheduler-runs → 308 redirect (source=scheduler filter)
- New endpoints: /api/admin/observability/{facets,kpis,views}

* test: update activity + scheduler-runs tests for unified page

- test_admin_activity_page_renders asserts new structural anchors
- test_admin_scheduler_runs_page_admin_only asserts 308 redirect

* fix(observability): respect [hidden] on modal + side panel

CSS `display: flex` on .obs-modal beat the [hidden] attribute's UA
display:none, so the save-view modal rendered on page load and Cancel
clicks couldn't dismiss it. Gate the modal's flex layout on
:not([hidden]); add the same display:none guard prophylactically to
.obs-panel and .obs-views-panel.

* feat(observability): user enrichment in audit + interactive /admin/usage

Activity:
- /api/admin/activity now joins users for user_email + user_name per row
- User column renders "name (id-prefix)" or "email (id-prefix)" instead
  of an opaque truncated UUID; falls back to id when the user record is
  missing

Usage:
- /admin/usage rewritten as the same filter/group-by/search pattern as
  /admin/activity. Faceted dropdowns (User / Tool / Source / Event type)
  populated from usage_events; debounced free-text search across
  tool_name / skill_name / subagent_type / command_name
- New endpoints /api/admin/usage/{facets,kpis,query}; the query endpoint
  supports group_by in {day, username, tool_name, source, ref_id} with
  sort + offset pagination, plus an ungrouped raw-events mode
- 4 KPI cards (events, distinct users, distinct tools, error rate) are
  clickable quick-filters; clicking a grouped row applies the bucket as
  a filter
- Old static `?window=7d|30d|all` server preload removed; all state is
  client-side via since_minutes + group_by + filters in the URL

* fix(observability): clearer labels, all-column sort, drop saved views UI

- Rename page titles: "Activity" → "Server activity", "Usage" → "Tool usage"
  with a one-line subtitle on each explaining what the page covers and
  linking the other one. The two pages source different data (audit_log
  vs usage_events) and the previous labels conflated them.
- Drop the saved-views dropdown + save modal from /admin/activity. The
  modal pop-open bug was the trigger; the value wasn't there yet. The
  /api/admin/observability/views CRUD + DuckDB table stay in place.
- Rename "Live (30s)" to "Auto-refresh (30s)" with a tooltip clarifying
  that it's the re-fetch rate, not the time range. Time range now
  labeled "Time range" instead of "Window".
- All audit-table columns are sortable (User, Source, Action, Resource,
  Result added); sort is page-local with a Jinja comment explaining the
  trade-off. Same for raw usage rows.
- Fix duplicate sort-arrow bug — the literal "▼" in the Time th HTML was
  rendering alongside the CSS ::before arrow. Removed the literal; CSS
  is the single source of truth.

* feat(observability): global Sessions browser + transcript viewer + CLI

Web:
- /admin/sessions — list every collected session JSONL across all users
  with time-range, user, model, errors-only and free-text filters. Default
  sort surfaces error-heavy sessions first. KPI cards (sessions, distinct
  users, sessions w/ errors, tool error rate) clickable as quick-filters.
- /admin/sessions/<username>/<file> — transcript viewer rendering the
  JSONL chronologically: user prompts, assistant text, tool calls (with
  JSON input) and tool results (with flattened output). Errors get a red
  border + chip and a "Next error" navigation button at the top.
- Admin dropdown gains a "Sessions" link.

API:
- GET /api/admin/sessions/{list,kpis,facets} — filtered cross-user reads
  off usage_session_summary
- GET /api/admin/sessions/{username}/{file}/transcript — parses JSONL via
  the existing services.session_pipeline.lib, returns chronological events
- GET /api/admin/sessions/{username}/{file}/download — JSONL stream, same
  path-safety guards as the per-user endpoint, audit-logged

CLI:
- `agnes admin sessions list [--user X] [--errors] [--since 7d]` — table
  output with `!` prefix on rows that hit a tool error
- `agnes admin sessions show <username> <file>` — transcript dump, with
  `--errors` to print only the failed tool_result blocks
- `agnes admin sessions download <username> <file> [-o path]`
- `agnes admin sessions kpis` — top-level numbers

* feat(internal): expose telemetry tables to agnes query with row-level RBAC

Three new registered tables backed by system.duckdb, queryable through
the same /api/query plumbing analysts use for Keboola / BigQuery /
local sources:

  agnes_sessions  → usage_session_summary  (filter: username)
  agnes_usage     → usage_events           (filter: username)
  agnes_audit     → audit_log              (filter: user_id)

RBAC is per-row, not per-table: admins see every user's rows; non-admins
see only their own. The filter is built server-side from the auth user
dict; non-admin filter values are regex-validated before SQL interpolation.

Implementation:
- new connector connectors/internal/ with access (filter+exec) + registry
  (idempotent table_registry seed at startup)
- /api/query detects internal table refs and short-circuits to a CTE
  wrapper that prepends "WITH agnes_x AS (SELECT * FROM <src> WHERE …),
  …" then "SELECT * FROM (<user_sql>) AS _q". DuckDB cursor on the
  shared system.duckdb handle — opening parallel handles / ATTACH on the
  same file is blocked process-wide.
- mixing internal + BQ / registered local tables in one SELECT is
  rejected (v1 limitation)
- src.rbac.can_access_table waves internal tables through for all
  authenticated users; row scoping is the actual security control
- /api/v2/schema and /api/v2/sample gained internal branches; sample
  intentionally skips its cache because rows are RBAC-scoped per caller
- audit row written as action='query.internal' with is_admin flag

Tests: connectors/internal/access — RBAC, filter clause, schema, CTE
wrapper coexistence with user-supplied aggregations, unsafe-username
rejection. 16/16 passing.

Motivating queries this enables:
  SELECT tool_name, COUNT(*) FROM agnes_usage
   WHERE is_error GROUP BY 1 ORDER BY 2 DESC
   -- analyst self-introspection: which tools fail for me?

  SELECT user_id, COUNT(*) FROM agnes_audit
   WHERE action = 'session.transcript_view' GROUP BY 1
   -- admin: who's been looking at whose session transcripts?

* feat(admin): group dropdown into 5 named sections + internal tables in /catalog

Admin dropdown gains section headers so admins can land on the right
page without re-reading the full menu:

  Activity Center      Server activity / Tool usage / Sessions
  Users & Access       Users / Groups / Resource access / Tokens
  Data                 Tables
  Agent Experience     Curated Marketplaces / Flea Submissions /
                       Agent Setup Prompt / Agent Workspace Prompt
  Server               Server config

"Agent Experience" frames the curated content + prompts as one cluster
— it's all admin-controlled material that shapes what an analyst's AI
agent encounters. "Configuration" → "Server" since only one item lives
there now.

Renamed the section's first two items:
  "Activity" → "Server activity" (matches page H1)
  "Usage"    → "Tool usage"

Also fixes /catalog visibility of the internal tables (agnes_sessions /
_usage / _audit) for non-admin users: ``app.auth.access.can_access``
short-circuits to True for resource_type='table' + an internal-table id.
Without this, non-admins saw the tables in /api/v2/catalog (which uses
the same RBAC bypass) but not on the /catalog HTML page (which calls
can_access directly, requiring a resource_grants row internal tables
don't have).

CSS for `.app-nav-menu-section`: small caps, muted, non-clickable; first
section trims top padding so the panel doesn't open with an awkward gap.

* refactor(admin): move corporate memory into Admin > Agent Experience

Memory link was the only admin-only entry in the primary nav (gated by
session.user.is_admin). Moves it into the Admin dropdown under Agent
Experience, alongside Curated Marketplaces / Flea Submissions / Prompts
— all admin-curated content that shapes what an analyst's AI agent
encounters.

Renamed the nav label to "Shared Knowledge" to match what the page
actually is (admin-curated organisational knowledge from session
verification, surfaced to agents). URL stays at /corporate-memory; the
route still gates on require_admin per the existing comment.

Side effect: primary nav (Home / Marketplace / Data Packages) is now
uniform for every authenticated user — no conditional admin-only entry.

* ui: rename admin entries to Curated Knowledge / Init Prompt / Workspace Prompt

- "Shared Knowledge" → "Curated Knowledge" (parallel with "Curated
  Marketplaces" in the same Agent Experience section; "curated" tells
  the admin what they do there — review + approve)
- "Agent Setup Prompt" → "Init Prompt" (matches the `agnes init` flow
  it actually drives)
- "Agent Workspace Prompt" → "Workspace Prompt" (the "Agent" prefix
  was redundant — every item in the section is agent-facing)

Renames page titles + H1s on /admin/agent-prompt and
/admin/workspace-prompt to match.

* refactor: rename Usage → Telemetry across user-facing surfaces

External surfaces all switch; internal Python module / file names and the
physical DB tables (usage_events, usage_session_summary, usage_tool_daily,
usage_plugin_daily) stay — renaming them would force a schema migration
+ a redo of the LLM Text-to-SQL prompt for no analyst-visible win.

Changes:
- Admin dropdown: "Tool usage" → "Telemetry"
- Page H1 / <title>: same
- URL: /admin/usage → /admin/telemetry; old URL 308-redirects
- API prefix: /api/admin/usage/* → /api/admin/telemetry/*
- CLI: primary command `agnes admin telemetry …`; `agnes admin usage` kept
  as a deprecated alias so existing operator scripts keep working
- Internal data-source table id: agnes_usage → agnes_telemetry. The
  registry seed now evicts any stale internal-source row whose id no
  longer matches INTERNAL_TABLES, so the old `agnes_usage` row is
  removed from table_registry on next app boot
- All tests + JS endpoint paths updated

* test(rbac): include auto-appended internal tables in expectations

get_accessible_tables now appends agnes_sessions / agnes_telemetry /
agnes_audit to every authenticated user's accessible-tables list so the
internal data source shows up in /catalog. The two existing rbac tests
asserted hardcoded list shapes that pre-dated the change.

Rewritten to assert "granted tables + the canonical internal-table set"
instead of literal lists, so the test stays correct if the internal
table roster changes again later.

* ui: visual dividers between admin-dropdown sections

Adds a 1px top border + 6px top margin to every section header except
the first, so the five named groups (Activity Center, Users & Access,
Data, Agent Experience, Server) read as visually separated clusters.
The header itself stays small-caps + muted as before — the border is
additive.

* ui(memory): match obs-topbar visual on /corporate-memory

The Curated Knowledge page (linked from the admin dropdown's Agent
Experience section) opened straight into the stats bar — no title,
no subtitle, no shared chrome with the other admin pages. Adds an
obs-topbar-style header at the top of .container-memory:

  - H1 "Curated Knowledge"
  - subtitle explaining what the page is + how AI agents pull from it

The `.ck-*` class set duplicates the inline obs-* styles from
/admin/activity etc. for this one page; promoting the obs-* class set
to style-custom.css for shared reuse is the obvious next step (4 pages
already inline the same CSS), tracked as a follow-up.

Page <title> also renamed from "Corporate Memory" → "Curated Knowledge".

* ui(tables): list Agnes internal tables in /admin/tables + group in /catalog

/admin/tables previously rendered three per-source-type listings
(BQ / Keboola / Jira) and dropped any row whose source_type didn't
match — so the agnes_sessions / agnes_telemetry / agnes_audit rows
seeded into table_registry were invisible. Adds a fourth read-only
section "Agnes internal tables" that filters source_type === 'internal'
and renders the same registry-table layout the other sections use,
with two changes:

  - no Register button (these rows are seeded on every app boot from
    connectors/internal/registry.py)
  - Edit + Delete actions hidden (any change would be reverted on the
    next start). Manage access stays so admins can still inspect.

Mode badge picks up a new mode-internal CSS class (teal accent) so the
display doesn't lie and call it "local".

In /catalog, internal tables now group under an "agnes" accordion
section (bucket="agnes" on seed) instead of falling into the catch-all
"default". Single source of truth for which tables exist; admins find
them where they expect.

* ui(tables): Agnes internal as a 4th tab next to BQ/Keboola/Jira

Previous iteration mounted the internal-table listing as a separate
standalone card under the tab strip. Reshapes it to a proper
tab-content section so admins switch between data sources via one
consistent nav (BigQuery / Keboola / Jira / Agnes internal).

- New tab button "Agnes internal" in the tab-nav.
- The listing card becomes <section id="tab-content-internal"
  class="tab-content">; switchTab() already routes by id so no JS
  change beyond extending the hash allowlist for direct #internal
  links.
- Tab content keeps the read-only treatment from the previous commit
  (no Register button, no Edit / Delete in renderRegistryListing).

* ui: rename Curated Knowledge → Curated Memory

Settles the naming back on "Curated Memory" — parallel structure with
"Curated Marketplaces" in the same Agent Experience section, and zero
rename ripple: URL (/corporate-memory), API (/api/memory/*), CLI
(agnes admin memory), and Python modules all stay on "memory" so the
admin label finally lines up with the underlying surfaces.

The "Curated" prefix still tells admins what they do on the page
(review pending → approve / mandate / reject) and reads as a sibling
of "Curated Marketplaces" right next to it in the dropdown.

Touches: admin dropdown label, page <title>, page H1. DB tables stay
on knowledge_* (already the canonical naming for the data shape).

* ui: rename "Server activity" → "Audit log"

"Audit log" is what the page actually is — server-side audit_log table
rendered with KPI cards + filter bar + sortable table. The "Server
activity" label confused the term with Claude Code session telemetry
(Telemetry page) and didn't make the source/concept clear.

Touches:
- Admin dropdown nav label
- /admin/activity page H1 + subtitle
- /admin/telemetry subtitle cross-link
- test_activity_api page-renders assertion

URL (/admin/activity) and API (/api/admin/activity/*) stay — the
"activity" name has stuck at the route layer for a year; rerouting
those would churn dashboards/bookmarks for zero analyst-visible win.

* ui(admin-nav): gray band on each section header for clearer separation

Previous iteration used a 1px top border between section labels — the
labels still blended into the items above/below at a glance. Switches
to a light gray background band per section header, extended edge-to-
edge inside the panel via negative horizontal margins. Bolder
font-weight (700) reinforces the separation; bumping the font color
isn't needed because the band itself does the work.

First section's header tucks into the panel's top border-radius so the
band reaches the corners without a gap.

* ui(catalog): rename internal-table category to "Agnes Internal"

`bucket` is what /catalog renders as the accordion category header
verbatim — "agnes" lowercase didn't read as a real category name and
got confused with a system identifier. Bumps to "Agnes Internal".
Seed re-applies on every app boot so existing rows pick up the new
bucket value via `ON CONFLICT (id) DO UPDATE`.

* ui(catalog): split Agnes Internal into its own card on /catalog

Previously the three internal tables landed inside the "Core Business
Data" card under an "Agnes Internal" accordion alongside Keboola / BQ
buckets — readers conflated system telemetry with business datasets,
and the data_stats header counter ("3 tables · ~X rows total") only
ever counted synced rows so internal tables looked invisible.

Split the catalog page into two cards:
- Core Business Data: only non-internal source_types (Keboola, BQ,
  Jira). Accordions group by bucket as before. Stats counter reflects
  this card's tables.
- Agnes Internal: a dedicated card with its own visual treatment
  (teal accent matching the mode-internal badge in /admin/tables).
  Flat list (no accordion — only 3 rows, never grows here), each
  row carries the canonical `agnes query` snippet. Read-only — no
  profiler click, no In-stack toggle, no sync metadata.

Route adds `internal_card` context object; template renders the new
card only when it's non-None.

* fix(rbac): hide internal tables from /admin/access + drop "my" framing

Two related cleanups for the Agnes-internal tables:

1. /admin/access (resource grants) no longer lists them. The
   `can_access` check has a hardcoded internal-table bypass — security
   is row-level (per-request view filter), so a table-grain
   `resource_grants` row would do nothing. Surfacing them in the UI
   let admins set up grants that silently no-op. Filter at the
   `_table_blocks` projection so the UI tree never sees them.

2. Display names drop the analyst-perspective "my" framing:
     "Agnes — my sessions"          → "Agnes sessions"
     "Agnes — my telemetry events"  → "Agnes telemetry events"
     "Agnes — my audit log"         → "Agnes audit log"
   The "my" only makes sense from the querying analyst's seat
   (`SELECT … FROM agnes_sessions` returns *their* rows); on /admin/*
   pages where admin sees / configures them across users, the
   pronoun was misleading. Description text now spells out the
   row-level RBAC contract explicitly.

Display names update via TableRegistryRepository.register's ON CONFLICT
UPDATE on next app boot; no manual cleanup needed.

* ui: subtitle notes about agnes_* tables on each Activity Center page

The recursive observability story — Agnes serves its own audit /
telemetry / session data through the same `agnes query` plumbing
analysts use for business data — wasn't surfaced anywhere on the
admin pages that show that data. Three pages get a one-liner with
the canonical `agnes query` snippet + the RBAC contract (analysts
see their own rows, admin sees all):

- /admin/activity (Audit log)   → agnes_audit
- /admin/telemetry (Tool usage) → agnes_telemetry
- /admin/sessions               → agnes_sessions

Sets up the discovery moment for admins: they're reading the page,
they see "you can query this from Claude Code", they remember it
when an analyst asks "how do I find my own failed tool calls?".

* ui(tables): explain "Show log" empty-state on /admin/tables

Cache warmup log <pre> renders with a dark background and is only
populated by the SSE stream during a Re-warm all run. Opening the
page cold + clicking Show log just revealed a black bar with no
context — admins couldn't tell what they were looking at.

Adds an inline paragraph above the <pre> explaining what the log is,
the row format, when it fills in, and where to find the historical
audit trail (/admin/activity). The actual <pre> stays empty until
SSE events arrive, but the surrounding copy carries the meaning.

* ui(tables): auto-open cache-warmup log on Re-warm all click

A Re-warm all run takes ~24s per remote BQ row. With the <details>
collapsed by default, operators saw the button disable, watched a
quiet ~24s pass, and assumed nothing had happened — the streaming
log was hidden behind a closed disclosure.

Two small JS tweaks:
- cacheWarmupRun() opens the details on click, so streamed lines
  appear without an extra interaction
- cacheWarmupOnStart() hides the inline hint paragraph the moment
  real log content lands, so the dark log block isn't competing
  with redundant context

Hint paragraph also clarifies that only `query_mode='remote'` BQ
rows are warmed — operators with only materialized/internal tables
would see total=0 and the page would "do nothing" by spec.

* ui: trim Agnes internal copy across surfaces

Descriptions had grown to explain the extraction pipeline ("parsed
out of session JSONLs"), the underlying table ("Backed by
usage_session_summary"), the RBAC mechanic ("row-level RBAC at query
time — analysts see their own; admin sees all"), and the SQL snippet.
Every implementation detail meant another rewrite on the next iter.

Strips to one stable line per surface: what the data is, plus
"Also available locally for analysis". Mechanics live in code +
docs; the page copy says what the user needs to know.

Touched:
- connectors/internal/access.py: INTERNAL_TABLES descriptions
- activity_center.html / admin_usage.html / admin_sessions.html
  subtitles
- catalog.html Agnes Internal card description + row strip
- admin_tables.html "Agnes internal" tab hint

* fix(internal): is_user_admin arity bugs + + saved-view payload cap

Round-1 code review (PR #278) caught two blocking bugs and three nits.

Blocking — both `is_user_admin(user)` (single dict arg) calls raised
TypeError. is_user_admin signature is `(user_id, conn)`. Affected:

- app/api/query.py:_run_internal_query — every POST /api/query that
  references agnes_sessions / agnes_telemetry / agnes_audit blew up
  with a 500. The headline analyst-facing feature of this PR was
  unusable through the API.
- app/api/v2_sample.py — same shape; `GET /api/v2/sample/agnes_*`
  returned 500.

Both fixed to call `is_user_admin(user.get("id"), conn)`. Added two
FastAPI-level tests in test_internal_data_source.py that go through
the TestClient — the existing unit tests on `execute_internal_query`
and `build_filter_clause` skipped the request-handler layer where the
bugs lived, which is why this landed.

Nits also closed:
- connectors/internal/access.py: `+` allowed in _USERNAME_RE /
  _USER_ID_RE so RFC 5321 email local-parts (alice+test@x) resolve
  correctly without hitting InternalAccessError.
- app/api/observability.py: saved-view payload capped at 64 KiB to
  prevent an admin from bloating system.duckdb with a malformed save.

* fix(security): close non-admin data-leak via underlying-table refs

PR #278 R2 review surfaced a non-admin-exploitable bypass: SQL whose
string literal contains 'agnes_sessions' routed into the privileged
internal-query path, then queried the underlying physical table
(usage_session_summary / usage_events / audit_log) directly, escaping
the CTE wrapper's row filter. Two reinforcing defenses:

1. find_internal_refs() now strips single-quoted string literals
   before scanning for alias names — a literal alone no longer
   routes the request into the privileged code path.

2. execute_internal_query() rejects non-admin SQL that references
   the underlying physical tables (usage_*, audit_log). The CTE
   wrapper only scopes the agnes_* aliases; a direct FROM on the
   base table — or a shadowing inner WITH that still has to read
   the base table — bypasses RBAC. Block before execution with an
   actionable error pointing to the agnes_* alias. Admins are
   unaffected (god-mode short-circuit on the filter clause).

3. tests/test_internal_data_source.py — three new negative tests
   covering literal-only matches, direct-table refs, and CTE
   shadow attempts.

Also tightens usage_ask.py's SELECT-only validator: pragma_table_info,
pragma_storage_info, pragma_database_*, and duckdb_tables / columns /
views / indexes / schemas are reflection functions that leak metadata
the analyst question shouldn't reach. \bPRAGMA\b in _FORBIDDEN never
matched the function-call form (word-boundary between `A` and `_`).

* fix(security): dynamic denylist for non-admin internal queries

R3 review (PR #278) caught a wider data-leak than R2: the underlying-
physical-table guard listed only the 7 usage_* + audit_log tables,
but system.duckdb has 30+ other sensitive tables — users (emails +
ids), personal_access_tokens, resource_grants, user_groups,
user_observability_views, store_*, marketplace_*, knowledge_*, etc.
A non-admin SQL like

    SELECT * FROM agnes_sessions
    UNION ALL SELECT email, id, … FROM users LIMIT 1

would leak every user's row.

Replaces the hardcoded denylist with a **dynamic allowlist** —
non-admin SQL may reference ONLY the registered agnes_* aliases.
Every other table in `information_schema.tables` (main schema) is
rejected. Future migrations that add a new sensitive table are
automatically covered without re-editing this module.

Also strips SQL comments (`/* */` and `--`) before the identifier
scan so a comment-wrapped table name (`/**/users/**/`) can't slip
past the regex.

Four new negative tests pin: `users`, `personal_access_tokens`,
block-comment wrap, line-comment wrap.

Plus: per-user view-count cap (100) on /api/admin/observability/views
so an admin can't fill system.duckdb with thousands of saved views.

* release: 0.54.0 — Activity Center + Telemetry + Sessions + internal datasource

Cuts the work shipped across this PR (Activity Center build, recursive
internal data source) into a versioned release. Bumps pyproject.toml
to 0.54.0; renames the top of CHANGELOG.md from [Unreleased] to
[0.54.0] — 2026-05-12 with a header summary; opens a fresh
[Unreleased] section for the next round.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 22:41:19 +02:00

27 KiB
Raw Blame History

Admin Observability — parent spec

Status: spec / discussion. Verified against origin/main at 65342cd1 (release 0.49.0). Schema v39. Worktree: tmp_oss-activity-spec.

Children (executable plans):

  • 2026-05-11-activity-center-mvp.md — Activity Center rebuild + audit gap closure (this PR)
  • (next) 2026-05-NN-admin-sessions.md/admin/sessions + failure_scan processor
  • (next) 2026-05-NN-feedback-inbox.mdagnes report CLI + /admin/feedback + Claude skill

1. Why this exists

Agnes today has dozens of moving server-side processes — scheduler ticks, syncs, materialized BQ runs, marketplace clones, memory pipeline, RBAC mutations, PAT issuance, session uploads, queries. Some land in audit_log, some in sync_history, some only in container stdout, some nowhere.

An admin who asks "is my Agnes instance healthy and what happened?" today does one of three things:

  1. SSHs into the VM and docker logs across containers.
  2. Opens DuckDB directly with duckdb /data/state/system.duckdb.
  3. Clicks through five separate admin pages (/admin/scheduler-runs, /admin/tokens, /admin/access, /admin/marketplaces, /admin/users) and stitches the picture together.

/activity-center was supposed to fix this. It doesn't — the template renders fake "Executive Pulse / Maturity Roadmap / Business Processes" sections fed by an empty handler context. Issue #206.

This spec rebuilds it as /admin/activity and adds two adjacent observability surfaces:

  • /admin/sessions — admin browses Claude Code session transcripts across users, finds failure patterns ("where Claude got stuck so we can fix the CLI / setup prompt / skill"). New failure_scan processor in the existing services/session_pipeline/ framework.
  • /admin/feedback — inbox for explicit user-reported problems. New agnes report CLI command + Claude skill + new feedback_reports table.

The three surfaces together turn Agnes from a black box into a glass box for operators.


2. Audience model (no personas, just resources + RBAC)

Per v13 RBAC, the only hard distinction is is_admin=true (god-mode) vs. everyone else. We do not introduce new role bits. Instead we frame everything as resources that admins control via existing resource_grants. When the spec says "admin sees X" it means "the page is gated by require_admin; admin can later grant the underlying resource to other groups if the customer asks".

Resources used / introduced

Resource Read-own surface Manage-all surface New / existing
Server operations (audit_log + sync_history + session_processor_state) /admin/activity rebuilt
Session transcripts (${DATA_DIR}/user_sessions/<user>/*.jsonl) /profile/sessions /admin/sessions NEW page
Failure findings (new session_findings table) tab in /admin/sessions NEW table
User feedback (feedback_reports table — NEW) (write-only via agnes report) /admin/feedback NEW
All others various existing pages various existing pages unchanged

3. Non-goals

  • Replacing /admin/diagnose. Different question (current state vs. history).
  • Strategic / exec value-reporting. The current template's "maturity roadmap" / "decisions supported" framing is deleted.
  • Live streaming (SSE / WebSocket). Polling every 30s is enough.
  • Cross-instance / fleet view.
  • Mandatory LLM features. Activity Center works fully without PostHog or any external service.
  • Analyst-side /profile/activity. Their existing /profile/sessions is already their personal audit trail in practice; adding a third profile page is not justified.

4. State on origin/main — verified facts the spec depends on

4.1 Schema (src/db.py:43)

SCHEMA_VERSION = 39

Tables relevant to this work:

  • audit_log (id, timestamp, user_id, action, resource, params JSON, result, duration_ms) — the primary event source. 30+ writer call sites today.
  • sync_history (id, table_id, synced_at, rows, duration_ms, status, error) — per-table sync events.
  • session_processor_state (processor_name, session_file, username, processed_at, items_extracted, file_hash) — composite PK (processor_name, session_file). Per-processor checkpoint.
  • verification_evidence, knowledge_items, knowledge_contradictions, knowledge_item_relations — memory pipeline output (read-only for AC).
  • telegram_links (user_id PK, chat_id, linked_at) — for admin notifications.
  • users, user_groups, user_group_members, resource_grants — RBAC.
  • instance_templates (singleton template store from earlier PRs; #246 proposes folding it into a unified content store, not yet built).

4.2 session_pipeline framework (services/session_pipeline/contract.py)

@dataclass(frozen=True)
class ProcessorResult:
    items_count: int = 0

class SessionProcessor(Protocol):
    name: str
    cadence_minutes: int
    def process_session(
        self,
        session_path: Path,
        username: str,
        session_key: str,
        conn: duckdb.DuckDBPyConnection,
    ) -> ProcessorResult: ...
  • Runner: services/session_pipeline/runner.py. Idempotent per (processor_name, session_file, file_hash).
  • Registry: services/session_processors/__init__.py:PROCESSORS = {"verification": …, "usage": …}.
  • Scheduler invokes: POST /api/admin/run-session-processor?processor=<name> (env-overridable interval per processor, e.g. SCHEDULER_USAGE_PROCESSOR_INTERVAL=600).

Implication: failure-scan is a third processor following the same protocol. No new framework code.

4.3 Audit coverage gaps (verified)

These endpoints exist today and do not write audit_log:

Endpoint File Reason needed in AC
POST /api/sync/trigger app/api/sync.py:772 The dominant scheduler-fired action; today only the call to the scheduler endpoint is audited, not what actually ran.
POST /api/scripts/run-due app/api/scripts.py:138 Custom user scripts running on-server with no trail.
POST /api/query + variants app/api/query.py:140+ Analyst queries — invisible without #158.
POST /api/query-hybrid app/api/query_hybrid.py Same.
POST /api/upload/sessions app/api/upload.py:55 Session push — invisible.
GET /api/data/{table_id}/download app/api/data.py:45 Parquet pulls — invisible.

The MVP closes the four non-query gaps. Query attribution (#158) is its own scope.

4.4 PostHog (src/observability/posthog_client.py)

Singleton get_posthog(), methods:

  • .capture(event: str, distinct_id: str, properties: dict | None) -> None
  • .capture_exception(exc, distinct_id, request, properties) -> None
  • .is_feature_enabled(key, distinct_id, default) — usable for opt-in feature flags inside AC

Off by default (POSTHOG_API_KEY unset). All call sites must be no-op-safe.

4.5 Telegram (services/telegram_bot/sender.py)

async def send_message(chat_id: int, text: str, parse_mode: str = "Markdown") -> bool

Lookup telegram_links row by user_id. No existing admin notification flow — feedback inbox is its first user.


5. Architecture decisions

5.1 Where the three surfaces live

/admin/activity     ← rebuilt /activity-center (this PR)
/admin/sessions     ← NEW (follow-up plan)
/admin/feedback     ← NEW (follow-up plan)

All three:

  • Gated by Depends(require_admin) — no new resource type for now.
  • Listed in _app_header.html admin dropdown.
  • Share a common drawer / detail-modal pattern (one Jinja partial reused).
  • Share the same audit-recursive rule: reading from these endpoints itself writes one audit_log row.
  • Each gets a top-of-page health micro-summary that links to the Activity Center health pulse.

5.2 Data — separate change_log vs. fattened audit_log

Decision: fatten audit_log with two new columns.

Rationale: Adding a separate change_log table requires every mutating endpoint to write to two places, doubling the failure modes. The audit_log row IS the change log entry, plus params_before for diff/rollback purposes. The vast majority of audit rows are non-mutations (reads, ticks, queries) where params_before is null — null storage cost in DuckDB is trivial.

Schema migration v40:

ALTER TABLE audit_log ADD COLUMN params_before JSON;       -- prior state, null for non-mutations
ALTER TABLE audit_log ADD COLUMN client_ip VARCHAR;        -- promoted from params for indexability
ALTER TABLE audit_log ADD COLUMN client_kind VARCHAR;      -- 'cli' | 'web' | 'agent' | 'scheduler' | 'external'
ALTER TABLE audit_log ADD COLUMN correlation_id VARCHAR;   -- groups multi-step operations
CREATE INDEX idx_audit_timestamp_desc ON audit_log(timestamp);
CREATE INDEX idx_audit_user_time ON audit_log(user_id, timestamp);
CREATE INDEX idx_audit_action_time ON audit_log(action, timestamp);

AuditRepository.log() gains the four new kwargs. Existing callers compile-time-unbroken (kwargs default to None).

Operational note (reviewer pass): DuckDB does not honor DESC in CREATE INDEX — the planner picks direction at query time. The _desc suffix in the index name is informative, not directive. Direction is enforced by ORDER BY ... DESC in AuditRepository.query().

Upgrade window (reviewer pass): index creation on a populated audit_log (>100k rows) is single-threaded and may take 3060s per index. Customers upgrading to v40 should expect a 30120s startup window on first launch. CHANGELOG entry for v40 must call this out.

5.3 Filtering & pagination

AuditRepository.query() today supports user_id, action, limit. Rewrite to:

def query(
    self,
    *,
    since: datetime | None = None,
    until: datetime | None = None,
    user_id: str | None = None,
    action_prefix: str | None = None,   # 'sync.', 'query.', 'auth.', …
    action_in: list[str] | None = None,
    resource: str | None = None,
    result_pattern: str | None = None,  # 'success', 'error.%'
    correlation_id: str | None = None,
    q: str | None = None,                # full-text over params JSON
    cursor: tuple[datetime, str] | None = None,  # (timestamp, id)
    limit: int = 100,
) -> tuple[list[dict], tuple[datetime, str] | None]:
    ...

Returns (rows, next_cursor). Cursor encodes (timestamp, id) to make pagination stable under same-second writes. All filters AND together. q does LIKE '%substring%' on params::TEXT for v1; FTS upgrade is later.

5.4 Health pulse

Single endpoint GET /api/admin/activity/health returning a JSON dict cached server-side 30s:

{
  "status": "green | yellow | red",
  "fields": [
    {"key": "scheduler", "value": "47s ago", "raw_seconds": 47, "color": "green", "click_filter": "action_prefix=run_"},
    {"key": "sync_24h", "value": "18 ok / 2 fail", "ok": 18, "fail": 2, "color": "yellow", "click_filter": "action_prefix=sync."},
    {"key": "active_users_today", "value": "12", "color": "green"},
    {"key": "memory_pipeline", "value": "ok (3 runs)", "color": "green", "click_filter": "action_prefix=run_session_processor"},
    {"key": "diagnose_warnings", "value": "0", "color": "green"}
  ],
  "sentence": "All systems nominal — 12 active users, last sync 4 min ago, no warnings."
}

Thresholds in code, not config. Acceptance: each field can be tested deterministically by seeding audit_log / sync_history and frozen-clock fixtures.

5.5 What gets MVP and what gets P2

Activity Center tab MVP (this PR) Phase B Phase C
Health pulse
Timeline params_before diff
Sync (per-table grid)
Changes (mutations) ✓ (read-only diff) rollback
Queries ✓ (gated on #158)
Performance
Usage (DAU/WAU)
Costs

5.6 /admin/sessions — failure_scan processor

New file services/session_processors/failure_scan.py. Heuristics (deterministic, no LLM in v1):

Signal Detection
Tool error turn with tool_use followed by tool result containing is_error: true / exit code [1-9]
Permission denied tool result contains permission denied (case-insensitive)
User rejection user turn matching regex `\b(no
Loop pattern 3+ consecutive assistant turns with same tool_use.name and similar input hash
Abrupt end last turn role=user (never closed by assistant)

Writes findings to NEW table session_findings:

CREATE TABLE session_findings (
    id VARCHAR PRIMARY KEY,
    session_file VARCHAR NOT NULL,
    username VARCHAR NOT NULL,
    finding_type VARCHAR NOT NULL,    -- tool_error | permission_denied | user_rejection | loop | abrupt_end
    turn_index INTEGER NOT NULL,
    severity VARCHAR DEFAULT 'info',   -- info | warning | error
    excerpt TEXT,                      -- short context for UI display
    detected_at TIMESTAMP DEFAULT current_timestamp
);
CREATE INDEX idx_session_findings_session ON session_findings(session_file);
CREATE INDEX idx_session_findings_type ON session_findings(finding_type);

Admin UI (/admin/sessions):

  • List view: one row per session JSONL file, sortable by recency / # findings / user, filters: user, date range, has finding of type X
  • Detail view: chronological replay of the session JSONL with finding markers inline; click a finding → highlights the relevant turn(s)
  • Aggregated view: heatmap "finding type × week" across all users

5.7 /admin/feedback — feedback_reports + agnes report

NEW table:

CREATE TABLE feedback_reports (
    id VARCHAR PRIMARY KEY,
    created_at TIMESTAMP DEFAULT current_timestamp,
    reporter_user VARCHAR,             -- nullable for anonymous (future)
    message TEXT NOT NULL,
    session_excerpt TEXT,              -- last N turns of JSONL serialized
    session_file VARCHAR,              -- pointer to full JSONL if uploaded
    environment JSON,                  -- agnes version, OS, claude code version
    fingerprint VARCHAR,               -- sha256 over (message + last error excerpt) for dedup
    status VARCHAR DEFAULT 'open',     -- open | triaged | resolved | wontfix
    assignee VARCHAR,
    tags JSON,                         -- ['cli', 'setup-prompt', 'skill-name', …]
    resolution TEXT,
    resolved_at TIMESTAMP,
    resolved_by VARCHAR
);
CREATE INDEX idx_feedback_status_created ON feedback_reports(status, created_at);
CREATE INDEX idx_feedback_fingerprint ON feedback_reports(fingerprint);

End-to-end flow:

  1. Analyst (or Claude proactively) runs agnes report --message "…".
  2. CLI bundles last 50 turns of current session JSONL (via cli/lib/claude_sessions.py:list_session_files) + env info.
  3. CLI shows preview ("This will be sent: …") and asks for confirmation. Mandatory — never silent submission.
  4. POST /api/feedback with the bundle.
  5. Server inserts row, computes fingerprint, writes audit_log(action='feedback.report'), returns report_id.
  6. Server triggers Telegram notification to all admin users with linked chat_id (best-effort, swallowed errors).
  7. Admin opens /admin/feedback, clicks row → modal with full message + session replay + env.
  8. Admin actions: assign to self, tag, mark resolved (with resolution text), mark wontfix.

Claude-side trigger: a first-party skill agnes-report (in the OSS marketplace) that bundles current session and invokes agnes report. Skill manifest lives in services/marketplace/oss/agnes-report/ (sibling to existing system plugins from #241).


6. Static content (CLAUDE.md template, copy on the new pages)

Issue #246 proposes a unified content framework. The MVP does NOT block on it — new pages embed copy directly in templates. When #246 lands, those strings move to instance_content slugs. Tracked as P2 follow-up; no migration debt incurred because the templates are small.


7. Security & privacy

7.1 Access

  • All /admin/activity/*, /admin/sessions/*, /admin/feedback/* endpoints: Depends(require_admin).
  • No new resource type. Admin god-mode for v1. Future: optional audit:read grant for a hypothetical "compliance" group.

7.2 PII in params

  • Default UI render: literal values in SQL strings masked to ? placeholders; literal strings elsewhere truncated to 128 chars.
  • "Show raw" toggle + audit.reveal_raw logging deferred to Phase B (reviewer pass): MVP ships with truncation-only display. The toggle UI + its dedicated audit action land alongside the Changes/Diff tab. Until then, admins who need raw values open DuckDB directly — that path itself does not leave a trace, which is documented as a known v40 gap.
  • Database always stores raw values. Masking is render-side, not storage-side.

7.3 Recursive audit

Every read of /admin/activity / /admin/sessions / /admin/feedback writes audit_log(action='activity.read' | 'sessions.read' | 'feedback.read'). Suppressed when:

  • Endpoint is the polling health endpoint (high-frequency, low signal).
  • Same actor + same filter combination within last 60s.

Reviewer note — single-worker assumption (v40): The suppression cache (_RECENT_AUDITS) and health-pulse cache (_HEALTH_CACHE) are per-process module-level dicts. v40 ships with the existing single-worker uvicorn default (no compose change required). When multi-worker uvicorn is later enabled, both caches move to a shared store — a separate plan tracks that. Until then, dedup is per-worker and a multi-worker deployment would let one bad actor produce N rows / minute instead of 1.

7.4 Feedback privacy

session_excerpt is included in the feedback payload. Skill / CLI must show preview before submit — this is a hard requirement, not a UX suggestion. Logged in audit_log(action='feedback.report', params={ack_preview: true}).

Server stores excerpts as text. Retention default unbounded; admin can purge feedback_reports row directly (still leaves audit_log trace).


8. Observability of observability

  • All new endpoints emit PostHog events when PostHog is enabled:
    • activity_health_viewed
    • activity_timeline_filtered (with filter keys, not values)
    • feedback_report_submitted
    • session_failure_detected
  • All swallowed errors posthog.capture_exception().
  • PostHog events are best-effort; never block the user-visible flow.

9. Phasing across subsystems

WEEK 1  ┌─ Activity Center MVP (this PR) ─────────────────────────┐
        │  - schema v40 (audit_log columns + indices)              │
        │  - AuditRepository.query() rewrite                       │
        │  - SyncHistoryRepository.list_recent()                   │
        │  - close 4 audit gaps (sync.trigger, scripts.run-due,    │
        │    upload.sessions, data.download)                       │
        │  - /admin/activity handler + template                    │
        │  - Health pulse + Timeline + Sync tabs                   │
        │  - redirect /activity-center → /admin/activity           │
        │  - delete demo template content (BREAKING)               │
        └──────────────────────────────────────────────────────────┘

WEEK 2  ┌─ Admin sessions (separate plan) ────────────────────────┐
        │  - schema v41 (session_findings table)                  │
        │  - services/session_processors/failure_scan.py          │
        │  - register in PROCESSORS + scheduler JOBS              │
        │  - /admin/sessions list + detail                        │
        │  - integrate with Activity Center timeline              │
        └──────────────────────────────────────────────────────────┘

WEEK 3  ┌─ Feedback inbox (separate plan) ────────────────────────┐
        │  - schema v42 (feedback_reports table)                  │
        │  - POST /api/feedback endpoint                          │
        │  - cli/commands/report.py                               │
        │  - agnes-report skill in OSS marketplace                │
        │  - /admin/feedback list + detail                        │
        │  - Telegram admin notifications                         │
        └──────────────────────────────────────────────────────────┘

WEEK 4+ ┌─ Phase B / C (separate plans) ──────────────────────────┐
        │  - params_before + Changes tab + Rollback (B)           │
        │  - Usage tab (B)                                        │
        │  - Queries tab gated on #158 (C)                        │
        │  - Performance tab (C)                                  │
        │  - LLM scoring in failure_scan (C)                      │
        │  - GitHub issue auto-file from feedback row (C)         │
        └──────────────────────────────────────────────────────────┘

Each weekly chunk is a separate PR with its own CHANGELOG entry. Order matters: Activity Center first because closing the audit gaps benefits the other two surfaces' timelines.


10. Open questions (decisions still owed)

  1. Rollback in Phase B — generic vs. allowlist? Recommendation: allowlist of 9 specific actions (instance_config.update, registry.update/create/delete, resource_grants.add/remove, user_groups.*, user_group_members.*, instance_templates.set). Generic rollback is a footgun.
  2. Telegram admin notification volume. Feedback reports could come fast. Recommendation: rate-limit per admin to 1 message / 5 min; daily digest for the rest. Configurable later.
  3. Session replay in feedback — store full JSONL or last 50 turns only? Recommendation: last 50 turns inline + pointer to full file if it still exists. Avoids storing duplicate JSONLs in the DB.
  4. agnes report always uploads the session, or opt-in? Recommendation: prompt every time. Power-users can add --yes to bypass; default is interactive.
  5. failure_scan LLM scoring in v1 or v2? Recommendation: v1 deterministic heuristics only. LLM scoring is v2 once we have data to validate heuristic precision against.
  6. /admin/scheduler-runs deprecation timing. Recommendation: keep as a redirect to /admin/activity?action_prefix=run_session_processor after MVP ships; remove after one release cycle.

11. What this displaces / replaces

  • /activity-center → redirected to /admin/activity. Demo template content deleted (BREAKING per CHANGELOG).
  • /admin/scheduler-runs → redirected to /admin/activity?action_in=run_session_processor:verification,run_session_processor:usage,marketplace.sync_all after week 1.
  • Dashboard widget pointing at /activity-center → URL updated to /admin/activity.

Nothing else removed. /admin/diagnose, /admin/tokens, /admin/access, /admin/marketplaces, /admin/registry, /admin/server-config remain as mutating surfaces; Activity Center deep-links into them.


12. Acceptance criteria for the whole programme (across all three subsystems)

When all three subsystems have shipped:

  1. An admin opening /admin/activity sees, within 500ms p95, a health pulse and a chronological timeline of every event on the instance for the last 24h.
  2. Every audit-writing endpoint (incl. the 4 newly instrumented in week 1) appears in the timeline within the same admin session as the action.
  3. An admin clicking on a sync event sees the sync_history detail; clicking on a feedback.report event sees the feedback row; clicking on a run_session_processor event sees the per-processor state row.
  4. An analyst running agnes report --message "test" produces a feedback_reports row, an audit_log row, a Telegram message to any admin with a linked chat_id, and visible entries in both /admin/feedback and /admin/activity.
  5. A Claude Code session that contains a tool error triggers a row in session_findings after the next failure_scan processor tick, surfaced in /admin/sessions.
  6. Removing the broken demo content from activity_center.html lands in a single PR with CHANGELOG **BREAKING** marker.
  7. All three pages render correctly with PostHog disabled (no events emitted, no client snippet injected for AC's own analytics, page works fully).
  8. Every new admin page passes a smoke test that asserts: invoking an audit-writing endpoint surfaces the row in the page's API response within the same test.

12a. Reviewer pass — applied & deferred

Three sub-agent reviews (security, production resilience, code architecture) ran against the original draft. Consolidated outcomes:

Applied to spec:

  • §5.2 — DuckDB DESC behavior + upgrade-window note
  • §7.2 — audit.reveal_raw mechanism deferred to Phase B
  • §7.3 — explicit single-worker uvicorn assumption for v40

Applied to plan (2026-05-11-activity-center-mvp.md):

  • Import path corrected (app.auth.dependencies._get_db)
  • Test fixtures aligned with seeded_app / admin_user / get_system_db() pattern from existing tests/conftest.py
  • All new audit writes wrapped in try/except + logger.exception
  • Filename sanitization on POST /api/upload/sessions
  • 256-char length cap on logged strings
  • 7-day cap when q filter used without explicit since
  • Migration idempotency + representative evolved-DB test
  • Conventions section added at the top of the plan

Deferred with rationale (out of MVP):

  • audit.reveal_raw toggle + UI (Phase B)
  • Shared-cache multi-worker support (separate plan)
  • Health pulse threshold env config (P2 polish)
  • diagnose_warnings real count (depends on diagnose endpoint expansion)
  • Default audit retention policy (Phase B follow-up)
  • PostHog SDK timeout knob (add if observed in prod)

Reviewer reports are not separately archived in the repo — their consolidated outputs landed as the inline edits above and the "Revisions applied" appendix in the plan doc.


13. Implementation plan documents

This spec is the parent. The executable plans are:

  • 2026-05-11-activity-center-mvp.md — full TDD task list for Week 1 work. Start here.
  • (next) 2026-05-NN-admin-sessions.md — failure_scan + /admin/sessions.
  • (next) 2026-05-NN-feedback-inbox.md — agnes report + /admin/feedback.

Each child plan refers back to this spec for cross-cutting decisions.