Commit Graph

815 Commits

Author SHA1 Message Date
9b3cc54646 feat: add backup integrity verification 0.5.5 2026-07-14 16:05:28 +03:00
c3ad0afc17 refactor: remove rejected dataset review feature 2026-07-14 15:56:31 +03:00
2a56ea5fc9 test: fix backend and frontend test contracts 2026-07-14 10:43:38 +03:00
66497da72b feat(mapper): secure xlsx upload and dataset selection 2026-07-14 00:34:10 +03:00
d630573402 fix(backup): orthogonal code review fixes + UI/UX overhaul
## Critical fixes
- H1: Fix env_id/env/environment_id triple inconsistency in API route
  (_action_routes.py now passes 'environment_id', matches scheduler)
- H2: Decompose BackupPlugin.execute() — CC 13 → 5 methods, CC ≤ 5 each
- H3: Fix unhandled int() ValueError on non-numeric dashboard_ids
- H4: Add concurrent guard test with API-style params (env key fallback)
- H5: Make RetentionPolicy configurable via StorageConfig
  (retention_daily/weekly/monthly in config model + backend plugin)
- Fix: storage DELETE route missing 'await' on async delete_file (bug)

## UI/UX overhaul
- NEW: centralized cron utility (frontend/src/lib/utils/cron.ts)
  - validateCron(), calcNextCronRun(), formatNextRun()
  - Used by BackupManager, BackupDashboardModal
- BackupManager: replace custom BackupList with shared FileList
  - Adds: download, delete, bulk actions, search, sort, pagination
  - Adds: cron next-run preview below schedule input
  - Adds: auto-open TaskDrawer on backup task creation
- BackupDashboardModal: dead 'Cron Help' button removed
  - Adds: live cron validation + next-run preview
- StorageSettings: adds retention daily/weekly/monthly fields
- BackupCreateRequest type fixed to match actual API contract
- i18n: 7 new keys for en/ru (next_run, retention_*)
2026-07-13 20:58:02 +03:00
2819ca3a15 semantic 2026-07-13 17:24:39 +03:00
ed85e0d80a feat(git): clarify dashboard release flow 2026-07-13 16:53:35 +03:00
2eca5b514b docs(specs): complete speckit packages 036-039 2026-07-13 15:10:07 +03:00
c2bd6cb441 feat(git): clarify dashboard release flow 2026-07-13 12:55:24 +03:00
00d2619c86 fix: align DRAFT integration test with removed DRAFT check in validate_job_preconditions
- DRAFT validation was removed from orchestrator_validation.py (moved to service layer)
- Integration test expected ValueError for DRAFT jobs — fixed to test actual behavior
- 194/194 integration tests pass, 0 failures
2026-07-12 19:44:11 +03:00
a39a76c87f feat(agent-centric-logging): consolidate CoT infra in shared, close REASON→REFLECT chains
- shared/cot_logger.py is SSOT; backend/cot_logger.py deleted
- elapsed_ms timing in all REFLECT markers
- Frontend: REASON→REFLECT/EXPLORE in all fetch/post/delete/requestApi
- Dynamic src: route.GET.api.plugins instead of hardcoded api.request_handler
- trace_id generated immediately (no 'no-trace'), X-Trace-ID in both directions
- Global error handlers (window error + unhandledrejection + error.svelte)
- Fixed duplicate logging (shared/logger.py double StreamHandler)
- propagate=False in configure_logger (was in ConfigManager = duplicated startup logs)
- belief_scope: 'Coherence OK' → '{anchor}: completed' + elapsed_ms
- Fixed 28 pre-existing test failures (scheduler sig, DB columns, DRAFT validation, etc)
2026-07-12 19:30:57 +03:00
24d3b7d1f9 refactor(task-manager): implement task resilience and execution lifecycle improvements
Enhance the reliability and observability of the task execution engine
by introducing retry mechanisms, idempotency, and structured progress
tracking.

- Implement centralized retry logic with exponential backoff support
  in `JobLifecycle`.
- Add `retry_task` API endpoint and `TaskManager` method for manual
  task restarts.
- Introduce task idempotency using `_idempotency_key` to prevent
  duplicate executions.
