* 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>
1047 lines
40 KiB
Python
1047 lines
40 KiB
Python
"""Admin commands — agnes admin."""
|
|
|
|
import json
|
|
|
|
import typer
|
|
|
|
from cli.client import api_get, api_post, api_delete, api_patch, api_put
|
|
from cli.commands.admin_activity import activity_app
|
|
from cli.commands.admin_ask import app as admin_ask_app
|
|
from cli.commands.admin_metrics import admin_metrics_app
|
|
from cli.commands.admin_news import admin_news_app
|
|
from cli.commands.admin_sessions import sessions_app as admin_sessions_app
|
|
from cli.commands.admin_store import admin_store_app
|
|
from cli.commands.admin_usage import app as admin_usage_app
|
|
from cli.commands.memory_admin import memory_admin_app
|
|
|
|
admin_app = typer.Typer(help="Admin operations (requires admin role)")
|
|
admin_app.add_typer(activity_app, name="activity", help="Activity Center — audit_log timeline, health pulse, sync history")
|
|
admin_app.add_typer(admin_ask_app, name="ask", help="Ask a natural-language question about telemetry")
|
|
admin_app.add_typer(admin_metrics_app, name="metrics")
|
|
admin_app.add_typer(admin_sessions_app, name="sessions", help="Browse Claude Code sessions across all users")
|
|
admin_app.add_typer(admin_store_app, name="store")
|
|
admin_app.add_typer(admin_news_app, name="news")
|
|
admin_app.add_typer(memory_admin_app, name="memory")
|
|
# Telemetry subcommand: primary name is "telemetry", "usage" kept as an
|
|
# alias so existing operator scripts that call `agnes admin usage export …`
|
|
# keep working through this release. Drop the alias in a future cleanup
|
|
# once external callers have caught up.
|
|
admin_app.add_typer(admin_usage_app, name="telemetry", help="Telemetry export and admin queries")
|
|
admin_app.add_typer(admin_usage_app, name="usage", help="(deprecated alias of `telemetry`)")
|
|
|
|
|
|
@admin_app.command("add-user")
|
|
def add_user(
|
|
email: str = typer.Argument(..., help="User email"),
|
|
name: str = typer.Option("", help="User display name"),
|
|
):
|
|
"""Add a new user. New users start with no group memberships — to make
|
|
them admin, add them to the Admin group separately:
|
|
|
|
agnes admin group add-member <admin-group-id> <email>
|
|
"""
|
|
resp = api_post("/api/users", json={"email": email, "name": name or email.split("@")[0]})
|
|
if resp.status_code == 201:
|
|
data = resp.json()
|
|
typer.echo(f"Created user: {data['email']} (id: {data['id']})")
|
|
else:
|
|
typer.echo(f"Failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("list-users")
|
|
def list_users(as_json: bool = typer.Option(False, "--json")):
|
|
"""List all users."""
|
|
resp = api_get("/api/users")
|
|
if resp.status_code != 200:
|
|
typer.echo(f"Failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
users = resp.json()
|
|
if as_json:
|
|
typer.echo(json.dumps(users, indent=2))
|
|
else:
|
|
for u in users:
|
|
status_str = "active" if u.get("active", True) else "DEACTIVATED"
|
|
admin_flag = "admin" if u.get("is_admin") else "user"
|
|
typer.echo(
|
|
f" {u['email']:30s} {admin_flag:6s} {status_str:12s} id={u['id'][:8]}"
|
|
)
|
|
|
|
|
|
@admin_app.command("remove-user")
|
|
def remove_user(user_id: str = typer.Argument(..., help="User ID to remove")):
|
|
"""Remove a user."""
|
|
resp = api_delete(f"/api/users/{user_id}")
|
|
if resp.status_code == 204:
|
|
typer.echo("User removed.")
|
|
else:
|
|
typer.echo(f"Failed: {resp.text}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("register-table")
|
|
def register_table(
|
|
name: str = typer.Argument(..., help="Table display name (DuckDB view name for BQ)"),
|
|
source_type: str = typer.Option("keboola", help="Source type: keboola | bigquery | jira | local"),
|
|
bucket: str = typer.Option("", help="Source bucket (Keboola) or dataset (BigQuery)"),
|
|
source_table: str = typer.Option("", help="Source table name in the bucket/dataset"),
|
|
query_mode: str = typer.Option("local", help="Query mode: local | remote | materialized"),
|
|
query: str = typer.Option(
|
|
"",
|
|
"--query",
|
|
help=(
|
|
"SQL body for query_mode='materialized' (BigQuery only). "
|
|
"Inline SQL or `@path/to.sql` to read from disk."
|
|
),
|
|
),
|
|
description: str = typer.Option("", help="Table description"),
|
|
sync_schedule: str = typer.Option(
|
|
"",
|
|
help="Cron schedule (e.g. 'every 6h' / 'daily 03:00'); honored by materialized BQ rows",
|
|
),
|
|
# v26 Keboola sync-strategy support
|
|
sync_strategy: str = typer.Option(
|
|
"full_refresh",
|
|
"--sync-strategy",
|
|
help="Keboola: full_refresh (default) | incremental | partitioned",
|
|
),
|
|
primary_key: str = typer.Option(
|
|
"",
|
|
"--primary-key",
|
|
help="Primary key column(s), comma-separated. Required for incremental dedup.",
|
|
),
|
|
incremental_window_days: int = typer.Option(
|
|
None,
|
|
"--incremental-window-days",
|
|
help="Backtrack window applied to last_sync (default 7 at sync time)",
|
|
),
|
|
max_history_days: int = typer.Option(
|
|
None,
|
|
"--max-history-days",
|
|
help="Cap on first-sync history depth (None = unbounded)",
|
|
),
|
|
where_filters_json: str = typer.Option(
|
|
"",
|
|
"--where-filters-json",
|
|
help=(
|
|
"JSON array of {column, operator, values}. Inline JSON or "
|
|
"@path/to/filters.json. Date placeholders supported: "
|
|
"{{today}}, {{last_week}}, {{last_3_months}}, etc. "
|
|
"(see connectors.keboola.where_filters for the full list). "
|
|
"Filters force the SDK extraction path (slower than the "
|
|
"DuckDB extension); use only when needed."
|
|
),
|
|
),
|
|
partition_by: str = typer.Option(
|
|
"",
|
|
"--partition-by",
|
|
help="Date column driving partition keys (required for partitioned strategy)",
|
|
),
|
|
partition_granularity: str = typer.Option(
|
|
"",
|
|
"--partition-granularity",
|
|
help="day | month (default) | year — for partitioned strategy",
|
|
),
|
|
initial_load_chunk_days: int = typer.Option(
|
|
None,
|
|
"--initial-load-chunk-days",
|
|
help="Chunk size for partitioned first-sync chunked initial load (default 30)",
|
|
),
|
|
dry_run: bool = typer.Option(
|
|
False,
|
|
"--dry-run",
|
|
help="Run validation + (BQ) source-side check without writing to the registry",
|
|
),
|
|
):
|
|
"""Register a single table.
|
|
|
|
Modes:
|
|
- **local** (Keboola): batch pull, parquet on disk. Requires
|
|
`--bucket` + `--source-table`.
|
|
- **remote** (BigQuery): view only, queries go to BQ. Requires
|
|
`--bucket` + `--source-table`.
|
|
- **materialized** (BigQuery): server-side scheduled SQL → parquet.
|
|
Requires `--query` (inline or `@file.sql`) AND `--bucket` (BQ
|
|
dataset of the destination identifier). `--source-table` defaults
|
|
to the registered `name` when omitted; explicit override is rare.
|
|
Note: `agnes schema <name>` builds the BQ identifier as
|
|
`bq.<bucket>.<source_table>` even for materialized rows, so an
|
|
empty `--bucket` here registers the row but breaks subsequent
|
|
schema/describe calls.
|
|
|
|
`--dry-run` goes through /precheck (BQ remote only — for materialized
|
|
rows, dry-run is a no-op since the SQL itself is the contract).
|
|
"""
|
|
from pathlib import Path
|
|
|
|
# Resolve --query @file.sql shorthand.
|
|
source_query = ""
|
|
if query:
|
|
if query.startswith("@"):
|
|
sql_path = Path(query[1:])
|
|
if not sql_path.exists():
|
|
typer.echo(f"Error: SQL file not found: {sql_path}", err=True)
|
|
raise typer.Exit(2)
|
|
source_query = sql_path.read_text(encoding="utf-8").strip()
|
|
else:
|
|
source_query = query.strip()
|
|
|
|
# Keboola materialized rows can omit --query: a NULL source_query means
|
|
# "full-table export via Storage API export-async" (see v25→v26
|
|
# migration notes). For BigQuery materialized rows, --query is still
|
|
# required — BQ has no analogous "full table" semantic at the registry
|
|
# layer (the path is a SELECT against `<project>.<dataset>.<table>`,
|
|
# which the admin must spell out).
|
|
if query_mode == "materialized" and not source_query and source_type != "keboola":
|
|
typer.echo(
|
|
"Error: --query-mode materialized requires --query (literal SQL or @path.sql) for source_type=" + source_type,
|
|
err=True,
|
|
)
|
|
raise typer.Exit(2)
|
|
|
|
# Bucket is load-bearing on materialized rows. For BQ it backs the
|
|
# destination identifier (`agnes schema <name>` builds `bq."<bucket>"."
|
|
# <src>"` from it; an empty bucket trips "unsafe BQ identifier in
|
|
# registry" at query time). For Keboola it's the bucket id passed to
|
|
# `/v2/storage/tables/<bucket>.<source_table>/export-async` — without
|
|
# it the export call would 404. Same requirement, different rationale.
|
|
if query_mode == "materialized" and not bucket:
|
|
typer.echo(
|
|
"Error: --query-mode materialized requires --bucket (the "
|
|
"BQ dataset / Keboola bucket id for the source identifier).",
|
|
err=True,
|
|
)
|
|
raise typer.Exit(2)
|
|
|
|
payload = {
|
|
"name": name,
|
|
"source_type": source_type,
|
|
"bucket": bucket,
|
|
"source_table": source_table or name,
|
|
"query_mode": query_mode,
|
|
"description": description,
|
|
}
|
|
# Omit empty optional fields so the server-side validator doesn't see
|
|
# `source_query=""` on a remote/local row (which would trigger the
|
|
# "source_query forbidden" branch).
|
|
if source_query:
|
|
payload["source_query"] = source_query
|
|
if sync_schedule:
|
|
payload["sync_schedule"] = sync_schedule
|
|
|
|
# v26 sync-strategy support fields. Always send sync_strategy (it has a
|
|
# default). Send the rest only when the operator set them — empty/None
|
|
# → omit so the server stores NULL.
|
|
payload["sync_strategy"] = sync_strategy
|
|
if primary_key:
|
|
payload["primary_key"] = [c.strip() for c in primary_key.split(",") if c.strip()]
|
|
if incremental_window_days is not None:
|
|
payload["incremental_window_days"] = incremental_window_days
|
|
if max_history_days is not None:
|
|
payload["max_history_days"] = max_history_days
|
|
if partition_by:
|
|
payload["partition_by"] = partition_by
|
|
if partition_granularity:
|
|
payload["partition_granularity"] = partition_granularity
|
|
if initial_load_chunk_days is not None:
|
|
payload["initial_load_chunk_days"] = initial_load_chunk_days
|
|
if where_filters_json:
|
|
# Inline JSON or @path/to.json
|
|
if where_filters_json.startswith("@"):
|
|
wf_path = Path(where_filters_json[1:])
|
|
if not wf_path.exists():
|
|
typer.echo(f"Error: where_filters file not found: {wf_path}", err=True)
|
|
raise typer.Exit(2)
|
|
wf_text = wf_path.read_text(encoding="utf-8")
|
|
else:
|
|
wf_text = where_filters_json
|
|
try:
|
|
import json as _json
|
|
payload["where_filters"] = _json.loads(wf_text)
|
|
except _json.JSONDecodeError as e:
|
|
typer.echo(f"Error: --where-filters-json is not valid JSON: {e}", err=True)
|
|
raise typer.Exit(2)
|
|
|
|
if dry_run:
|
|
# Hits /precheck — no DB write, but for BQ does a real
|
|
# bigquery.Client(project).get_table() round-trip so the operator
|
|
# gets the same NotFound / Forbidden error they'd see at
|
|
# registration time, before committing.
|
|
resp = api_post("/api/admin/register-table/precheck", json=payload)
|
|
if resp.status_code == 200:
|
|
data = resp.json()
|
|
t = data.get("table") or {}
|
|
typer.echo("[DRY RUN] precheck OK")
|
|
typer.echo(f" name: {t.get('name')}")
|
|
typer.echo(f" source_type: {t.get('source_type')}")
|
|
typer.echo(f" bucket: {t.get('bucket')}")
|
|
typer.echo(f" source_table: {t.get('source_table')}")
|
|
if t.get("project_id"):
|
|
typer.echo(f" project_id: {t.get('project_id')}")
|
|
if t.get("rows") is not None:
|
|
typer.echo(f" rows: {t.get('rows'):,}")
|
|
if t.get("size_bytes") is not None:
|
|
typer.echo(f" size_bytes: {t.get('size_bytes'):,}")
|
|
cols = t.get("columns") or []
|
|
if cols:
|
|
typer.echo(f" columns ({len(cols)}):")
|
|
for c in cols:
|
|
typer.echo(f" - {c.get('name'):<32s} {c.get('type', '')}")
|
|
return
|
|
typer.echo(f"Precheck failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
resp = api_post("/api/admin/register-table", json=payload)
|
|
# 200 (BQ sync materialize OK), 201 (legacy non-BQ), and 202 (BQ
|
|
# background materialize) are all success.
|
|
if resp.status_code in (200, 201, 202):
|
|
if resp.status_code == 202:
|
|
typer.echo(f"Registered (materializing in background): {name}")
|
|
else:
|
|
typer.echo(f"Registered: {name}")
|
|
|
|
# Post-success hints. Two operator gotchas this catches:
|
|
#
|
|
# 1. `agnes pull` does not auto-materialize newly-registered
|
|
# rows — registration adds a registry row, but the parquet
|
|
# is built only when the scheduler tick runs (or first-sync
|
|
# is triggered manually). Without this hint operators see
|
|
# "Updated 0 tables" on `agnes pull` and assume something
|
|
# is broken.
|
|
# 2. `register-table` does NOT auto-grant. `agnes catalog`
|
|
# filters per-user via `resource_grants`, so operators
|
|
# other than the registering admin won't see the new row
|
|
# until a grant is created.
|
|
#
|
|
# Hint #1 only fires for `local` and `materialized` (the modes
|
|
# that actually produce a parquet); 202-async path covers a
|
|
# different signal, so don't double-message there.
|
|
if query_mode in ("local", "materialized") and resp.status_code != 202:
|
|
typer.echo(
|
|
" Next: run `agnes setup first-sync` to materialize "
|
|
"the parquet (or wait for the scheduler tick)."
|
|
)
|
|
typer.echo(
|
|
f" Note: register-table does not auto-grant. Run "
|
|
f"`agnes admin grant create <group> table {name}` to "
|
|
f"make this visible in `agnes catalog` for non-admin users."
|
|
)
|
|
# Third hint: BQ-remote rows can fail at first analyst query if the
|
|
# SA lacks dataViewer/jobUser. Pointing at the smoke command
|
|
# surfaces the failure at registration time, not 30 minutes later.
|
|
if query_mode == "remote":
|
|
typer.echo(
|
|
f" Note: this is a remote-query table. Verify the SA can read it:\n"
|
|
f" agnes query --remote \"SELECT COUNT(*) FROM {name}\"\n"
|
|
f" If it 403s, see docs/admin/query-modes.md → \"BigQuery → IAM\"."
|
|
)
|
|
elif resp.status_code == 409:
|
|
typer.echo(f"Already exists: {name}")
|
|
else:
|
|
typer.echo(f"Failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("discover-and-register")
|
|
def discover_and_register(
|
|
source_type: str = typer.Option("keboola", help="Source type"),
|
|
token: str = typer.Option(None, help="Keboola Storage API token"),
|
|
url: str = typer.Option(None, help="Keboola stack URL"),
|
|
dry_run: bool = typer.Option(False, "--dry-run", help="Show what would be registered"),
|
|
as_json: bool = typer.Option(False, "--json", help="Output as JSON"),
|
|
):
|
|
"""Discover all tables from source and register them."""
|
|
import httpx
|
|
import os
|
|
|
|
kbc_token = token or os.environ.get("KEBOOLA_STORAGE_TOKEN", "")
|
|
kbc_url = url or os.environ.get("KEBOOLA_STACK_URL", "")
|
|
|
|
if not kbc_token or not kbc_url:
|
|
typer.echo("Need KEBOOLA_STORAGE_TOKEN and KEBOOLA_STACK_URL (env or --token/--url)", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
typer.echo(f"Discovering tables from {kbc_url}...")
|
|
resp = httpx.get(f"{kbc_url.rstrip('/')}/v2/storage/tables",
|
|
headers={"X-StorageApi-Token": kbc_token}, timeout=30)
|
|
resp.raise_for_status()
|
|
tables = resp.json()
|
|
typer.echo(f"Found {len(tables)} tables")
|
|
|
|
if as_json and dry_run:
|
|
typer.echo(json.dumps([{"id": t["id"], "name": t["name"],
|
|
"bucket": t.get("bucket", {}).get("id", ""),
|
|
"rows": t.get("rowsCount", 0)} for t in tables], indent=2))
|
|
return
|
|
|
|
registered = 0
|
|
skipped = 0
|
|
errors = 0
|
|
|
|
for t in tables:
|
|
table_id = t["id"]
|
|
name = t["name"]
|
|
bucket_id = t.get("bucket", {}).get("id", "")
|
|
|
|
if dry_run:
|
|
typer.echo(f" [DRY RUN] {name:30s} bucket={bucket_id:20s} rows={t.get('rowsCount', 0):>10,}")
|
|
continue
|
|
|
|
# Keboola tables always go through the Storage API export-async
|
|
# path (`materialize_query`), which is `query_mode='materialized'`
|
|
# in the registry. A NULL source_query means "full table export"
|
|
# — same effective semantics the old 'local' mode gave, but via
|
|
# the Storage API instead of the DuckDB extension. See
|
|
# connectors/keboola/storage_api.py + the v25→v26 migration.
|
|
# Other connectors keep their per-source default.
|
|
default_mode = "materialized" if source_type == "keboola" else "local"
|
|
resp = api_post("/api/admin/register-table", json={
|
|
"name": name,
|
|
"source_type": source_type,
|
|
"bucket": bucket_id,
|
|
"source_table": name,
|
|
"query_mode": default_mode,
|
|
"description": f"Auto-discovered from {source_type}",
|
|
})
|
|
|
|
# 200 (BQ synchronous materialize), 201 (legacy non-BQ insert),
|
|
# and 202 (BQ background materialize) are all success — mirrors
|
|
# the matrix in the single-table register-table command. Pre-fix
|
|
# this only accepted 201, so every successful BQ row counted as
|
|
# an error (review NIT 6 in #119).
|
|
if resp.status_code in (200, 201, 202):
|
|
registered += 1
|
|
suffix = " (materializing in background)" if resp.status_code == 202 else ""
|
|
typer.echo(f" ✓ {name}{suffix}")
|
|
elif resp.status_code == 409:
|
|
skipped += 1
|
|
else:
|
|
errors += 1
|
|
typer.echo(f" ✗ {name}: {resp.json().get('detail', resp.text)}")
|
|
|
|
if not dry_run:
|
|
typer.echo(f"\nDone: {registered} registered, {skipped} already existed, {errors} errors")
|
|
|
|
|
|
@admin_app.command("list-tables")
|
|
def list_tables(as_json: bool = typer.Option(False, "--json")):
|
|
"""List registered tables."""
|
|
resp = api_get("/api/admin/registry")
|
|
if resp.status_code != 200:
|
|
typer.echo(f"Failed: {resp.text}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
data = resp.json()
|
|
if as_json:
|
|
typer.echo(json.dumps(data, indent=2))
|
|
else:
|
|
typer.echo(f"Registered tables: {data['count']}")
|
|
for t in data["tables"]:
|
|
typer.echo(f" {t['name']:30s} src={t.get('source_type','?'):10s} mode={t.get('query_mode','?'):6s} bucket={t.get('bucket',''):20s}")
|
|
|
|
|
|
@admin_app.command("unregister-table")
|
|
def unregister_table(
|
|
table_id: str = typer.Argument(..., help="Table id to unregister"),
|
|
yes: bool = typer.Option(
|
|
False, "--yes", "-y",
|
|
help="Skip the confirmation prompt (for scripts).",
|
|
),
|
|
):
|
|
"""Unregister a table from the registry.
|
|
|
|
Calls `DELETE /api/admin/registry/{table_id}`. The server unhooks the
|
|
master view, removes the canonical parquet for materialized rows, and
|
|
clears the matching `sync_state` row. Issue #177.
|
|
"""
|
|
if not yes:
|
|
typer.echo(f"About to unregister table: {table_id}")
|
|
if not typer.confirm("Continue?"):
|
|
typer.echo("Aborted.")
|
|
raise typer.Exit(0)
|
|
resp = api_delete(f"/api/admin/registry/{table_id}")
|
|
if resp.status_code == 204:
|
|
typer.echo(f"Unregistered: {table_id}")
|
|
return
|
|
if resp.status_code == 404:
|
|
typer.echo(f"Not registered: {table_id}", err=True)
|
|
raise typer.Exit(1)
|
|
try:
|
|
detail = resp.json().get("detail", resp.text)
|
|
except Exception:
|
|
detail = resp.text
|
|
typer.echo(f"Failed: {detail}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("update-table")
|
|
def update_table(
|
|
table_id: str = typer.Argument(..., help="Table id to update"),
|
|
name: str = typer.Option(None, "--name", help="New display name"),
|
|
bucket: str = typer.Option(None, "--bucket", help="New bucket / dataset"),
|
|
source_table: str = typer.Option(
|
|
None, "--source-table", help="New source table name"
|
|
),
|
|
query_mode: str = typer.Option(
|
|
None,
|
|
"--query-mode",
|
|
help="New query mode: local | remote | materialized",
|
|
),
|
|
query: str = typer.Option(
|
|
None,
|
|
"--query",
|
|
help=(
|
|
"New SQL body for query_mode='materialized' (BigQuery). "
|
|
"Inline SQL or `@path/to.sql` to read from disk. Use "
|
|
"`--query=` (empty value) to clear."
|
|
),
|
|
),
|
|
description: str = typer.Option(
|
|
None, "--description", help="New description"
|
|
),
|
|
sync_schedule: str = typer.Option(
|
|
None,
|
|
"--sync-schedule",
|
|
help="New cron schedule (e.g. 'every 6h' / 'daily 03:00'); honored by materialized BQ rows",
|
|
),
|
|
source_type: str = typer.Option(
|
|
None,
|
|
"--source-type",
|
|
help="Change source type. Rare — most edits keep this fixed.",
|
|
),
|
|
):
|
|
"""Update a registered table.
|
|
|
|
Calls `PUT /api/admin/registry/{table_id}` with only the supplied
|
|
fields. Field omitted → unchanged. Issue #177.
|
|
|
|
For BQ rows, the server schedules a background rebuild so the master
|
|
view picks up the change without waiting for the next scheduled sync.
|
|
Switching `query_mode` away from `materialized` clears the stale
|
|
`source_query` automatically.
|
|
"""
|
|
from pathlib import Path
|
|
|
|
payload: dict = {}
|
|
if name is not None:
|
|
payload["name"] = name
|
|
if bucket is not None:
|
|
payload["bucket"] = bucket
|
|
if source_table is not None:
|
|
payload["source_table"] = source_table
|
|
if query_mode is not None:
|
|
payload["query_mode"] = query_mode
|
|
if description is not None:
|
|
payload["description"] = description
|
|
if sync_schedule is not None:
|
|
payload["sync_schedule"] = sync_schedule
|
|
if source_type is not None:
|
|
payload["source_type"] = source_type
|
|
if query is not None:
|
|
if query.startswith("@"):
|
|
sql_path = Path(query[1:])
|
|
if not sql_path.exists():
|
|
typer.echo(f"Error: SQL file not found: {sql_path}", err=True)
|
|
raise typer.Exit(2)
|
|
payload["source_query"] = sql_path.read_text(encoding="utf-8").strip()
|
|
else:
|
|
payload["source_query"] = query.strip()
|
|
|
|
if not payload:
|
|
typer.echo(
|
|
"No fields supplied. Pass at least one of --name, --bucket, "
|
|
"--source-table, --query-mode, --query, --description, "
|
|
"--sync-schedule, --source-type.",
|
|
err=True,
|
|
)
|
|
raise typer.Exit(2)
|
|
|
|
resp = api_put(f"/api/admin/registry/{table_id}", json=payload)
|
|
if resp.status_code == 200:
|
|
data = resp.json()
|
|
updated = data.get("updated") or sorted(payload.keys())
|
|
typer.echo(f"Updated {table_id}: {', '.join(updated)}")
|
|
return
|
|
if resp.status_code == 404:
|
|
typer.echo(f"Not registered: {table_id}", err=True)
|
|
raise typer.Exit(1)
|
|
try:
|
|
detail = resp.json().get("detail", resp.text)
|
|
except Exception:
|
|
detail = resp.text
|
|
typer.echo(f"Failed: {detail}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("metadata-show")
|
|
def metadata_show(
|
|
table_id: str = typer.Argument(..., help="Table ID to show metadata for"),
|
|
as_json: bool = typer.Option(False, "--json", help="Output as JSON"),
|
|
):
|
|
"""Show column metadata for a table."""
|
|
resp = api_get(f"/api/admin/metadata/{table_id}")
|
|
if resp.status_code != 200:
|
|
typer.echo(f"Failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
data = resp.json()
|
|
if as_json:
|
|
typer.echo(json.dumps(data, indent=2))
|
|
else:
|
|
columns = data.get("columns", [])
|
|
if not columns:
|
|
typer.echo(f"No column metadata for table: {table_id}")
|
|
return
|
|
typer.echo(f"Column metadata for table: {table_id} ({len(columns)} columns)")
|
|
typer.echo(f" {'COLUMN':<30s} {'BASETYPE':<12s} {'CONFIDENCE':<12s} DESCRIPTION")
|
|
typer.echo(" " + "-" * 80)
|
|
for col in columns:
|
|
typer.echo(
|
|
f" {col['column_name']:<30s} {col.get('basetype') or '':^12s} "
|
|
f"{col.get('confidence') or '':^12s} {col.get('description') or ''}"
|
|
)
|
|
|
|
|
|
@admin_app.command("metadata-apply")
|
|
def metadata_apply(
|
|
proposal_path: str = typer.Argument(..., help="Path to proposal JSON file"),
|
|
push_to_source: bool = typer.Option(False, "--push-to-source", help="Push metadata to Keboola after import"),
|
|
dry_run: bool = typer.Option(False, "--dry-run", help="Show what would change without applying"),
|
|
):
|
|
"""Apply a metadata proposal JSON to DuckDB."""
|
|
import os
|
|
|
|
if not os.path.exists(proposal_path):
|
|
typer.echo(f"Proposal file not found: {proposal_path}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
with open(proposal_path, "r", encoding="utf-8") as f:
|
|
proposal = json.load(f)
|
|
|
|
tables = proposal.get("tables", {})
|
|
total = sum(len(t.get("columns", {})) for t in tables.values())
|
|
|
|
if dry_run:
|
|
typer.echo(f"[DRY RUN] Would import {total} column(s) from {len(tables)} table(s):")
|
|
for table_id, table_data in tables.items():
|
|
columns = table_data.get("columns", {})
|
|
for col_name, col_data in columns.items():
|
|
typer.echo(
|
|
f" {table_id}.{col_name}: basetype={col_data.get('basetype')} "
|
|
f"description={col_data.get('description')}"
|
|
)
|
|
return
|
|
|
|
from src.repositories.column_metadata import ColumnMetadataRepository
|
|
from src.db import get_system_db
|
|
|
|
conn = get_system_db()
|
|
try:
|
|
repo = ColumnMetadataRepository(conn)
|
|
count = repo.import_proposal(proposal_path)
|
|
typer.echo(f"Imported {count} column(s) from proposal.")
|
|
finally:
|
|
conn.close()
|
|
|
|
if push_to_source:
|
|
for table_id in tables:
|
|
resp = api_post(f"/api/admin/metadata/{table_id}/push")
|
|
if resp.status_code == 200:
|
|
typer.echo(f"Pushed metadata for {table_id} to source.")
|
|
else:
|
|
typer.echo(f"Failed to push {table_id}: {resp.json().get('detail', resp.text)}", err=True)
|
|
|
|
|
|
# ---- User management (#11) ----
|
|
|
|
|
|
def _resolve_user_id(ref: str) -> str:
|
|
"""Accept either a UUID or an email; look up email → id via list."""
|
|
if "@" not in ref:
|
|
return ref
|
|
resp = api_get("/api/users")
|
|
if resp.status_code != 200:
|
|
typer.echo(f"Could not list users: {resp.text}", err=True)
|
|
raise typer.Exit(1)
|
|
for u in resp.json():
|
|
if u.get("email") == ref:
|
|
return u["id"]
|
|
typer.echo(f"User not found: {ref}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
def _print_user_result(resp, ok_msg: str) -> None:
|
|
if resp.status_code in (200, 204):
|
|
typer.echo(ok_msg)
|
|
else:
|
|
try:
|
|
detail = resp.json().get("detail", resp.text)
|
|
except Exception:
|
|
detail = resp.text
|
|
typer.echo(f"Failed: {detail}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("set-role")
|
|
def set_role(
|
|
user_ref: str = typer.Argument(..., help="User id or email"),
|
|
role: str = typer.Argument(..., help="(removed — see message)"),
|
|
):
|
|
"""[REMOVED] Roles were replaced by group memberships in v0.25."""
|
|
typer.echo(
|
|
"Error: 'agnes admin set-role' was removed in v0.25.\n"
|
|
" Roles were replaced by group memberships.\n"
|
|
f" Make {user_ref!r} admin:\n"
|
|
" agnes admin group list # find Admin group id\n"
|
|
f" agnes admin group add-member <admin-id> {user_ref}\n",
|
|
err=True,
|
|
)
|
|
raise typer.Exit(2)
|
|
|
|
|
|
@admin_app.command("deactivate")
|
|
def deactivate(user_ref: str = typer.Argument(..., help="User id or email")):
|
|
"""Deactivate a user (blocks login, existing tokens also rejected)."""
|
|
uid = _resolve_user_id(user_ref)
|
|
resp = api_post(f"/api/users/{uid}/deactivate")
|
|
_print_user_result(resp, f"Deactivated {user_ref}")
|
|
|
|
|
|
@admin_app.command("activate")
|
|
def activate(user_ref: str = typer.Argument(..., help="User id or email")):
|
|
"""Re-activate a deactivated user."""
|
|
uid = _resolve_user_id(user_ref)
|
|
resp = api_post(f"/api/users/{uid}/activate")
|
|
_print_user_result(resp, f"Activated {user_ref}")
|
|
|
|
|
|
@admin_app.command("reset-password")
|
|
def reset_password(user_ref: str = typer.Argument(..., help="User id or email")):
|
|
"""Generate a reset token (emailed if SMTP/SendGrid configured)."""
|
|
uid = _resolve_user_id(user_ref)
|
|
resp = api_post(f"/api/users/{uid}/reset-password")
|
|
if resp.status_code == 200:
|
|
data = resp.json()
|
|
typer.echo(f"Reset URL: {data['reset_url']}")
|
|
typer.echo(f"Email sent: {data['email_sent']}")
|
|
else:
|
|
typer.echo(f"Failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@admin_app.command("set-password")
|
|
def set_password(
|
|
user_ref: str = typer.Argument(..., help="User id or email"),
|
|
password: str = typer.Option(
|
|
..., prompt=True, hide_input=True, confirmation_prompt=True,
|
|
help="New password (hidden input)",
|
|
),
|
|
):
|
|
"""Set a user's password directly (force-reset flow)."""
|
|
uid = _resolve_user_id(user_ref)
|
|
resp = api_post(f"/api/users/{uid}/set-password", json={"password": password})
|
|
if resp.status_code == 204:
|
|
typer.echo(f"Password set for {user_ref}")
|
|
else:
|
|
typer.echo(f"Failed: {resp.json().get('detail', resp.text)}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
# ---- Access management (v12 — user_groups + members + resource_grants) ----
|
|
#
|
|
# Calls the unified access REST API under /api/admin (see app/api/access.py).
|
|
# Every endpoint requires Admin user_group membership.
|
|
|
|
group_app = typer.Typer(help="User group + membership management")
|
|
grant_app = typer.Typer(help="Resource grant CRUD")
|
|
admin_app.add_typer(group_app, name="group")
|
|
admin_app.add_typer(grant_app, name="grant")
|
|
|
|
|
|
def _fail(resp, prefix: str = "Failed") -> None:
|
|
try:
|
|
detail = resp.json().get("detail", resp.text)
|
|
except Exception:
|
|
detail = resp.text
|
|
typer.echo(f"{prefix}: {detail}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
def _print_rows(rows: list, columns: list[tuple[str, str, int]]) -> None:
|
|
header = " " + " ".join(f"{h:<{w}s}" for _, h, w in columns)
|
|
typer.echo(header)
|
|
typer.echo(" " + "-" * (len(header) - 2))
|
|
for row in rows:
|
|
cells = []
|
|
for key, _, width in columns:
|
|
val = row.get(key)
|
|
cells.append(f"{(str(val) if val is not None else ''):<{width}s}")
|
|
typer.echo(" " + " ".join(cells))
|
|
|
|
|
|
def _resolve_group_id(ref: str) -> str:
|
|
"""Accept group id (UUID-ish) or name; look up via /api/admin/groups."""
|
|
resp = api_get("/api/admin/groups")
|
|
if resp.status_code != 200:
|
|
_fail(resp, prefix="Could not list groups")
|
|
for g in resp.json():
|
|
if g["id"] == ref or g["name"] == ref:
|
|
return g["id"]
|
|
typer.echo(f"Group not found: {ref}", err=True)
|
|
raise typer.Exit(1)
|
|
|
|
|
|
@group_app.command("list")
|
|
def group_list(as_json: bool = typer.Option(False, "--json")):
|
|
"""List all user groups."""
|
|
resp = api_get("/api/admin/groups")
|
|
if resp.status_code != 200:
|
|
_fail(resp)
|
|
rows = resp.json()
|
|
if as_json:
|
|
typer.echo(json.dumps(rows, indent=2)); return
|
|
typer.echo(f"User groups: {len(rows)}")
|
|
_print_rows(rows, [
|
|
("name", "NAME", 24),
|
|
("description", "DESCRIPTION", 40),
|
|
("is_system", "SYSTEM", 7),
|
|
("member_count", "MEMBERS", 8),
|
|
("grant_count", "GRANTS", 7),
|
|
])
|
|
|
|
|
|
@group_app.command("create")
|
|
def group_create(
|
|
name: str = typer.Argument(..., help="Group name"),
|
|
description: str = typer.Option("", help="Description"),
|
|
):
|
|
"""Create a new user group."""
|
|
resp = api_post("/api/admin/groups", json={"name": name, "description": description or None})
|
|
if resp.status_code != 201:
|
|
_fail(resp)
|
|
typer.echo(f"Created group: {name} (id={resp.json()['id']})")
|
|
|
|
|
|
@group_app.command("delete")
|
|
def group_delete(group_ref: str = typer.Argument(..., help="Group id or name")):
|
|
"""Delete a user group (and its members + grants)."""
|
|
gid = _resolve_group_id(group_ref)
|
|
resp = api_delete(f"/api/admin/groups/{gid}")
|
|
if resp.status_code in (200, 204):
|
|
typer.echo(f"Deleted group {group_ref}"); return
|
|
_fail(resp)
|
|
|
|
|
|
@group_app.command("members")
|
|
def group_members(group_ref: str = typer.Argument(..., help="Group id or name")):
|
|
"""List members of a group."""
|
|
gid = _resolve_group_id(group_ref)
|
|
resp = api_get(f"/api/admin/groups/{gid}/members")
|
|
if resp.status_code != 200:
|
|
_fail(resp)
|
|
rows = resp.json()
|
|
typer.echo(f"Members: {len(rows)}")
|
|
_print_rows(rows, [
|
|
("email", "EMAIL", 30),
|
|
("name", "NAME", 20),
|
|
("source", "SOURCE", 14),
|
|
("active", "ACTIVE", 7),
|
|
])
|
|
|
|
|
|
@group_app.command("add-member")
|
|
def group_add_member(
|
|
group_ref: str = typer.Argument(..., help="Group id or name"),
|
|
email: str = typer.Argument(..., help="User email"),
|
|
):
|
|
"""Add a user to a group (source='admin' — survives Google sync)."""
|
|
gid = _resolve_group_id(group_ref)
|
|
resp = api_post(f"/api/admin/groups/{gid}/members", json={"email": email})
|
|
if resp.status_code != 201:
|
|
_fail(resp)
|
|
typer.echo(f"Added {email} to {group_ref}")
|
|
|
|
|
|
@group_app.command("remove-member")
|
|
def group_remove_member(
|
|
group_ref: str = typer.Argument(..., help="Group id or name"),
|
|
email: str = typer.Argument(..., help="User email"),
|
|
):
|
|
"""Remove a user from a group (only admin-source rows can be removed this way)."""
|
|
gid = _resolve_group_id(group_ref)
|
|
user_id = _resolve_user_id(email)
|
|
resp = api_delete(f"/api/admin/groups/{gid}/members/{user_id}")
|
|
if resp.status_code in (200, 204):
|
|
typer.echo(f"Removed {email} from {group_ref}"); return
|
|
_fail(resp)
|
|
|
|
|
|
@grant_app.command("list")
|
|
def grant_list(
|
|
resource_type: str = typer.Option("", "--type", help="Filter by resource type"),
|
|
group_ref: str = typer.Option("", "--group", help="Filter by group id or name"),
|
|
as_json: bool = typer.Option(False, "--json"),
|
|
):
|
|
"""List resource grants."""
|
|
params = {}
|
|
if resource_type:
|
|
params["resource_type"] = resource_type
|
|
if group_ref:
|
|
params["group_id"] = _resolve_group_id(group_ref)
|
|
resp = api_get("/api/admin/grants", params=params)
|
|
if resp.status_code != 200:
|
|
_fail(resp)
|
|
rows = resp.json()
|
|
if as_json:
|
|
typer.echo(json.dumps(rows, indent=2)); return
|
|
typer.echo(f"Resource grants: {len(rows)}")
|
|
_print_rows(rows, [
|
|
("group_name", "GROUP", 20),
|
|
("resource_type", "RESOURCE TYPE", 22),
|
|
("resource_id", "RESOURCE ID", 40),
|
|
("assigned_by", "ASSIGNED BY", 24),
|
|
])
|
|
|
|
|
|
@grant_app.command("create")
|
|
def grant_create(
|
|
group_ref: str = typer.Argument(..., help="Group id or name"),
|
|
resource_type: str = typer.Argument(..., help="Resource type (e.g. marketplace_plugin)"),
|
|
resource_id: str = typer.Argument(..., help="Resource path (e.g. foundry-ai/metrics-plugin)"),
|
|
):
|
|
"""Grant a group access to a specific resource."""
|
|
gid = _resolve_group_id(group_ref)
|
|
resp = api_post("/api/admin/grants", json={
|
|
"group_id": gid,
|
|
"resource_type": resource_type,
|
|
"resource_id": resource_id,
|
|
})
|
|
if resp.status_code != 201:
|
|
_fail(resp)
|
|
typer.echo(f"Granted {group_ref}: {resource_type}/{resource_id}")
|
|
|
|
|
|
@grant_app.command("delete")
|
|
def grant_delete(grant_id: str = typer.Argument(..., help="Grant id")):
|
|
"""Delete a grant by id."""
|
|
resp = api_delete(f"/api/admin/grants/{grant_id}")
|
|
if resp.status_code in (200, 204):
|
|
typer.echo(f"Deleted grant {grant_id}"); return
|
|
_fail(resp)
|
|
|
|
|
|
@grant_app.command("resource-types")
|
|
def grant_resource_types(as_json: bool = typer.Option(False, "--json")):
|
|
"""List the resource types modules have registered."""
|
|
resp = api_get("/api/admin/resource-types")
|
|
if resp.status_code != 200:
|
|
_fail(resp)
|
|
rows = resp.json()
|
|
if as_json:
|
|
typer.echo(json.dumps(rows, indent=2)); return
|
|
_print_rows(rows, [
|
|
("key", "KEY", 28),
|
|
("display_name", "DISPLAY NAME", 28),
|
|
("id_format", "ID FORMAT", 36),
|
|
])
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Break-glass: out-of-band admin grant.
|
|
#
|
|
# Talks directly to system.duckdb — no HTTP, no auth dependency. The whole
|
|
# point is recovery for the case where the running server's authorization
|
|
# layer is broken or there is no admin left to authenticate as. Requires
|
|
# filesystem access to ${DATA_DIR}/state/system.duckdb and is therefore
|
|
# restricted to operators with shell access on the host.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
breakglass_app = typer.Typer(
|
|
help="Out-of-band recovery (talks directly to system.duckdb)",
|
|
)
|
|
admin_app.add_typer(breakglass_app, name="break-glass")
|
|
|
|
|
|
@breakglass_app.command("grant-admin")
|
|
def break_glass_grant_admin(
|
|
email: str = typer.Argument(..., help="Email of the user to promote"),
|
|
yes: bool = typer.Option(
|
|
False, "--yes", "-y", help="Skip confirmation prompt"
|
|
),
|
|
) -> None:
|
|
"""Grant Admin-group membership to a user without going through the API.
|
|
|
|
Operates directly on system.duckdb. Use when the server is up but the
|
|
Admin group has no live members (race, mistake, accidental DELETE) or
|
|
when bootstrapping a brand-new install before any admin exists. Membership
|
|
is recorded with source='cli_break_glass' so it's distinguishable from
|
|
google_sync / admin / system_seed in audits.
|
|
|
|
The DuckDB file must not be locked by a running app process — stop the
|
|
app or use a separate replica before running this.
|
|
"""
|
|
import uuid as _uuid
|
|
|
|
from src.db import SYSTEM_ADMIN_GROUP, get_system_db
|
|
from src.repositories.user_groups import UserGroupsRepository
|
|
from src.repositories.user_group_members import UserGroupMembersRepository
|
|
from src.repositories.users import UserRepository
|
|
|
|
if not yes:
|
|
confirm = typer.confirm(
|
|
f"Grant Admin-group membership to {email!r} (break-glass)?",
|
|
default=False,
|
|
)
|
|
if not confirm:
|
|
typer.echo("Aborted.")
|
|
raise typer.Exit(1)
|
|
|
|
conn = get_system_db()
|
|
try:
|
|
users = UserRepository(conn)
|
|
groups = UserGroupsRepository(conn)
|
|
members = UserGroupMembersRepository(conn)
|
|
|
|
admin_group = groups.get_by_name(SYSTEM_ADMIN_GROUP)
|
|
if admin_group is None:
|
|
typer.echo(
|
|
f"FATAL: '{SYSTEM_ADMIN_GROUP}' group missing. Start the app "
|
|
"once so _seed_system_groups can recreate it, then retry.",
|
|
err=True,
|
|
)
|
|
raise typer.Exit(2)
|
|
|
|
existing = users.get_by_email(email)
|
|
if existing is None:
|
|
user_id = _uuid.uuid4().hex
|
|
users.create(
|
|
id=user_id,
|
|
email=email,
|
|
name=email.split("@", 1)[0],
|
|
)
|
|
typer.echo(f"Created user {email} (id={user_id[:8]}…)")
|
|
else:
|
|
user_id = existing["id"]
|
|
|
|
if members.has_membership(user_id, admin_group["id"]):
|
|
typer.echo(
|
|
f"{email} is already a member of '{SYSTEM_ADMIN_GROUP}'."
|
|
)
|
|
return
|
|
|
|
members.add_member(
|
|
user_id=user_id,
|
|
group_id=admin_group["id"],
|
|
source="cli_break_glass",
|
|
added_by="cli:break-glass",
|
|
)
|
|
typer.echo(
|
|
f"Granted Admin to {email}. Audit source='cli_break_glass'."
|
|
)
|
|
finally:
|
|
try:
|
|
conn.close()
|
|
except Exception:
|
|
pass
|