- Add `retry_count`, `max_retries`, `last_error`, and `progress` fields
  to the `Task` model and ensure persistence via `TaskPersistenceService`.
- Upgrade `SchedulerService` to use differential synchronization with
  the persistent `SQLAlchemyJobStore` for better job durability.
- Implement structured heartbeat logging to support real-time progress
  updates.
- Update project documentation and ADRs to reflect the new plugin
  runtime and task resilience patterns.
- Add comprehensive unit and integration tests for the new task
  lifecycle features.
2026-07-12 15:31:56 +03:00
0cb1f80cd6 feat(git): implement deployment tracking and enhance lifecycle UX
Introduce a deployment recording system to track dashboard versions
across environments and improve the Git management user experience.

- Add `Deployment` model and Alembic migration to persist deployment
  history.
- Implement `GitDeploymentRecorder` and `GitFingerprint` plugins to
  automate deployment logging and content hashing.
- Add `get_deployment_status` API endpoint to retrieve real-time
  environment states.
- Refactor `GitLifecycleHeader` to prioritize Call-to-Action (CTA)
  buttons and improve visual hierarchy.
- Update `GitWorkspacePanel` to emphasize version saving and
  streamline commit workflows.
- Enhance `GitEnvironmentTimeline` with deployment status integration,
  collapsible UI, and improved theme consistency.
- Add auto-navigation logic in `GitManagerModel` to guide users to
  relevant tabs based on recommended actions.
- Clean up obsolete documentation and update i18n strings for
  git visualization features.
2026-07-12 14:57:03 +03:00
b39d9991b9 fix(logs): resolve old prod execution issues + full GRACE-Poly compliance
- translate: pure-skip scheduled runs now COMPLETE (not FAILED); extract _compute_final_status
- scheduler: cron validation at update; pre-validate + skip legacy bad expr (/15*) in load
- git: robust get_branch_commits (existence check for 'prod' to avoid fatal)
- health: use explore for network/auth failures (reduces spam)
- Full semantic protocol updates across modules:
  - complete #region/#endregion + @BRIEF/@PRE/@POST/@INVARIANT/@RELATION/@RATIONALE
  - belief_scope + CoT markers (reason/explore/reflect)
  - semantics-testing compliance in tests
- Addresses exact symptoms from container_backend.log and backend/logs/app.*

Related to 039-dashboard-scenario-ui log analysis.
2026-07-10 12:35:07 +03:00
3404967f76 feat(git): add environment timeline visualization and branch commit APIs
Implement a new Git environment timeline component to visualize dashboard
versions across different deployment stages (Development, Pre-production,
and Production). This includes new backend endpoints and frontend
services to support historical data retrieval and version comparison.

- Add `get_branch_commits` and `get_commit_diff` endpoints to backend
  API and Git service.
- Implement `GitEnvironmentTimeline` Svelte component for visual
  representation of deployment history.
- Update `GitManagerModel` to manage timeline state, including
  environment histories and version selection for comparison.
- Add `getBranchCommits` and `getCommitDiff` methods to `gitService`.
- Improve UX by separating the branch selector from the version map.
- Add comprehensive i18n support for the new visualization features.
2026-07-10 10:55:10 +03:00
db07bbb1d5 feat(maintenance): improve store with pending removals + ADR-0006 compliance
- Add pendingRemovals tracking and isEventRemoving() to maintenance store for better in-flight UX in EventsTable.
- Strongly type maintenance API client and store (replace unknown[]).
- Migrate selectedTask/taskLogs to dedicated lib/stores/selectedTask.svelte.ts (proper rune store with separate subscribers).
- Remove legacy central stores.svelte.ts and related dead code (src/pages/, old tests) to comply with ADR-0006 (global stores must be individual files in lib/stores/).
- Update mocks, components, models and tests accordingly.
- Fix related bugs (subscriber decoupling, test mocks).
- Add dedicated test_selectedTask.ts.
- Minor cleanups: semantic tokens, @RATIONALE for model-first, contracts update.
- All key tests (maintenance, selectedTask, store) pass.

Refs: ADR-0006, specs/031-maintenance-banner
2026-07-09 22:14:01 +03:00
fd9218a722 chore(agents): remove deprecated agent definitions and add task CRUD tests
Remove several legacy agent configuration files from the `.kilo/` directory and add new unit tests for task CRUD operations in the backend API routes.

- delete .kilo/agent/swarm-master.md
- delete .kilo/agents/closure-gate.md
- delete .kilo/agents/mcp-backend-coder.md
- delete .kilo/agents/swarm-master.md
- delete .kilo/agents/tester.md
- add backend/src/api/routes/__tests__/test_tasks_crud.py
- update backend/src/api/routes/__tests__/conftest.py to include test database URLs
2026-07-08 21:19:33 +03:00
3b13c67c0d feat(translate): language detection, async HTTP LLM, history model, agent improvements
- Add async HTTP-based LLM transport (_llm_async_http.py)
- Add orthogonal LLM call tests
- Improve language detection (_lang_detect.py) and batch insert
- Update translate schemas, service utils, preview constants/prompts
- Add TranslateHistoryModel with pagination and filtering
- Update agent confirmation, persistence, langgraph setup, run, tools
- Improve LLM health checking in shared module
- Update translate runs API, history route
2026-07-08 19:35:49 +03:00
e6532c8dab refactor(translate): remove DRAFT status from UI, auto-transition via preflight
- Remove DRAFT badge, 'Mark as READY' button, DRAFT filter pill, DRAFT run gate
- Auto-transition DRAFT<->READY based on runReady (all required preflight items)
- Move PreflightChecklist to page top — always visible across tabs
- Remove orchestration DRAFT gate — preflight handles readiness
- Remove 10 dead i18n keys (status_draft, mark_ready, disabled_draft, hint_draft)
- Add reverse transition READY->DRAFT when fields cleared
- Remove unused runComplete prop from RunTabContent
- Add fallback badge styling for unrecognized statuses
2026-07-08 19:35:05 +03:00
2d0fe96a63 chore: add GRACE semantic contracts across agent + backend + build scripts
- Add @RELATION/@RATIONALE/@REJECTED headers to agent modules
- Add GRACE contracts to backend services, models, schemas
- Update build.sh with single-image build commands (build:backend|frontend|agent)
- Update docker entrypoint: openssl rsa → openssl pkey (alg-agnostic)
- Add @RATIONALE to backend core modules (cot_logger, config_manager, ssl)
2026-07-08 11:10:59 +03:00
25643a5656 test(frontend): reach coverage targets — 99.45% stmts, 89.14% branches, 99.71% fns, 99.82% lines
Add 813 new tests (+31.6%) to bring all covered files to thresholds:
- 4 zero-coverage models (KeyRecovery, BulkReplace, TopNavbar,
  TranslationRunResult) → 100% with L1 model-invariant tests
- 8 low-coverage models extended past thresholds
- UI components (Pagination 1→31, Skeleton 20, Badge 27, ConfirmDialog 21)
- API modules (api.ts, cot-logger, maintenance, reports) → 100%
- Utils/stores (dateFormat, timezone, toasts, stores, maintenance)

Production changes:
- Add GRACE contract headers (@RATIONALE/@REJECTED) to 10+ files
- Fix batcheslength→batches.length typo in TranslationRunResult.svelte
- Refactor Badge.svelte || expressions into cls() helper
2026-07-08 11:09:52 +03:00
d0facf4a3a fix(translate): datasource change not persisted on save + preview column cleanup
Root cause: saveJob() used stale sourceDatasourceId (set once on load)
instead of live datasourceId (updated by ConfigTabForm via $bindable).
Since sourceDatasourceId was always truthy, the || fallback to datasourceId
never triggered — the old datasource ID was always sent to PUT.

Fixes:
- Removed dead sourceDatasourceId atom; saveJob() uses datasourceId directly
- Bound sourceTable via $bindable through ConfigTabForm; updated on select
- loadDatasourceColumns() syncs databaseDialect from Superset columns API
- saveJob() sends undefined for database_dialect="unknown" to force re-detect
- Backend: added direct_db+connection_id validation on update (mirroring create)
- Removed redundant "Язык ист." column from TranslationPreview table
- Removed unused getDetectedLang function

Tests:
- TranslationJobModel: datasourceId save mapping, dialect sync, unknown→undefined
- TranslateJobService: reject direct_db without connection_id, preserve existing

Verified: browser — translate_cross datasource persisted after save+reload,
dialect detected as "clickhouse", columns loaded (2), translation column preserved.
2026-07-07 23:50:08 +03:00
34aeeb92a2 fix(backend+frontend): migration deadlock, async pattern, timeout safety, fire-and-forget translations
Backend:
- MigrationPlugin.execute — remove AsyncJobRunner.run() deadlock on post-migration
  ID sync (2 deadlocks total: plugins/migration.py + api/routes/migration.py
  trigger_sync_now). Replace blocking runner.run with direct await.
- MigrationPlugin.execute — fix temp file leak (dry_run=True prevented cleanup).
- MigrationPlugin.execute — IdMappingService(SessionLocal()) now closed in finally.
- MigrationPlugin.execute — wire IdMappingService into MigrationEngine constructor
  so cross-filter patching actually works instead of silently skipping.
- MigrationPlugin.execute — SupersetClient.aclose() in finally to prevent
  httpx connection pool leak.
- TaskManager — _async_tasks dict leak (add_done_callback cleanup).
- JobLifecycle — CancelledError handler (tasks stuck in RUNNING after cancel).
- JobLifecycle — persist_task BEFORE _broadcast_task_status (crash consistency).
- JobLifecycle — wait_for_resolution/wait_for_input now have 3600s timeout.
- AsyncJobRunner.run — 300s timeout on future.result() (APScheduler thread safety).

Translate scheduler:
- execute_scheduled_translation — replace blocking runner.run(orch.execute_run(run))
  with fire-and-forget TranslationOrchestrator.execute_background(). APScheduler
  thread is freed in ms instead of blocking for the full translation duration.
  Translation runs of 10k+ rows (200+ LLM batches, hours) no longer hit the
  300s runner timeout.
- TranslationOrchestrator.execute_background — new static method: opens own DB
  session, dispatches asyncio.create_task, handles errors + notification.
- Scheduler last_run_at updated at dispatch time (not after completion).

Frontend:
- MigrationModel.stepReady[3] now requires dryRunResult != null (was always
  true, allowing UI to reach step 3 without dry-run).
- WizardModel.goToStep gate for step 3 uses stepReady[3].
- +page.svelte  — dryRunResult no longer self-clears via reactive loop.
- Progress bar step 3 indicator gate fixed for new readiness logic.

Tests:
- 2 new regression tests for migration sync (deadlock-free, completes cleanly).
- test_migration_plugin.py — _make_mock_superset_client/_make_mock_mapping_service
  helpers for proper async mock behavior (aclose, sync_environment AsyncMock).
- 10 scheduled-translation tests updated for fire-and-forget pattern.
- MigrationModel.test.ts — step 3 invariant + goToStep block test.
- All affected tests: 104 backend + 79 frontend = 183 passed.
2026-07-07 21:04:23 +03:00
3f6d7222c3 fix(agent): proxy gradio config and reduce translate blocking 2026-07-07 17:37:36 +03:00
cfb95fa3c8 refactor(agent): extract agent+shared into standalone packages with full GRACE semantic markup
- Move agent code from backend/src/agent/ to agent/src/ss_tools/agent/
- Extract shared stdlib-only utilities to shared/src/ss_tools/shared/
- Add #region/#endregion contracts to all ~140 functions (INV_1 compliance)
- Update docker files, entrypoint, build scripts for new package layout
- Backend now imports ss_tools.shared._llm_health (no gradio/langchain deps)
- Add specs for 036-039 feature plans
2026-07-07 15:18:24 +03:00
da6a3f28ad fix(agent): rewrite _llm_health to use openai+httpx instead of langchain
Previous lazy-import fix still required langchain at function call time.
Root cause: langchain_openai/langchain_core are only in requirements-agent.txt,
not requirements-backend.txt. The /api/agent/llm-status endpoint runs in
the backend container which has 'openai' but not 'langchain'.

Rewrite _check_llm_provider_health() to use:
- AsyncOpenAI from 'openai' package (in both containers)
- httpx to call /api/agent/llm-config on localhost (same as agent does)
- system_ssl_context() for SSL (same as LLM test endpoint)
- openai exceptions (APIConnectionError, APITimeoutError, etc.)

No langchain dependency at all — works in both backend and agent containers.

Verified: 977 tests passed, import without langchain succeeds.
2026-07-07 13:34:07 +03:00
ff2f1825a8 fix(agent): lazy imports in _llm_health — langchain_core not in backend container
_llm_health.py imported langchain_core, langchain_openai, and openai at
module level. These packages are only installed in the agent container
(requirements-agent.txt), not the backend container (requirements-backend.txt).

Moved all langchain/openai imports inside _check_llm_provider_health() with
ImportError handled gracefully — returns 'unavailable' status instead of
ModuleNotFoundError 500 error.

Root cause: the /api/agent/llm-status endpoint runs in the backend container,
which has httpx but not langchain. The agent container has all LLM deps.

Verified: import without langchain succeeds, health check returns 'unavailable'.
2026-07-07 13:24:45 +03:00
89cd123dec fix(frontend): dynamic year + git commit hash in APP_VERSION
- Footer.svelte: replace hardcoded '2025' with new Date().getFullYear()
- build.sh: append git short hash to APP_VERSION for all bundle commands
  (bundle, bundle:embeddings, bundle:light). Format: '0.5.2+6f029903'.
  Previously only the tag was passed (e.g. '0.5.2'), and .git was not
  available in Docker context so vite.config.js fell back to '0.0.0'.

Verified: frontend assets contain '0.5.2+6f029903', getFullYear() replaces
hardcoded 2025.
2026-07-07 12:29:46 +03:00
6f02990347 fix(ssl+agent): capath for all HTTP clients + isolate gradio import
SSL fix (ADR-0009 Finding 7):
- Replace ssl.create_default_context() with system_ssl_context(capath)
  in client_registry.py, async_network.py, notifications/providers.py,
  git/_base.py. Previous fix (0.5.1) only covered LLM clients; the
  Superset API client still used ssl.create_default_context() which
  loads cafile (flat bundle) where OpenSSL 3.x ignores intermediate CA
  certificates. system_ssl_context() uses capath only (hash symlinks).

Agent fix:
- Extract _check_llm_provider_health + _llm_status from agent/app.py
  into agent/_llm_health.py. The /api/agent/llm-status endpoint was
  importing from agent/app.py which triggers 'import gradio' at module
  level. Backend container does not have gradio installed, causing
  ModuleNotFoundError (500 error) every 30s on health check polling.

Config:
- Add ALLOWED_ORIGINS to docker-compose.yml + docker-compose.enterprise-clean.yml

ADR-0009 updated: Layer 2 table expanded with 4 missing clients,
Finding 5 reconciled (LLM_CA_CERT_URLS restored in 0.5.1), version 0.5.2.

Verified: 1110 unit tests passed, gradio import isolation confirmed.
2026-07-07 12:18:43 +03:00
1182b29fe0 fix(certs): restore HTTP CA auto-download and test edge matrix
Restore LLM_CA_CERT_URLS support for corporate PKI HTTP cert delivery.
Downloaded certificates are installed into the llm/ CA category and share
the same system trust + NSS import path as CERTS_PATH-mounted certs.

Changes:
- certs.sh: add download_llm_ca_certs with HTTP-only curl policy,
  PEM/DER handling, retries, llm/ storage, hash symlinks for llm+custom
- backend/agent entrypoints: run download before install_all_certs
- compose/env/docs: expose LLM_CA_CERT_URLS again and update ADR-0009
- integration tests: cover PEM/DER/CER, invalid certs, non-HTTP skips,
  query-string filenames, private/server skips, empty inputs, combined
  LLM_CA_CERT_URLS + CERTS_PATH channels, and NSS imports

Verified:
- 194 passed, 1 skipped integration tests
- full backend container smoke passed with testcontainers PostgreSQL
- docker bundle rebuilt for 0.5.0
2026-07-07 10:23:49 +03:00
702ee25ae4 fix(docker): add missing certs.sh COPY to backend/all-in-one Dockerfile
Backend entrypoint sources certs.sh for CA certificate installation,
but the file was never copied into the Docker image — causing
container crash loop on startup (regression in 7f932610).

Changes:
- docker/backend.Dockerfile, docker/all-in-one.Dockerfile: COPY certs.sh
- docker/backend.entrypoint.sh: remove dead install_llm_ca_certs,
  install_certificates (replaced by docker/certs.sh); update @INVARIANT
- backend/src/core/ssl.py: fix describe_context() to report actual
  system cert count (SSLContext.capath attr does not exist in Python 3)
- __tests__: rewrite stale tests asserting LLM_SSL_VERIFY=false →
  verify=False; behaviour is permanently removed — always CERT_REQUIRED
- backend/tests/integration/test_backend_container.py [new]: 5 tests
  verifying certs.sh presence, sourceability, and full-stack smoke
  (testcontainers PG → entrypoint → migrations → health)
- conftest.py: restore health-wait loop and fixtures in superset_container
- ADR-0009, README.md, scripts, .env: align docs with centralized SSL
2026-07-07 00:58:41 +03:00
aafd89f2c7 test(integration): add encrypted key Superset container test with SSL_KEY_PASSPHRASE
conftest.py: superset_container fixture supports {encrypted_key: True}
  - Writes encrypted private key to container
  - Decrypts with openssl rsa -passin env:SSL_KEY_PASSPHRASE
  - Starts Flask/Werkzeug TLS server with decrypted key
  - Falls back to unencrypted key for existing tests

test_superset_tls_custom_ca.py:
  - NEW: TestEncryptedPrivateKeySuperset class
    - test_superset_health_over_tls_with_encrypted_key
    - test_openssl_capath_encrypted_key
  - Uses parametrize({tls: True, encrypted_key: True})

Validates full production flow: encrypted key → SSL_KEY_PASSPHRASE
→ openssl decrypt → TLS handshake → client trust via capath.
2026-07-06 21:21:42 +03:00
7f93261060 refactor(ssl): centralize SSL trust management, remove LLM_SSL_VERIFY
Centralized SSL via one contract: CERTS_PATH=/opt/certs mounted into all containers.

Backend:
  - NEW: backend/src/core/ssl.py — system_ssl_context(), httpx_verify(),
    cert_dir_inventory()
  - LLMClient._get_ssl_verify() → delegates to core.ssl
  - _llm_async_http._get_verify() → delegates to core.ssl
  - Removed LLM_SSL_VERIFY env reading from all runtime code

Docker:
  - NEW: docker/certs.sh — shared cert installer (PEM/DER/cer to .crt conversion,
    update-ca-certificates, hash symlinks, NSS import)
  - NEW: docker/agent.entrypoint.sh — agent entrypoint with cert installation
  - backend.entrypoint.sh → uses certs.sh instead of install_llm_ca_certs
  - Dockerfile.agent → adds ca-certificates, openssl, entrypoint

Compose:
  - Removed LLM_CA_CERT_URLS and LLM_SSL_VERIFY from all compose files
  - Added CERTS_PATH volume mount to agent (dev + enterprise)
  - Added certs volume mount to backend/agent in dev compose

Env examples:
  - Removed LLM_SSL_VERIFY, LLM_CA_CERT_URLS from .env.example,
    .env.enterprise-clean.example, .env.current.example, .env.master.example,
    backend/.env.example
  - Enhanced CERTS_PATH comments with accepted formats

Diagnostics:
  - diag_container.py: removed LLM_* checks, added CERTS_PATH inventory,
    uses core.ssl for context creation

Tests:
  - Updated test_llm_analysis_service, test_llm_async_http,
    test_client_headers to verify centralized ssl context (no env disable)
  - 4/4 SSL tests pass
2026-07-06 21:00:28 +03:00
4590e1d3cd fix(scripts): fix --target arg parsing in diag_container.py 2026-07-06 20:37:22 +03:00
e2f3c8165d docs(adr): reference ADR-0009 SSL cert management findings
Production SSL failure for lite.ai.rusal.com confirmed: LLM_CA_CERT_URLS
not set → LLM CA certs not downloaded. System CA store has corporate
certs from /opt/certs but lite.ai.rusal.com uses a different CA.

Diagnostic script scripts/diag_container.py covers all 6 check categories
per ADR-0009: env, system CA, openssl capath/cafile, Python SSLContext,
httpx connectivity, encryption health.

Fix: set LLM_CA_CERT_URLS in .env.enterprise-clean or place the CA .crt
in ./certs/ on the host. Run diag_container.py to verify.
2026-07-06 20:27:28 +03:00
912a3f0f70 feat(scripts): add container diagnostic script for SSL cert + encryption health
Checks 6 categories:
  1. Environment — ENCRYPTION_KEY, LLM_SSL_VERIFY, LLM_CA_CERT_URLS
  2. System CA store — ca-certificates.crt, custom/LLM certs, hash symlinks
  3. OpenSSL connectivity — cafile vs capath (per ADR-0009 Finding 7)
  4. Python SSLContext(capath) — what _get_ssl_verify() uses
  5. httpx(capath) — integration test
  6. Encryption key health — decrypt test for all LLM provider api_keys

Usage:
  docker cp scripts/diag_container.py superset-tools-backend-1:/tmp/
  docker compose exec backend python3 /tmp/diag_container.py --target lite.ai.rusal.com:443
2026-07-06 20:27:03 +03:00
ac5a139dc9 fix(ui): render KeyRecoveryWizard into body portal to avoid layout margin
Modal now mounts at document.body level via svelte mount/unmount.
Extracted WizardContent.svelte for portal rendering.
Eliminates 32px margin from page layout wrapper
(max-w-7xl/space-y-6/px-4 container).

Added KeyRecoveryWizard as portal wrapper, WizardContent as
the actual modal component.
2026-07-06 19:00:24 +03:00
680da3baa3 xz -3 2026-07-06 18:26:31 +03:00
eef7a459ea fix(security): address QA/security audit findings — authorization, i18n, error safety
Critical (C1): Added has_permission('security', 'READ') to /health and
  /fingerprint endpoints; has_permission('security', 'WRITE') to /recover.
  Previously any authenticated user could enumerate encrypted secrets and
  overwrite stored values.

High (Bug #1): Fixed recover endpoint — updated/failed status now correctly
  reflects whether a non-empty replacement value was submitted. Empty values
  now report 'skipped' instead of falsely 'updated'.

High (Bug #2, #3): Replaced all hardcoded English strings in
  KeyRecoveryWizard.svelte and SystemSettings.svelte with $t.settings.*
  i18n lookups. Keys already existed in en/ru settings.json.

High (H1): Added _sanitize_error() helper to truncate + scrub exception
  messages before logging, preventing potential secret leakage in log output.

Cleanup: Moved LLMProviderConfig import to module top. Instantiate
  ConnectionService once before for-loop. Added @TEST_EDGE declarations
  and @PRE/@SIDE_EFFECT to C4 contract.

Tests: 226 passed
2026-07-06 18:22:36 +03:00
99ccf64458 fix(i18n): remove duplicate closing braces in encryption recovery strings 2026-07-06 18:07:44 +03:00
e1b0175ec4 feat(security): add encryption health inventory and key recovery wizard
Backend:
  - GET /api/security/encryption/health — inventory of all stored encrypted
    secrets (LLM providers, DB connections, profile Git tokens) with
    decrypt attempt and structured broken/healthy status
  - GET /api/security/encryption/fingerprint — non-secret key fingerprint
  - POST /api/security/encryption/recover — bulk replacement of
    undecryptable secrets with partial_success semantics

Frontend:
  - KeyRecoveryModel.svelte.ts — state machine (idle→scanning→
    healthy/needs_recovery→editing→saving→complete/partial_success/error)
  - KeyRecoveryWizard.svelte — tabbed dialog with LLM/DB/Git sections,
    security guidance, re-encrypt command display, edit/save flow
  - SystemSettings entry point — 'Check encrypted secrets' card with
    fingerprint and broken count
  - API methods: getEncryptionHealth, recoverEncryptedSecrets
  - Types: EncryptionRecoveryTypes
  - i18n: en/ru strings for recovery flow

Tests: 226 passed
2026-07-06 18:05:05 +03:00
5d5590d9d9 fix(agent): pin gradio <6 to avoid breaking ChatInterface API changes 2026-07-06 16:18:55 +03:00
09d83fad98 fix(docker): add alembic to requirements-backend.txt, entrypoint needs it for migrations 2026-07-06 15:49:48 +03:00
2716f15804 refactor(env): unify Docker env vars — canonical AUTH_SECRET_KEY, remove JWT_SECRET fallback
Canonical variables:
  - AUTH_SECRET_KEY — JWT signing key for backend + agent (was split across
    AUTH_SECRET_KEY / JWT_SECRET)
  - SERVICE_JWT — agent→backend service token
  - No JWT_SECRET fallback: decoder fails with migration guidance if only
    JWT_SECRET is set

Compose files unified:
  - docker-compose.yml, docker-compose.enterprise-clean.yml,
    docker-compose.e2e.yml — all use AUTH_SECRET_KEY
  - build.sh generated compose now passes AUTH_SECRET_KEY + ENCRYPTION_KEY
    to backend

Env examples unified and completed:
  - .env.example — comprehensive template, all compose vars
  - .env.enterprise-clean.example — production template
  - backend/.env.example — backend-only run
  - docker/.env.agent.example — agent-only run
  - NEW: .env.current.example, .env.master.example,
    .env.e2e.example, frontend/.env.example

Tests aligned:
  - conftest sets AUTH_SECRET_KEY (canonical value matched across test files)
  - test mocks use canonical name
  - 1176 passed, 0 failed
2026-07-06 14:24:17 +03:00
ef3ce378bf refactor(agent): lightweight JWT decoder — JWT_SECTRET first, AUTH_SECTRET_KEY fallback
Replaced src.core.auth.jwt.decode_token import with local _jwt_decoder.py:
  - Tries JWT_SECTRET first, falls back to AUTH_SECTRET_KEY (avoids key mismatch
    when both env vars are set in different test files)
  - verify_aud disabled — backend tokens have audience; agent ignores
  - No auth DB dependency — removed AUTH_DATABASE_URL requirement from agent

Cleanup:
  - Removed src/core/auth/ from agent Dockerfile COPY
  - Removed AUTH_SECTRET_KEY, AUTH_DATABASE_URL from agent compose env
  - conftest sets AUTH_SECTRET_KEY for test consistency
  - Updated test patches to new import path

Tests: 1176 passed, 0 failed
2026-07-06 13:45:22 +03:00
fcfea2ddc8 refactor(agent): use local JWT decoder instead of src.core.auth.jwt
Replace src.core.auth.jwt import with lightweight _jwt_decoder.py that
uses jose.jwt directly with JWT_SECRET env var. Avoids pulling AuthConfig
→ AUTH_DATABASE_URL/SECRET_KEY validators → SQLAlchemy models into agent.

Removed: AUTH_SECRET_KEY, AUTH_DATABASE_URL from agent compose env.
Removed: src/core/auth/ copies from Dockerfile.agent COPY section.
Added:   src/agent/_jwt_decoder.py — stateless JWT validation.
2026-07-06 13:37:08 +03:00
a141ffcd76 fix(agent): add libpq5 system dep for psycopg v3 (langgraph checkpoint) 2026-07-06 12:23:35 +03:00
bdb20e7132 fix(agent): pass AUTH_DATABASE_URL to agent container, auth config requires it 2026-07-06 12:19:14 +03:00
752dc1cbaa fix(agent): resolve missing imports — jose, auth config, AUTH_SECRET_KEY
- Added python-jose[cryptography] to requirements-agent.txt
- Made sqlalchemy.orm.Session and TokenBlacklist imports lazy in jwt.py
  so decode_token works without pulling ORM models into agent image
- Added src/core/auth/__init__.py, config.py, jwt.py to agent Dockerfile COPY
- Added AUTH_SECRET_KEY env var to agent compose (reads from JWT_SECRET)
2026-07-06 12:13:26 +03:00
789478ea16 docs(adr): document agent source copy strategy and logger.py dependency 2026-07-06 11:35:57 +03:00