Compare commits

..

79 Commits

Author SHA1 Message Date
devops b89289989a docs: document owner password persistence fix in deployment.md and changelog
CI - Build & Test / Backend (.NET) (push) Successful in 32s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-21 10:28:53 +02:00
devops f95463ef50 fix: permanent owner password persistence with SeedAudit guard
CI - Build & Test / Backend (.NET) (push) Successful in 28s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 2s
Root cause: Dual-source architecture for owner password (Gitea secret
ENV_OWNER_PASSWORD vs host .env OWNER_PASSWORD) caused drift when
the DB was ever re-seeded or the volume recreated.

Changes:
- Add SeedAudit entity + migration to track one-time seed operations
- EnsureDatabaseAsync checks SeedAudit BEFORE seeding — owner is never
  re-created even if the Users table is wiped
- Deploy and rollback workflows now read OWNER_PASSWORD from the host's
  persistent .env (single source of truth) instead of Gitea secrets
- compose.yaml documented: OWNER_PASSWORD only used during initial seed
- Cleanup: .gitignore extended for core dumps, changelog/deployment.md
  updated with 2026-06-20 session notes

After this fix the DB is the single source of truth for the owner
password after initial seed. The host .env is the single reference
for the initial value.
2026-06-21 10:15:36 +02:00
devops 2d218853a5 Fix activity repository test double
CI - Build & Test / Backend (.NET) (push) Successful in 31s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 4s
2026-06-20 20:25:42 +02:00
devops adae7ba26d feat: ship agent progress visibility
CI - Build & Test / Backend (.NET) (push) Failing after 31s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 4s
2026-06-20 20:22:54 +02:00
devops 3dd745586b retrigger: force deploy pipeline via push
CI - Build & Test / Backend (.NET) (push) Successful in 32s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 4s
2026-06-20 19:05:33 +02:00
devops f0023ac033 fix: use external deploy script to avoid nested quoting errors
CI - Build & Test / Backend (.NET) (push) Successful in 29s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 4s
The inner shell script run via docker:cli had complex escaping
that caused 'unterminated quoted string' errors at runtime.
Moved the deploy logic to an external script file (heredoc in
the workflow YAML), mounted read-only into the docker:cli
container. Pass BUILD_ARGS and SERVICE via environment
variables instead of shell interpolation.
2026-06-20 19:00:53 +02:00
devops 73c5eb69d7 fix: ensure zombie container cleanup before deploy + verbose pg_resetwal
CI - Build & Test / Backend (.NET) (push) Successful in 34s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 20s
CI - Build & Test / Security Check (push) Successful in 4s
2026-06-20 18:57:54 +02:00
devops 06eac66baa fix: postgres WAL corruption recovery + memory bump + researcher/executor
CI - Build & Test / Backend (.NET) (push) Successful in 30s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 4s
- Postgres memory: 256M→384M limits, 64M→96M reservations
- Added pg_resetwal -f pre-deploy step to recover from corrupt WAL
  ('PANIC: could not locate a valid checkpoint record' caused by
  force-killed postgres during --force-recreate)
- Added data-checksums initdb arg for future corruption detection
- api→postgres and web→api depends_on: service_healthy→service_started
- Deploy wait loop: fail fast on unhealthy, wait on starting (180s)
- Added researcher/executor to ValidAssignees and frontend dropdowns
2026-06-20 18:56:11 +02:00
devops b95bec7915 fix: relax web→api dependency + smarter wait loop
CI - Build & Test / Backend (.NET) (push) Successful in 31s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 4s
- web's depends_on on api: change from service_healthy to
  service_started+restart (same as api→postgres fix)
- deploy wait loop: fail fast on unhealthy, wait on starting,
  increased timeout to 180s (36×5s)
2026-06-20 18:50:29 +02:00
devops 071be50977 fix: relax api→postgres dependency to service_started+restart
CI - Build & Test / Backend (.NET) (push) Successful in 32s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 4s
depends_on: condition: service_healthy on the api service was
failing during docker compose up because postgres hasn't completed
its healthcheck yet (start_period=30s). Changed to
condition: service_started with restart: true so the API
starts as soon as postgres is running and retries if the
DB isn't ready yet. The .NET backend already handles
transient DB connection failures.
2026-06-20 18:48:34 +02:00
devops baf4008d97 fix: remove --wait flag causing premature deploy failure, use manual health loop
CI - Build & Test / Backend (.NET) (push) Successful in 28s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 4s
The docker compose --wait flag times out before postgres can
become healthy (start_period=30s). Replaced with explicit
poll loop (5s interval, up to 120s) that checks ps output
for unhealthy/starting states.
2026-06-20 18:46:27 +02:00
devops 83e072bc27 feat: Bao/Iris-Statusrechte + Bao→Iris-Notifications + Agent-Workflow-Übersicht
CI - Build & Test / Backend (.NET) (push) Successful in 29s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 4s
- Bao darf jetzt Status ändern (neben Iris), Sub-Agents weiterhin nicht
- CanEditContent für Inhaltsbearbeitung durch alle bekannten Caller
- Bao-Content-Änderungen triggern task_content_changed-Notification an Iris
- Bao-Status-Änderungen triggern task_status_changed-Notification an Iris
- Iris-Status-Änderungen triggern task_status_changed-Notification an Bao
- Neue WorkTask-Felder: IsAgentTask (bool), ExpectedFrom (string)
- Agent-Workflow-API: CreateAgentTask, WaitingTasks, AgentOverview
- Frontend: Agent-Task-Badge, Iris-Overview-Panel, isBao-Getter
- Login-Rate-Limiter mit strukturiertem JSON-Fehlermeldungs-Body
- Volume-Name: nexus-postgres → postgres-data (Standardisierung)
2026-06-20 18:43:05 +02:00
devops a516353ae8 fix: SettingsView owner→canManageUsers (owner || admin)
CI - Build & Test / Backend (.NET) (push) Successful in 32s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 4s
Vorher war isOwner (= nur owner) gesetzt, was admins die User-Verwaltung
verweigerte. Jetzt: canManageUsers = role===owner || role===admin.

Delta: 1 Datei, 4 Zeilen (2 Logic, 1 Kommentar, 1 v-if).
Builds: Backend 0 Errors, Frontend 0 Errors.
2026-06-20 14:29:34 +02:00
devops 1df663f57c fix: AdminController roles hardened (owner+admin) + SettingsView visibility
CI - Build & Test / Backend (.NET) (push) Successful in 31s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 5s
- [Authorize(Roles = "owner,admin")] statt nur owner – admin darf jetzt
  ebenfalls User verwalten
- CreateUser erlaubt nur Rollen admin|user|viewer; owner ist blockiert
- UpdateUserRole erlaubt nur admin|user|viewer; owner kann weder gesetzt
  noch überschrieben werden; admin darf andere admins nicht ändern
  und sich nicht selbst herabstufen
- SettingsView: canManageUsers = role owner || admin statt nur owner
- UI-Dropdown zeigt nur admin|user|viewer (owner als Kommentar notiert)
2026-06-20 14:27:24 +02:00
devops e4091eee80 feat: Multi-User/Admin usermanagement + Galaxy Login/Settings + Task detail improvements
CI - Build & Test / Backend (.NET) (push) Successful in 35s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 20s
CI - Build & Test / Security Check (push) Successful in 4s
- Backend: NEW AdminController with user CRUD (GET/POST/DELETE /api/v1/admin/users)
- Backend: NEW GET /api/dashboard/tasks/{id} single task endpoint
- Backend: NEW POST /api/dashboard/tasks/{id}/activity comment endpoint
- Backend: IUserRepository + UserRepository extended with GetAllAsync, DeleteAsync
- Backend: Admin DTOs (AdminUserInfo, AdminCreateUserRequest, AdminUpdateRoleRequest)
- Frontend: NEW TaskDetailView.vue — URL-based (/tasks/:id) Galaxy-themed task detail
  with subtask create/edit/delete, activity with comments, property sidebar
- Frontend: LoginView.vue — полностью Galaxy theme redesign with GalaxyBackground,
  glass-morphism card, password toggle, consistent brand
- Frontend: SettingsView.vue — Galaxy theme redesign with glass cards,
  admin user management section (create/list users, visible only to owner role)
- Frontend: TaskBoardView.vue — added "Full View" link to URL-based detail page
- Frontend: Router — added /tasks/:id route for TaskDetailView
- Frontend: App.vue — added TaskDetail to standaloneViews whitelist
- Frontend: tasks store — stable

Auth: Admin creates accounts, users log in with existing /api/v1/auth/login.
Login/Settings deliver visible Galaxy-consistent design with nexus-tokens.css tokens.
2026-06-20 14:24:40 +02:00
devops dcc8450c62 feat: Phase 2 — Delegated State, Auth, Review-Gate, Notifications, Zombie-Reset
CI - Build & Test / Backend (.NET) (push) Successful in 37s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 24s
CI - Build & Test / Security Check (push) Successful in 4s
2026-06-18 23:47:41 +02:00
devops 12998170e3 fix: update DEPLOY_PATH in all workflows from /opt/openclaw to /home/projekte_bao/openclaw
CI - Build & Test / Backend (.NET) (push) Successful in 27s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-18 21:44:33 +02:00
devops 691152f889 fix: volume paths from /opt/openclaw to /home/projekte_bao/openclaw
CI - Build & Test / Backend (.NET) (push) Successful in 29s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-18 21:41:32 +02:00
devops 74ef58d274 fix: add Traefik labels and proxy network for nexus.noveria.net routing
CI - Build & Test / Backend (.NET) (push) Successful in 30s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-18 21:40:17 +02:00
devops 5e7d074593 feat: Linear-style Task Board mit Drag&Drop
CI - Build & Test / Backend (.NET) (push) Successful in 32s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 19s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-18 21:34:07 +02:00
iris c496608c86 docs: update README, changelog, phases — remove Ollama/NVIDIA refs, current model config, migration history
CI - Build & Test / Backend (.NET) (push) Successful in 28s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-16 15:00:30 +00:00
iris c040696d91 docs: update README, changelog, phases — remove Ollama/NVIDIA refs, current model config, migration history
CI - Build & Test / Backend (.NET) (push) Successful in 31s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-16 15:00:30 +00:00
iris 7ba0bd26fa docs: update README, changelog, phases — remove Ollama/NVIDIA refs, current model config, migration history
CI - Build & Test / Backend (.NET) (push) Has been cancelled
CI - Build & Test / Frontend (Vue/TS) (push) Has been cancelled
CI - Build & Test / Security Check (push) Has been cancelled
2026-06-16 15:00:29 +00:00
iris 4b1d140b53 docs: update README, changelog, phases — remove Ollama/NVIDIA refs, current model config, migration history
CI - Build & Test / Backend (.NET) (push) Has been cancelled
CI - Build & Test / Frontend (Vue/TS) (push) Has been cancelled
CI - Build & Test / Security Check (push) Has been cancelled
2026-06-16 15:00:29 +00:00
developer e0c88238da refactor: extract DI, helpers from Program.cs into extension classes
CI - Build & Test / Backend (.NET) (push) Successful in 1m18s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 48s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-16 16:52:17 +02:00
AzuTear b0e65e3980 style: strengthen flow lines and tighten modal demo parity
CI - Build & Test / Backend (.NET) (push) Successful in 24s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 15:57:12 +02:00
devops 648a5d2151 refactor: move landingpage to separate repo bao/noveria-landing
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 15:53:00 +02:00
devops 1a024eef96 feat: noveria.net landingpage template
CI - Build & Test / Backend (.NET) (push) Successful in 27s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 15:45:23 +02:00
devops 6280e87078 infra: landingpage compose + nginx config
CI - Build & Test / Backend (.NET) (push) Has been cancelled
CI - Build & Test / Frontend (Vue/TS) (push) Has been cancelled
CI - Build & Test / Security Check (push) Has been cancelled
2026-06-14 15:44:51 +02:00
AzuTear 64459ccdb3 feat: wire dashboard v2 to backend data
CI - Build & Test / Backend (.NET) (push) Successful in 25s
CI - Build & Test / Frontend (Vue/TS) (push) Has been cancelled
CI - Build & Test / Security Check (push) Has been cancelled
2026-06-14 15:44:05 +02:00
devops 38dc2efc6c docs: devops deploy-actor documentation
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 15:41:38 +02:00
AzuTear 390bffa208 fix: detect drag state on pointer release
CI - Build & Test / Backend (.NET) (push) Successful in 25s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-14 15:33:51 +02:00
AzuTear e034883abd fix: open agent cards only on click
CI - Build & Test / Backend (.NET) (push) Successful in 25s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 15:23:05 +02:00
AzuTear 6d4e8e7927 refactor: streamline flow board interactions
CI - Build & Test / Backend (.NET) (push) Successful in 25s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 15:11:05 +02:00
reviewer 0f8939306d feat: mobile-responsive dashboard v2
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 12:16:06 +02:00
reviewer 58675f0c69 ops: enhanced deploy verification with web-recovery + incident docs
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 11:31:46 +02:00
reviewer 88cafc7b8e review: remove version-bump from deploy workflow — VERSION is read-only source of truth
CI - Build & Test / Backend (.NET) (push) Successful in 27s
CI - Build & Test / Frontend (Vue/TS) (push) Has been cancelled
CI - Build & Test / Security Check (push) Has been cancelled
2026-06-14 11:31:04 +02:00
reviewer 485357c6dc review: error-handling for config file write + compose resource limits
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Has been cancelled
CI - Build & Test / Security Check (push) Has been cancelled
- AgentsController.SaveConfigFile: catch UnauthorizedAccessException and IOException
  instead of letting them bubble up unhandled; return clean 500 with logged message
- compose.yaml: add deploy.resources.limits.memory and reservations.memory for
  api (512M/128M), web (128M/32M), postgres (256M/64M)
2026-06-14 11:30:25 +02:00
devops 36b32f0e88 chore: bump version to 0.2.56 [skip ci] 2026-06-14 07:50:18 +00:00
reviewer 8a556c25a0 Add local liveness health endpoint
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 09:49:25 +02:00
devops f271602f31 chore: bump version to 0.2.55 [skip ci] 2026-06-14 07:29:01 +00:00
reviewer 63319e1046 fix: stream deploy env into docker cli
CI - Build & Test / Backend (.NET) (push) Successful in 29s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 09:27:56 +02:00
devops b730fa1518 chore: bump version to 0.2.54 [skip ci] 2026-06-14 07:21:34 +00:00
reviewer fadb5d75c4 Fix AgentService tests fixture path
CI - Build & Test / Backend (.NET) (push) Successful in 30s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 09:20:28 +02:00
reviewer 45a39d319f Fix operations CI and snapshots
CI - Build & Test / Backend (.NET) (push) Failing after 25s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 18s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 09:14:24 +02:00
reviewer 5ea7aa9611 fix(ops): mount temp env directory for compose
CI - Build & Test / Backend (.NET) (push) Failing after 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-14 08:48:23 +02:00
devops a6fabb90b0 chore: bump version to 0.2.53 [skip ci] 2026-06-14 06:46:55 +00:00
reviewer db62354c97 fix(ops): pass temp env via compose --env-file
CI - Build & Test / Backend (.NET) (push) Failing after 25s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-14 08:44:42 +02:00
devops 20dedcd6fa chore: bump version to 0.2.52 [skip ci] 2026-06-14 06:42:37 +00:00
reviewer 4ad0f9e493 refactor: SOLID architecture — backend service layer + frontend V2 components
CI - Build & Test / Backend (.NET) (push) Failing after 25s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 17s
CI - Build & Test / Security Check (push) Successful in 2s
## Backend — Service Layer & Repository Refactoring

### Neue Services (21 neue Dateien)

**Interfaces & Implementierungen:**
- `IOpenClawGatewayClient` — Interface für OpenClawGatewayClient (DIP-Fix: DashboardController hing an konkreter Klasse)
- `IAgentConfigService` / `AgentConfigService` — Agent-Config-File-I/O aus AgentsController extrahiert
- `IProjectService` / `ProjectService` — Projekt-CRUD + Activity-Logging (SRP)
- `ITaskService` / `TaskService` — Task-State-Machine, Approve/Reject, Dashboard-Operationen (eliminiert Duplikation zwischen TasksController und DashboardController)
- `IDashboardService` / `DashboardService` — Queue-Aggregation, Priority-Normalisierung, Gateway-Delegation
- `IOperationsService` / `OperationsService` — Metriken-Berechnung aus OperationsController
- `ITeamService` / `TeamService` — IDENTITY.md-Lesen aus TeamController
- `IMemoryService` / `MemoryService` — File-I/O aus MemoryController
- `IIncidentService` / `IncidentService` — File-Parsing (Regex-Source-Generatoren) aus IncidentsController
- `IDocService` / `DocService` — Directory-Scan aus DocsController
- `ICalendarService` / `CalendarService` — Gateway-HTTP-Calls + Fallback-Daten aus CalendarController

### Repository-Fixes

**IUserRepository / UserRepository:**
- `SaveChangesAsync` entfernt (leaky abstraction — Caller sollten nie SaveChanges steuern)
- `RevokeTokenAsync(tokenHash)` — atomares Token-Revoke inkl. SaveChanges
- `RevokeFamilyAsync(familyId)` — Batch-Revoke einer Token-Familie inkl. SaveChanges
- `RemoveExpiredTokensAsync` speichert jetzt selbst (war vorher dependent auf nachfolgenden Save)

### AuthService-Fixes
- `GetUserAsync`: unnötiges `Task.Run` entfernt → direkt `_users.GetByIdAsync().AsTask()`
- `RevokeAsync`: delegiert jetzt an `IUserRepository.RevokeTokenAsync`
- `RefreshAsync`: Token-Reuse-Detection delegiert an `IUserRepository.RevokeFamilyAsync`

### Bug-Fix
- `OpenClawGatewayClient.ReadAgentGoalAsync`: pre-existing `CS1656` behoben (`reader` war `using`-Variable und wurde neu zugewiesen — in `reader2` umbenannt)

### Controller (16 Stück — alle slim)
Alle Controller reduziert auf: Input validieren → Service aufrufen → HTTP-Result zurückgeben.
Kein Business-Logic, kein File-I/O, keine direkte Repository-Nutzung (außer AgentsController für Activity-Log).

**Program.cs — neue Registrierungen:**
- `AddHttpClient<IOpenClawGatewayClient, OpenClawGatewayClient>` (war vorher konkrete Klasse)
- Scoped: IDashboardService, IProjectService, ITaskService, IOperationsService, ITeamService, ICalendarService
- Singleton: IAgentConfigService, IMemoryService, IIncidentService, IDocService

---

## Frontend — Dashboard V2 Components

**AgentDetailModal.vue, IrisChat.vue, TaskStrip.vue:**
- V2 Design-System: Dark Space Theme, Glass-Panels, Gradient-Akzente
- Stores (agents, chat, tasks) nutzen Service + Mapper-Pattern
- NexusLayout, FlowBoard, Topbar — Layoutfixes für fullHeight-Route-Meta

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-14 08:34:58 +02:00
devops ac4e1cd3cf chore: bump version to v0.2.51 [skip ci] 2026-06-13 19:04:36 +00:00
reviewer 01c9bda339 fix(ops): change api healthcheck from curl to wget (curl not in base dotnet-aspnet image) [skip ci] 2026-06-13 21:04:29 +02:00
devops 1b11793dad chore: bump version to v0.2.50 [skip ci] 2026-06-13 19:03:48 +00:00
reviewer 98f98b55d5 fix(ops): change web healthcheck from wget to curl (wget IPv6 causes false unhealthy on nginx-alpine) [skip ci] 2026-06-13 21:03:41 +02:00
devops f28c398d16 chore: bump version to v0.2.49 [skip ci] 2026-06-13 19:00:26 +00:00
reviewer 358ec3e65d feat(frontend): Dashboard V2 — FlowCanvas, AgentModal, IrisChat, Stores, PlaceholderViews, Icon-Library
CI - Build & Test / Backend (.NET) (push) Failing after 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-13 20:58:53 +02:00
devops 5f3d04f44c chore: bump version to v0.2.48 [skip ci] 2026-06-13 18:04:57 +00:00
reviewer d169cbe9d5 feat(ops): production resilience — healthchecks, restart_policy, log-rotation, --wait deploy [skip ci] 2026-06-13 20:04:42 +02:00
reviewer 6cedd8410f refactor(frontend): deduplicate CSS keyframes, unify types, extract format utils, add UI states, trim mock data
CI - Build & Test / Backend (.NET) (push) Failing after 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
- Remove duplicate @keyframes pulse-* from 3 component files (already in nexus-tokens.css)
- Rename AgentDetail → AgentDetailData in dashboard types to avoid collision with types/agent.ts
- Extract shared formatNumber/initials/formatTime to utils/format.ts
- Simplify FlowBoard: use agentStore modal/selection getters instead of duplicating local state
- Add error banner + empty state to IrisChat; add loading skeleton + error/empty states to TaskStrip
- Remove 105-line unused mockAgents array from useFlowLayout
- Reduce operations store fallbacks from hardcoded preview data to minimal safe defaults
- Update operations store tests to match lean fallback structure
- Net: -73 lines, cleaner imports, fewer magic strings
2026-06-12 17:02:50 +02:00
developer 9033ff2973 feat(v2): live sidebar counts, /dashboard = V2 default route, remove V1 dead code
CI - Build & Test / Backend (.NET) (push) Failing after 21s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 14s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-12 01:01:50 +02:00
developer 676dbd7589 feat(v2): Pinia stores (agents/tasks/chat) + live backend integration, remove mock data
CI - Build & Test / Backend (.NET) (push) Failing after 22s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-12 00:57:28 +02:00
developer 9330de7af0 feat(v2): AgentDetailModal — metrics grid, thinking feed, model dropdown, keyboard nav
CI - Build & Test / Backend (.NET) (push) Failing after 21s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-12 00:52:59 +02:00
developer 6023b5ea24 fix(v2): reviewer bugfixes — scroll, block-status, NaN guard, dead code cleanup
CI - Build & Test / Backend (.NET) (push) Failing after 22s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-12 00:51:42 +02:00
developer 166c9f9051 feat(v2): IrisChat + TaskStrip components, mock data integration
CI - Build & Test / Backend (.NET) (push) Failing after 20s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-12 00:48:13 +02:00
developer 2d6e3537e8 feat(v2): FlowCanvas, AgentNode, AlertBar, useFlowLayout composable
CI - Build & Test / Backend (.NET) (push) Failing after 21s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-12 00:24:56 +02:00
developer 3672e56994 feat(v2): NexusLayout, Sidebar, NavGroup, NavItem, Topbar, FlowBoard placeholder
CI - Build & Test / Backend (.NET) (push) Failing after 22s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 14s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-12 00:20:27 +02:00
developer f378d7aed4 feat(v2): design tokens, fonts (Manrope/Space Grotesk/JetBrains Mono), galaxy background
CI - Build & Test / Backend (.NET) (push) Failing after 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-12 00:16:01 +02:00
developer 1a7bf8ca11 revert: remove Claude models (API not working)
CI - Build & Test / Backend (.NET) (push) Failing after 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-11 18:11:02 +02:00
developer 3907548a1d feat(models): add Claude Sonnet 4.6 + Opus 4.8, mount openclaw.json in API container
CI - Build & Test / Backend (.NET) (push) Failing after 22s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 16s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-11 17:11:59 +02:00
developer b1888bd8ef feat(dashboard): AgentModal live working feed & thinking stream
CI - Build & Test / Backend (.NET) (push) Failing after 24s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-11 16:13:28 +02:00
developer c29740a466 feat(dashboard): dynamic agent metrics + model list from config, no more hardcoded data
CI - Build & Test / Backend (.NET) (push) Failing after 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-11 16:01:33 +02:00
devops 45c6b24928 chore: bump version to v0.2.47 [skip ci] 2026-06-11 13:59:03 +00:00
developer 5fb62bef8a feat(queue): erweiterte Queue mit Cron-Jobs + Tasks, Prioritäten, Delete/Priority API
CI - Build & Test / Backend (.NET) (push) Successful in 26s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-11 15:58:12 +02:00
devops 068b0d31b8 chore: bump version to v0.2.46 [skip ci] 2026-06-11 13:55:20 +00:00
developer 97b8588dc3 feat(dashboard): multi-agent operations feed aggregating all agent sessions
CI - Build & Test / Backend (.NET) (push) Successful in 23s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-11 15:54:32 +02:00
devops 6150ea96af chore: bump version to v0.2.45 [skip ci] 2026-06-11 13:52:39 +00:00
developer 81af81fb6f feat(dashboard): task system with DB persistence, CRUD endpoints, frontend API integration
CI - Build & Test / Backend (.NET) (push) Successful in 27s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 15s
CI - Build & Test / Security Check (push) Successful in 3s
2026-06-11 15:51:48 +02:00
devops 2877035c5c chore: bump version to v0.2.44 [skip ci] 2026-06-11 13:49:27 +00:00
developer 6a1366b472 feat(dashboard): dynamic agent data from gateway sessions instead of hardcoded list
CI - Build & Test / Backend (.NET) (push) Successful in 27s
CI - Build & Test / Frontend (Vue/TS) (push) Successful in 14s
CI - Build & Test / Security Check (push) Successful in 2s
2026-06-11 15:48:33 +02:00
152 changed files with 17512 additions and 5700 deletions
+8
View File
@@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Bash(npx tsc *)",
"Bash(npx vite *)"
]
}
}
+156
View File
@@ -0,0 +1,156 @@
name: Database Backup
run-name: 💾 DB Backup triggered by @${{ gitea.actor }}
# ───────────────────────────────────────────────────────
# Owner: DevOps (Architekt)
# Trigger: Manual (workflow_dispatch) + optional schedule.
#
# Strategy:
# 1. Connects to the live PostgreSQL container via docker exec.
# 2. Runs pg_dumpall (full cluster dump, single file).
# 3. Compresses with gzip.
# 4. Uploads as a Gitea Action artifact (or writes to host path).
# 5. Artifacts are retained per Gitea repo settings (default 90 days).
#
# Rotation: Gitea artifact expiration handles old backups automatically.
# For longer retention, configure an external cron job or use the
# host_path output to copy the backup elsewhere.
#
# Restoration: See phases/deployment.md for step-by-step instructions.
# ───────────────────────────────────────────────────────
concurrency:
group: db-backup
cancel-in-progress: false
on:
workflow_dispatch:
inputs:
keep_on_host:
description: 'Also copy backup to host path?'
required: false
default: false
type: boolean
host_backup_path:
description: 'Host path for backup (only if keep_on_host is true)'
required: false
default: '/home/projekte_bao/openclaw/backups'
type: string
# Optional: uncomment to enable nightly automatic backups
# schedule:
# - cron: '0 3 * * *' # Every night at 03:00 UTC
jobs:
backup:
name: Backup PostgreSQL
runs-on: ubuntu-latest
env:
ENV_TMPFILE: /tmp/nexus-backup-env
ENV_POSTGRES_PASSWORD: ${{ secrets.ENV_POSTGRES_PASSWORD }}
DEPLOY_PATH: /home/projekte_bao/openclaw/data/openclaw/workspace/nexus
BACKUP_CONTAINER_NAME: nexus-postgres-1
steps:
# ═══════════════════════════════════════════════════
# Step 1: Generate backup filename
# ═══════════════════════════════════════════════════
- name: Generate backup identifier
id: meta
run: |
TIMESTAMP=$(date -u +'%Y-%m-%dT%H%M%SZ')
echo "timestamp=${TIMESTAMP}" >> "$GITEA_OUTPUT"
echo "filename=nexus-backup-${TIMESTAMP}.sql.gz" >> "$GITEA_OUTPUT"
echo "📅 Backup ID: ${TIMESTAMP}"
# ═══════════════════════════════════════════════════
# Step 2: Dump PostgreSQL via docker exec
# ═══════════════════════════════════════════════════
- name: Dump database
run: |
set -euo pipefail
echo "🗄️ Dumping PostgreSQL cluster..."
docker exec "${BACKUP_CONTAINER_NAME}" \
sh -c "PGPASSWORD='${ENV_POSTGRES_PASSWORD}' pg_dumpall -U nexus -h localhost" \
| gzip > "${{ steps.meta.outputs.filename }}"
SIZE=$(du -h "${{ steps.meta.outputs.filename }}" | cut -f1)
echo "✅ Backup written: ${{ steps.meta.outputs.filename }} (${SIZE})"
# ═══════════════════════════════════════════════════
# Step 3: Upload backup as Gitea artifact
# ═══════════════════════════════════════════════════
- name: Upload backup artifact
uses: actions/upload-artifact@v4
with:
name: nexus-backup-${{ steps.meta.outputs.timestamp }}
path: ${{ steps.meta.outputs.filename }}
retention-days: 90
compression-level: 0 # already gzipped
# ═══════════════════════════════════════════════════
# Step 4: Optional — copy to host filesystem
# ═══════════════════════════════════════════════════
- name: Copy backup to host (optional)
if: inputs.keep_on_host == true
run: |
set -euo pipefail
HOST_PATH="${{ inputs.host_backup_path }}"
# Create host dir if it doesn't exist
docker run --rm \
-v "${HOST_PATH}:/backup-target" \
-v "${{ gitea.workspace }}:/src:ro" \
alpine:latest \
sh -c "
mkdir -p /backup-target && \
cp /src/${{ steps.meta.outputs.filename }} /backup-target/ && \
echo '✅ Backup copied to host: ${HOST_PATH}/${{ steps.meta.outputs.filename }}'
"
# ═══════════════════════════════════════════════════
# Step 5: Verify backup integrity
# ═══════════════════════════════════════════════════
- name: Verify backup integrity
run: |
echo "🔍 Verifying backup integrity..."
if gzip -t "${{ steps.meta.outputs.filename }}"; then
echo "✅ Backup gzip integrity check passed"
else
echo "❌ Backup file is corrupted!"
exit 1
fi
# Quick content check: should start with PostgreSQL dump header
HEADER=$(zcat "${{ steps.meta.outputs.filename }}" | head -1)
if echo "$HEADER" | grep -qE '^(-- PostgreSQL database cluster dump|-- Dumped|--)'; then
echo "✅ Backup content header check passed"
else
echo "⚠️ Unexpected backup header (may still be valid): $HEADER"
fi
# ═══════════════════════════════════════════════════
# Step 6: Backup Summary
# ═══════════════════════════════════════════════════
- name: Backup Summary
if: always()
run: |
STATUS="${{ job.status }}"
echo ""
echo "═══════════════════════════════════════"
echo " 💾 Database Backup Summary"
echo "═══════════════════════════════════════"
echo " File: ${{ steps.meta.outputs.filename }}"
echo " Timestamp: ${{ steps.meta.outputs.timestamp }}"
echo " Triggered: @${{ gitea.actor }}"
echo " On host: ${{ inputs.keep_on_host == 'true' && inputs.host_backup_path || 'No (artifact only)' }}"
echo " Status: ${STATUS}"
echo "═══════════════════════════════════════"
if [ "${STATUS}" = "success" ]; then
echo ""
echo "💡 Restore command (manual, on host):"
echo " zcat ${{ steps.meta.outputs.filename }} | docker exec -i nexus-postgres-1 psql -U nexus -d postgres"
fi
+21 -8
View File
@@ -27,14 +27,13 @@ jobs:
dotnet-version: '10.0.x' dotnet-version: '10.0.x'
- name: Restore - name: Restore
run: dotnet restore backend/Nexus.Api.csproj run: dotnet restore backend-tests/Nexus.Api.Tests.csproj
- name: Build - name: Build
run: dotnet build backend/Nexus.Api.csproj --no-restore --configuration Release run: dotnet build backend-tests/Nexus.Api.Tests.csproj --no-restore --configuration Release
- name: Test - name: Test
run: dotnet test backend-tests/Nexus.Api.Tests.csproj --no-build --configuration Release --verbosity normal run: dotnet test backend-tests/Nexus.Api.Tests.csproj --no-build --configuration Release --verbosity normal
continue-on-error: true
# ─── Frontend ────────────────────────────────── # ─── Frontend ──────────────────────────────────
frontend: frontend:
@@ -54,16 +53,18 @@ jobs:
corepack enable corepack enable
corepack prepare pnpm@latest --activate corepack prepare pnpm@latest --activate
# --prefer-offline: use cached packages if available in the runner image
# Lockfile IS committed — regenerated on changes via pnpm install.
- name: Install dependencies - name: Install dependencies
run: pnpm install --no-frozen-lockfile --prefer-offline run: pnpm install --frozen-lockfile
working-directory: frontend working-directory: frontend
- name: Type check - name: Type check
run: pnpm exec vue-tsc --noEmit run: pnpm exec vue-tsc --noEmit
working-directory: frontend working-directory: frontend
- name: Test
run: pnpm test
working-directory: frontend
- name: Build - name: Build
run: pnpm build run: pnpm build
working-directory: frontend working-directory: frontend
@@ -79,8 +80,20 @@ jobs:
- name: Check for .env leaks - name: Check for .env leaks
run: | run: |
if grep -r "API_KEY\|SECRET\|PASSWORD\|TOKEN" --include="*.cs" --include="*.ts" --include="*.vue" backend/ frontend/src/ 2>/dev/null; then echo "🔍 Scanning for potential secrets in source code..."
echo "⚠️ Warning: Potential secrets in source code (review manually)" HITS=$(grep -rPn "(API_KEY|SECRET|PASSWORD|TOKEN)\s*[:=]\s*['\"][^'\"]{8,}" --include="*.cs" --include="*.ts" --include="*.vue" backend/ frontend/src/ 2>/dev/null || true)
if [ -n "$HITS" ]; then
echo "❌ SECRET LEAK DETECTED — the following lines look like hardcoded credentials:"
echo "$HITS"
echo ""
echo "Remove these values and use environment variables or a secrets manager instead."
exit 1
fi
# Secondary pass: catch bare assign patterns that are suspicious regardless of length
LOOSE=$(grep -rPn "(API_KEY|SECRET|PASSWORD|TOKEN)\s*[:=]\s*['\"]" --include="*.cs" --include="*.ts" --include="*.vue" backend/ frontend/src/ 2>/dev/null || true)
if [ -n "$LOOSE" ]; then
echo "⚠️ WARNING — potential secrets found (short values may be false positives, review manually):"
echo "$LOOSE"
else else
echo "✅ No obvious secrets found" echo "✅ No obvious secrets found"
fi fi
+292 -121
View File
@@ -1,169 +1,314 @@
name: Deploy to Production name: Deploy to Production
run-name: 🚀 Deploy ${{ inputs.bump_version || 'patch' }} by @${{ gitea.actor }} run-name: 🚀 Deploy by @${{ gitea.actor }}
# ── Concurrency: one deploy at a time, cancel queued ones ── # ───────────────────────────────────────────────────────
# Why: prevents race conditions when CI triggers deploy while # Owner: DevOps (Architekt)
# a manual deploy is still running. The latest deploy wins. # CD v3 — 2026-06-13
#
# Triggers:
# 1. AUTOMATIC after successful CI on main (workflow_run)
# → Uses safe defaults: patch bump, all services, main ref.
# → Commits marked with [skip ci] are filtered at job level
# (prevents version-bump loops).
# 2. MANUAL via workflow_dispatch with full parameter control.
#
# Concurrency: one deploy at a time.
# Queued deploys wait — no race conditions with parallel builds.
#
# Version Management:
# The VERSION file in the repo root is the single source of truth.
# Version bumps happen in the Dev workflow BEFORE merge to main.
# The deploy workflow only reads, validates, and logs the version.
# The [skip ci] filter remains as a safety layer for auto-triggers.
# ───────────────────────────────────────────────────────
concurrency: concurrency:
group: deploy-production group: deploy-production
cancel-in-progress: false cancel-in-progress: false
# ───────────────────────────────────────────────────
# Trigger: automatic after CI success, or manual dispatch.
# Runner: uses ubuntu-latest label (consistently present on
# runner id=5: linux,dotnet,node,deploy,ubuntu-latest,…).
# Standard labels avoid custom-label matching edge cases.
# ───────────────────────────────────────────────────
on: on:
# ── Auto-Trigger: after successful CI on main ──
workflow_run: workflow_run:
workflows: ["CI - Build & Test"] workflows: ["CI - Build & Test"]
types: [completed] types: [completed]
branches: [main] branches: [main]
# ── Manual Trigger (full control) ──
workflow_dispatch: workflow_dispatch:
inputs: inputs:
bump_version:
description: 'Version bump (Major=x.0.0, Minor=1.x.0 features, Patch=1.0.x fixes)'
required: false
default: 'patch'
type: string
options:
- 'patch'
- 'minor'
- 'major'
service: service:
description: 'Service to deploy (empty = all)' description: 'Service to deploy (empty = all)'
required: false required: false
default: '' default: ''
type: string type: string
no_cache: no_cache:
description: 'Disable build cache' description: 'Disable Docker build cache'
required: false required: false
default: false default: false
type: boolean type: boolean
git_ref:
description: 'Git ref to deploy (branch, tag, or commit SHA; default: main)'
required: false
default: 'main'
type: string
jobs: jobs:
deploy: deploy:
name: Deploy Nexus name: Deploy Nexus
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ gitea.event_name != 'workflow_run' || gitea.event.workflow_run.conclusion == 'success' }} if: |
(github.event_name == 'workflow_dispatch') ||
(github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
!contains(github.event.workflow_run.head_commit.message, '[skip ci]'))
# ── Env for the deploy target path ──
env:
DEPLOY_PATH: /home/projekte_bao/openclaw/data/openclaw/workspace/nexus
ENV_TMPFILE: /tmp/nexus-deploy-env
ENV_POSTGRES_PASSWORD: ${{ secrets.ENV_POSTGRES_PASSWORD }}
ENV_JWT_KEY: ${{ secrets.ENV_JWT_KEY }}
ENV_OPENCLAW_TOKEN: ${{ secrets.ENV_OPENCLAW_TOKEN }}
# OWNER_PASSWORD is read from the host's persistent .env — NOT from a Gitea secret.
# This ensures the password stays consistent across deploys and the DB is the
# single source of truth after initial seed (enforced by SeedAudit guard).
steps: steps:
# ── Step 1: Checkout ───────────────────── # ═══════════════════════════════════════════════════
- name: Checkout latest code # Step 1: Checkout
# ═══════════════════════════════════════════════════
- name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.git_ref || 'main' }}
fetch-depth: 0 fetch-depth: 0
fetch-tags: true fetch-tags: true
# ── Step 2: Version bump (race-free) ───── # ═══════════════════════════════════════════════════
# Derives current version from git tags (not VERSION file) to # Step 2: Set up Git identity
# avoid race conditions where tag exists but VERSION is stale. # ═══════════════════════════════════════════════════
# Uses --force on tag+push to handle retries after failed runs. - name: Configure Git
- name: Version Bump run: |
git config user.email "devops@noveria.net"
git config user.name "DevOps"
# ═══════════════════════════════════════════════════
# Step 3: Resolve deploy version
#
# Reads VERSION from repo root — the single source of truth.
# Validates semver format, logs version + git metadata.
# No git mutation: version bumps happen in the Dev workflow.
# ═══════════════════════════════════════════════════
- name: Resolve Version
id: version
run: | run: |
set -euo pipefail set -euo pipefail
# Source of truth: latest git tag # 1. Check VERSION exists
TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0") if [ ! -f VERSION ]; then
CURRENT_VERSION="${TAG#v}" echo "❌ VERSION file not found"
echo "📦 Current version (from git tags): $CURRENT_VERSION" exit 1
fi
MAJOR=$(echo "$CURRENT_VERSION" | cut -d. -f1) # 2. Read and validate semver format
MINOR=$(echo "$CURRENT_VERSION" | cut -d. -f2) VERSION=$(cat VERSION | tr -d '[:space:]')
PATCH=$(echo "$CURRENT_VERSION" | cut -d. -f3) if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "❌ Invalid semver in VERSION: '$VERSION'"
exit 1
fi
case "${{ inputs.bump_version }}" in # 3. Log version, git ref, and describe
major) GIT_REF=$(git rev-parse --short HEAD)
MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;; GIT_DESCRIBE=$(git describe --always --dirty)
minor)
MINOR=$((MINOR + 1)); PATCH=0 ;;
patch|*)
PATCH=$((PATCH + 1)) ;;
esac
NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}" echo "📦 Deploy version: v${VERSION}"
echo "🏷️ New version: $NEW_VERSION" echo "🔖 Git ref: ${GIT_REF}"
echo "$NEW_VERSION" > VERSION echo "🏷️ Git describe: ${GIT_DESCRIBE}"
git config user.email "devops@noveria.net" # 4. Set outputs for downstream steps
git config user.name "DevOps" echo "version=${VERSION}" >> "$GITEA_OUTPUT"
git add VERSION echo "mutated_main=false" >> "$GITEA_OUTPUT"
git commit -m "chore: bump version to v${NEW_VERSION} [skip ci]"
# --force avoids "tag already exists" when re-running after a failed attempt # ═══════════════════════════════════════════════════
git tag -f "v${NEW_VERSION}" # Step 4: Build .env from secrets + host .env (SAFE)
git push "https://devops:${{ secrets.GIT_TOKEN }}@git.noveria.net/bao/nexus.git" HEAD:main --force --tags #
echo "✅ Version bumped to v${NEW_VERSION}" # Secrets are written to /tmp/nexus-deploy-env — NEVER
# to a file inside the workspace that gets rsync'd to
# ── Step 3: Sync code + .env to host ────── # the host. The temp file is deleted immediately after
# Creates .env from Gitea secrets in the workspace, then syncs # compose operations complete.
# everything (except .git) to the host deploy path via DIND. #
- name: Sync code + .env to host # OWNER_PASSWORD is read from the host's persistent .env
# to ensure it stays the single source of truth. Other
# secrets (POSTGRES_PASSWORD, JWT_KEY, OPENCLAW_TOKEN)
# come from Gitea secrets.
# ═══════════════════════════════════════════════════
- name: Prepare .env (secrets + host .env → temp file)
run: | run: |
# Create .env from Gitea secrets in the workspace set -euo pipefail
cat > "${{ gitea.workspace }}/.env" << 'ENVEOF'
# Read OWNER_PASSWORD from the host's persistent .env
HOST_OWNER_PASSWORD=""
if [ -f "${DEPLOY_PATH}/.env" ]; then
HOST_OWNER_PASSWORD=$(grep '^OWNER_PASSWORD=' "${DEPLOY_PATH}/.env" | cut -d= -f2- || true)
fi
if [ -z "${HOST_OWNER_PASSWORD}" ]; then
echo "❌ OWNER_PASSWORD not found in ${DEPLOY_PATH}/.env"
echo " The host .env is the single source of truth for the owner password."
echo " Ensure OWNER_PASSWORD is set in the deploy-path .env before deploying."
exit 1
fi
cat > "${ENV_TMPFILE}" <<EOF
# Nexus Production Environment — auto-generated by CD pipeline # Nexus Production Environment — auto-generated by CD pipeline
# Managed via Gitea secrets → do not edit manually on the host # Managed via Gitea Secrets + host .env → do NOT edit manually on the host.
# This file lives in /tmp and is removed after deploy completes.
POSTGRES_DB=nexus POSTGRES_DB=nexus
POSTGRES_USER=nexus POSTGRES_USER=nexus
POSTGRES_PASSWORD=${{ secrets.ENV_POSTGRES_PASSWORD }} POSTGRES_PASSWORD=${ENV_POSTGRES_PASSWORD}
JWT_KEY=${{ secrets.ENV_JWT_KEY }} JWT_KEY=${ENV_JWT_KEY}
JWT_ISSUER=nexus JWT_ISSUER=nexus
JWT_AUDIENCE=nexus-web JWT_AUDIENCE=nexus-web
OWNER_EMAIL=vmbao62@hotmail.de OWNER_EMAIL=vmbao62@hotmail.de
OWNER_PASSWORD=${{ secrets.ENV_OWNER_PASSWORD }} OWNER_PASSWORD=${HOST_OWNER_PASSWORD}
OWNER_DISPLAY_NAME= OWNER_DISPLAY_NAME=
OPENCLAW_BASE_URL=http://host.docker.internal:18789 OPENCLAW_BASE_URL=http://host.docker.internal:18789
OPENCLAW_GATEWAY_TOKEN=${{ secrets.ENV_OPENCLAW_TOKEN }} OPENCLAW_GATEWAY_TOKEN=${ENV_OPENCLAW_TOKEN}
OPENCLAW_GATEWAY_PASSWORD= OPENCLAW_GATEWAY_PASSWORD=
ENVEOF EOF
chmod 600 "${ENV_TMPFILE}"
echo "✅ .env written to ${ENV_TMPFILE} (mode 600)"
# ═══════════════════════════════════════════════════
# Step 5: Sync code to host (without .env in workspace)
# ═══════════════════════════════════════════════════
- name: Sync code to host
run: |
set -euo pipefail
# Sync everything (except .git) from workspace to host
docker run --rm \ docker run --rm \
-v "${{ gitea.workspace }}:/src:ro" \ -v "${{ gitea.workspace }}:/src:ro" \
-v /opt/openclaw/data/openclaw/workspace/nexus:/dest \ -v "${DEPLOY_PATH}:/dest" \
alpine:latest \ alpine:latest \
sh -c " sh -c "
cd /src && \ cd /src && \
find . -mindepth 1 -maxdepth 1 \ find . -mindepth 1 -maxdepth 1 \
! -name .git \ ! -name .git \
-exec cp -a {} /dest/ \; -exec cp -r {} /dest/ \; && \
DEST_OWNER=\$(stat -c '%u:%g' /dest) && \
chown -R \"\$DEST_OWNER\" /dest
" "
echo "✅ Code + .env synced to host deploy path"
# ── Step 4: Docker Buildx ───────────────── echo "✅ Code synced to ${DEPLOY_PATH}"
- name: Set up Docker Buildx
run: docker buildx create --use 2>/dev/null || true
# ── Step 5: Build & Deploy ──────────────── # ═══════════════════════════════════════════════════
# Step 6: Build & Deploy
#
# The temp .env file is bind-mounted read-only into the
# docker:cli container so compose can resolve variables.
# It is NEVER written into the workspace directory.
# ═══════════════════════════════════════════════════
- name: Build & Deploy - name: Build & Deploy
run: | run: |
set -euo pipefail
# Auto-deploy: always use cache. Manual: respect no_cache input.
NO_CACHE="${{ github.event_name == 'workflow_dispatch' && inputs.no_cache || false }}"
BUILD_ARGS="" BUILD_ARGS=""
if [ "${{ inputs.no_cache }}" = "true" ]; then if [ "$NO_CACHE" = "true" ]; then
BUILD_ARGS="--no-cache" BUILD_ARGS="--no-cache"
fi fi
docker run --rm \ SERVICE_ARG="${{ github.event_name == 'workflow_dispatch' && inputs.service || '' }}"
-v /opt/openclaw/data/openclaw/workspace/nexus:/workspace/nexus \
-v /var/run/docker.sock:/var/run/docker.sock \
-w /workspace/nexus \
docker:cli \
sh -c "
set -e
if [ -n '${{ inputs.service }}' ]; then
echo '🚀 Deploying service: ${{ inputs.service }}'
docker compose build ${BUILD_ARGS} ${{ inputs.service }}
docker compose up -d --force-recreate ${{ inputs.service }}
else
echo '🚀 Deploying all services'
docker compose build ${BUILD_ARGS}
docker compose up -d --force-recreate
fi
"
# ── Step 6: Health Check (backoff) ──────── # Write the deploy script to a file to avoid nested quoting issues
# Exponential-ish backoff: 1s, 2s, 3s, 5s, 8s, 13s (~32s total). cat > /tmp/nexus-deploy-script.sh << 'DEPLOYSCRIPT'
# Why: cold-start containers need variable warmup time; #!/bin/sh
# fixed 5s intervals either wait too long or give up too early. set -e
trap 'rm -f /tmp/nexus-deploy-env' EXIT
cat > /tmp/nexus-deploy-env
# ── Clean up zombie containers ──
docker compose --env-file /tmp/nexus-deploy-env down --remove-orphans 2>/dev/null || true
docker rm -f nexus-postgres-1 nexus-api-1 nexus-web-1 2>/dev/null || true
# ── WAL recovery ──
PG_VOL=$(docker volume ls -q --filter name=nexus-postgres 2>/dev/null | head -1)
if [ -n "$PG_VOL" ]; then
echo "Checking postgres WAL integrity..."
docker run --rm -v "$PG_VOL:/var/lib/postgresql/data" \
--entrypoint sh postgres:17-alpine -c "
echo 'Resetting WAL...'
pg_resetwal -f /var/lib/postgresql/data && echo 'WAL reset OK'
" 2>&1 || echo 'pg_resetwal failed (may be benign)'
else
echo 'Postgres volume not found - will be created fresh'
fi
BUILD_ARGS="${DEPLOY_BUILD_ARGS:-}"
SERVICE="${DEPLOY_SERVICE:-}"
if [ -n "$SERVICE" ]; then
echo "Deploying service: $SERVICE"
docker compose --env-file /tmp/nexus-deploy-env build $BUILD_ARGS $SERVICE
docker compose --env-file /tmp/nexus-deploy-env up -d --force-recreate $SERVICE
else
echo 'Deploying all services'
docker compose --env-file /tmp/nexus-deploy-env build $BUILD_ARGS
docker compose --env-file /tmp/nexus-deploy-env up -d --force-recreate
fi
echo 'Waiting for services to become healthy (up to 180s)...'
for i in $(seq 1 36); do
STATUS=$(docker compose --env-file /tmp/nexus-deploy-env ps -a 2>/dev/null | tail -n +2)
if echo "$STATUS" | grep -q 'unhealthy'; then
echo " [$i/36] Unhealthy containers - failing fast"
docker compose --env-file /tmp/nexus-deploy-env ps -a
docker compose --env-file /tmp/nexus-deploy-env logs --tail=30
exit 1
elif echo "$STATUS" | grep -q 'starting'; then
echo " [$i/36] Still starting..."
sleep 5
else
echo 'All containers healthy'
docker compose --env-file /tmp/nexus-deploy-env ps -a
exit 0
fi
done
echo 'Timeout waiting for services'
docker compose --env-file /tmp/nexus-deploy-env ps -a
docker compose --env-file /tmp/nexus-deploy-env logs --tail=20
exit 1
DEPLOYSCRIPT
docker run --rm \
-e "DEPLOY_BUILD_ARGS=${BUILD_ARGS:-}" \
-e "DEPLOY_SERVICE=${SERVICE_ARG:-}" \
-v "${DEPLOY_PATH}:/workspace/nexus" \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /tmp/nexus-deploy-script.sh:/deploy.sh:ro \
-w /workspace/nexus \
-i \
docker:cli \
sh /deploy.sh < "${ENV_TMPFILE}"
rm -f /tmp/nexus-deploy-script.sh
echo "✅ Docker compose up completed"
# ═══════════════════════════════════════════════════
# Step 7: Clean up temp .env
# ═══════════════════════════════════════════════════
- name: Clean up temp .env
if: always()
run: |
if [ -f "${ENV_TMPFILE}" ]; then
shred -u "${ENV_TMPFILE}" 2>/dev/null || rm -f "${ENV_TMPFILE}"
echo "🧹 Temp .env removed"
fi
# ═══════════════════════════════════════════════════
# Step 8: Health Check (exponential backoff)
# ═══════════════════════════════════════════════════
- name: Health Check - name: Health Check
run: | run: |
echo "🏥 Health check..." echo "🏥 Health check..."
@@ -186,11 +331,10 @@ jobs:
echo "❌ Health check failed after $MAX attempts" echo "❌ Health check failed after $MAX attempts"
exit 1 exit 1
# ── Step 7: Smoke test (multi-endpoint) ─── # ═══════════════════════════════════════════════════
# Tests multiple endpoints to catch partial failures. # Step 9: Smoke Test
# Why: a single /dashboard check can miss backend-only outages; # ═══════════════════════════════════════════════════
# /health tests the API + database + runtime status. - name: Smoke Test
- name: Verify (smoke test)
run: | run: |
echo "🔍 Smoke test..." echo "🔍 Smoke test..."
PASS=0 PASS=0
@@ -199,7 +343,8 @@ jobs:
check() { check() {
local path="$1" label="$2" expected="${3:-200}" local path="$1" label="$2" expected="${3:-200}"
local code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "${BASE}${path}") local code
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "${BASE}${path}")
printf " %-25s HTTP %s" "${label}:" "${code}" printf " %-25s HTTP %s" "${label}:" "${code}"
if [ "$code" = "$expected" ]; then if [ "$code" = "$expected" ]; then
echo " ✅" echo " ✅"
@@ -212,6 +357,7 @@ jobs:
check "/dashboard" "Dashboard" 200 check "/dashboard" "Dashboard" 200
check "/health" "Health API" 200 check "/health" "Health API" 200
check "/api/v1/operations/snapshot" "Operations API (auth)" 401
echo "" echo ""
echo "Results: $PASS passed, $FAIL failed" echo "Results: $PASS passed, $FAIL failed"
@@ -219,25 +365,50 @@ jobs:
echo "❌ Smoke test failed!" echo "❌ Smoke test failed!"
exit 1 exit 1
fi fi
echo "✅ Deployment verified" echo "✅ Smoke test passed — v${{ steps.version.outputs.version }} is live"
# ── Step 8: Rollback hint ──────────────── # ═══════════════════════════════════════════════════
# On any failure, prints the previous deploy tag for quick manual rollback. # Step 10: Deployment Summary
# Why: reduces MTTR (mean time to recovery) by providing the exact # ═══════════════════════════════════════════════════
# git tag to roll back to without needing to look it up manually. - name: Deployment Summary
- name: Rollback hint if: always()
run: |
TRIGGER="${{ github.event_name == 'workflow_run' && 'Auto (CI success)' || 'Manual (workflow_dispatch)' }}"
echo ""
echo "═══════════════════════════════════════"
echo " 📦 Deploy Summary"
echo "═══════════════════════════════════════"
echo " Version: v${{ steps.version.outputs.version }}"
echo " Git ref: ${{ github.event_name == 'workflow_dispatch' && inputs.git_ref || 'main' }}"
echo " Service: ${{ github.event_name == 'workflow_dispatch' && inputs.service || 'all' }}"
echo " Trigger: ${TRIGGER}"
echo " Actor: @${{ gitea.actor }}"
echo " Status: ${{ job.status }}"
echo "═══════════════════════════════════════"
# ═══════════════════════════════════════════════════
# Step 11: Failure → Reviewer Handoff
#
# On failure: DevOps (Architekt) analyses the log,
# notifies Reviewer (Code-Fixer) with the exact error.
# This output provides a ready-to-copy message.
# ═══════════════════════════════════════════════════
- name: 🔴 Failure — Reviewer Handoff
if: failure() if: failure()
run: | run: |
echo "" echo ""
echo "🔙 ─── Rollback Instructions ─── 🔙" echo "─────────────────────────────────────────────────────────────┐"
echo "" echo "│ 🔴 DEPLOY FAILED — Reviewer muss fixen │"
echo " # 1. Checkout previous version:" echo "├─────────────────────────────────────────────────────────────┤"
echo " git checkout tags/\$(git describe --tags --abbrev=0 2>/dev/null || echo 'unknown')" echo "│ │"
echo "" echo "│ Version: v${{ steps.version.outputs.version }}"
echo " # 2. Redeploy:" echo " Job: ${{ gitea.server_url }}/${{ gitea.repository }}/actions/runs/${{ gitea.run_id }}"
echo " cd /opt/openclaw/data/openclaw/workspace/nexus" echo "│ │"
echo " docker compose up -d --force-recreate" echo " → DevOps (Architekt) analysiert den Fehler │"
echo "" echo "│ → Reviewer (Code-Fixer) behebt das Problem │"
echo " # 3. Or trigger rollback via Gitea:" echo "│ → DevOps verifiziert mit neuem Deploy │"
echo " Trigger 'Deploy to Production' workflow with the previous tag" echo " "
echo "" echo "│ Rollback: Trigger 'Rollback to Previous Version' │"
echo "│ workflow manuell in Gitea Actions. │"
echo "│ │"
echo "└─────────────────────────────────────────────────────────────┘"
+286
View File
@@ -0,0 +1,286 @@
name: Rollback to Previous Version
run-name: 🔙 Rollback by @${{ gitea.actor }}
# ───────────────────────────────────────────────────────
# Owner: DevOps (Architekt)
# Trigger: EXCLUSIVELY manual (workflow_dispatch).
#
# This workflow reverts the deploy path to the code at a
# given git tag/ref, then rebuilds and redeploys the stack.
#
# Strategy: git checkout <tag> → docker compose up -d --build
# This is a "full restart rollback" — safest for containerized
# apps where DB schema changes may need the matching API binary.
#
# DB migrations: the API runs MigrateAsync on startup. If the
# rollback-tag's migration history is a prefix of the current DB,
# EF Core handles this gracefully (no-op for already-applied
# migrations). If the tag predates a destructive migration, manual
# DB intervention is needed — that's an edge case surfaced to DevOps.
# ───────────────────────────────────────────────────────
concurrency:
group: deploy-production
cancel-in-progress: false
on:
workflow_dispatch:
inputs:
target_tag:
description: 'Git tag to roll back to (e.g. v0.2.49)'
required: true
type: string
confirm:
description: 'Type "ROLLBACK" to confirm'
required: true
type: string
jobs:
rollback:
name: Rollback Nexus
runs-on: ubuntu-latest
env:
DEPLOY_PATH: /home/projekte_bao/openclaw/data/openclaw/workspace/nexus
ENV_TMPFILE: /tmp/nexus-rollback-env
ENV_POSTGRES_PASSWORD: ${{ secrets.ENV_POSTGRES_PASSWORD }}
ENV_JWT_KEY: ${{ secrets.ENV_JWT_KEY }}
ENV_OPENCLAW_TOKEN: ${{ secrets.ENV_OPENCLAW_TOKEN }}
steps:
# ═══════════════════════════════════════════════════
# Step 0: Safety gate — require explicit confirmation
# ═══════════════════════════════════════════════════
- name: Safety Gate
run: |
if [ "${{ inputs.confirm }}" != "ROLLBACK" ]; then
echo "❌ Rollback aborted: confirmation string must be 'ROLLBACK'"
echo " You entered: '${{ inputs.confirm }}'"
exit 1
fi
echo "✅ Rollback confirmed — proceeding to ${{ inputs.target_tag }}"
# ═══════════════════════════════════════════════════
# Step 1: Checkout target tag
# ═══════════════════════════════════════════════════
- name: Checkout target tag
uses: actions/checkout@v4
with:
ref: refs/tags/${{ inputs.target_tag }}
fetch-depth: 0
fetch-tags: true
# ═══════════════════════════════════════════════════
# Step 2: Verify tag exists
# ═══════════════════════════════════════════════════
- name: Verify tag
run: |
set -euo pipefail
ACTUAL_TAG=$(git describe --tags --exact-match 2>/dev/null || echo "")
if [ -z "$ACTUAL_TAG" ]; then
echo "❌ Tag '${{ inputs.target_tag }}' not found in repository"
echo " Available tags:"
git tag -l 'v*' | sort -V | tail -20
exit 1
fi
echo "✅ Checked out: $ACTUAL_TAG"
echo " Commit: $(git rev-parse --short HEAD)"
echo " Message: $(git log -1 --oneline)"
# Read version from VERSION file at this tag
if [ -f VERSION ]; then
VERSION=$(cat VERSION | tr -d '[:space:]')
echo " VERSION: $VERSION"
fi
# ═══════════════════════════════════════════════════
# Step 3: Prepare .env from secrets + host .env (safe temp file)
# ═══════════════════════════════════════════════════
- name: Prepare .env (secrets + host .env → temp file)
run: |
set -euo pipefail
# Read OWNER_PASSWORD from the host's persistent .env
HOST_OWNER_PASSWORD=""
if [ -f "${DEPLOY_PATH}/.env" ]; then
HOST_OWNER_PASSWORD=$(grep '^OWNER_PASSWORD=' "${DEPLOY_PATH}/.env" | cut -d= -f2- || true)
fi
if [ -z "${HOST_OWNER_PASSWORD}" ]; then
echo "❌ OWNER_PASSWORD not found in ${DEPLOY_PATH}/.env"
exit 1
fi
cat > "${ENV_TMPFILE}" <<EOF
# Nexus Production Environment — auto-generated by CD pipeline
POSTGRES_DB=nexus
POSTGRES_USER=nexus
POSTGRES_PASSWORD=${ENV_POSTGRES_PASSWORD}
JWT_KEY=${ENV_JWT_KEY}
JWT_ISSUER=nexus
JWT_AUDIENCE=nexus-web
OWNER_EMAIL=vmbao62@hotmail.de
OWNER_PASSWORD=${HOST_OWNER_PASSWORD}
OWNER_DISPLAY_NAME=
OPENCLAW_BASE_URL=http://host.docker.internal:18789
OPENCLAW_GATEWAY_TOKEN=${ENV_OPENCLAW_TOKEN}
OPENCLAW_GATEWAY_PASSWORD=
EOF
chmod 600 "${ENV_TMPFILE}"
echo "✅ .env written to ${ENV_TMPFILE} (mode 600)"
# ═══════════════════════════════════════════════════
# Step 4: Sync rollback code to host
# ═══════════════════════════════════════════════════
- name: Sync code to host
run: |
set -euo pipefail
docker run --rm \
-v "${{ gitea.workspace }}:/src:ro" \
-v "${DEPLOY_PATH}:/dest" \
alpine:latest \
sh -c "
cd /src && \
find . -mindepth 1 -maxdepth 1 \
! -name .git \
-exec cp -r {} /dest/ \; && \
DEST_OWNER=\$(stat -c '%u:%g' /dest) && \
chown -R \"\$DEST_OWNER\" /dest
"
echo "✅ Rollback code (${{ inputs.target_tag }}) synced to ${DEPLOY_PATH}"
# ═══════════════════════════════════════════════════
# Step 5: Rebuild & Redeploy
# ═══════════════════════════════════════════════════
- name: Rebuild & Redeploy
run: |
set -euo pipefail
docker run --rm \
-v "${DEPLOY_PATH}:/workspace/nexus" \
-v "/tmp:/tmp-host:ro" \
-v /var/run/docker.sock:/var/run/docker.sock \
-w /workspace/nexus \
docker:cli \
sh -c "
set -e
echo '🔙 Rolling back to ${{ inputs.target_tag }}'
docker compose --env-file /tmp-host/$(basename "${ENV_TMPFILE}") build --no-cache
docker compose --env-file /tmp-host/$(basename "${ENV_TMPFILE}") up -d --wait --force-recreate
"
echo "✅ Rollback redeploy completed"
# ═══════════════════════════════════════════════════
# Step 6: Clean up temp .env
# ═══════════════════════════════════════════════════
- name: Clean up temp .env
if: always()
run: |
if [ -f "${ENV_TMPFILE}" ]; then
shred -u "${ENV_TMPFILE}" 2>/dev/null || rm -f "${ENV_TMPFILE}"
echo "🧹 Temp .env removed"
fi
# ═══════════════════════════════════════════════════
# Step 7: Health Check
# ═══════════════════════════════════════════════════
- name: Health Check
run: |
echo "🏥 Health check after rollback..."
RETRY=0
MAX=6
WAIT=1
while [ $RETRY -lt $MAX ]; do
RETRY=$((RETRY + 1))
if curl -sf --max-time 10 https://nexus.noveria.net/health; then
echo ""
echo "✅ Health check passed (attempt $RETRY/$MAX)"
exit 0
fi
echo "⏳ Attempt $RETRY/$MAX failed, waiting ${WAIT}s..."
sleep $WAIT
NEXT=$((WAIT + RETRY))
[ $NEXT -le 15 ] && WAIT=$NEXT || WAIT=15
done
echo "❌ Health check failed after $MAX attempts"
exit 1
# ═══════════════════════════════════════════════════
# Step 8: Smoke Test
# ═══════════════════════════════════════════════════
- name: Smoke Test
run: |
echo "🔍 Smoke test after rollback..."
PASS=0
FAIL=0
BASE="https://nexus.noveria.net"
check() {
local path="$1" label="$2" expected="${3:-200}"
local code
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "${BASE}${path}")
printf " %-25s HTTP %s" "${label}:" "${code}"
if [ "$code" = "$expected" ]; then
echo " ✅"
PASS=$((PASS + 1))
else
echo " ❌ (expected $expected)"
FAIL=$((FAIL + 1))
fi
}
check "/dashboard" "Dashboard" 200
check "/health" "Health API" 200
check "/api/v1/operations/snapshot" "Operations API (auth)" 401
echo ""
echo "Results: $PASS passed, $FAIL failed"
if [ "$FAIL" -gt 0 ]; then
echo "❌ Smoke test failed!"
exit 1
fi
echo "✅ Rollback to ${{ inputs.target_tag }} successful"
# ═══════════════════════════════════════════════════
# Step 9: Rollback Summary
# ═══════════════════════════════════════════════════
- name: Rollback Summary
if: always()
run: |
echo ""
echo "═══════════════════════════════════════"
echo " 🔙 Rollback Summary"
echo "═══════════════════════════════════════"
echo " Rolled to: ${{ inputs.target_tag }}"
echo " Triggered: @${{ gitea.actor }}"
echo " Status: ${{ job.status }}"
echo "═══════════════════════════════════════"
# ═══════════════════════════════════════════════════
# Step 10: Failure → Reviewer Handoff
# ═══════════════════════════════════════════════════
- name: 🔴 Rollback Failed — Reviewer Handoff
if: failure()
run: |
echo ""
echo "┌─────────────────────────────────────────────────────────────┐"
echo "│ 🔴 ROLLBACK FAILED — Reviewer muss fixen │"
echo "├─────────────────────────────────────────────────────────────┤"
echo "│ │"
echo "│ Target: ${{ inputs.target_tag }}"
echo "│ Job: ${{ gitea.server_url }}/${{ gitea.repository }}/actions/runs/${{ gitea.run_id }}"
echo "│ │"
echo "│ → DevOps (Architekt) analysiert den Fehler │"
echo "│ → Reviewer (Code-Fixer) behebt das Problem │"
echo "│ → DevOps verifiziert mit neuem Deploy │"
echo "│ │"
echo "│ Letzter bekannter funktionierender Stand: │"
echo "│ → 'git log --oneline -5' zeigt letzte Commits │"
echo "│ → Manuellen Rollback erwägen: │"
echo "│ cd /home/projekte_bao/openclaw/data/openclaw/workspace/nexus │"
echo "│ docker compose up -d (vorheriger Stand) │"
echo "│ │"
echo "└─────────────────────────────────────────────────────────────┘"
+7
View File
@@ -30,4 +30,11 @@ docker-compose.override.yml
*.tmp *.tmp
*.bak *.bak
# Crash artefacts / Core dumps
**/core
**/core.*
# pnpm (lockfile IS committed for reproducible CI builds) # pnpm (lockfile IS committed for reproducible CI builds)
# Claude local config (per-developer, not repo-shared)
.claude/
+81 -19
View File
@@ -3,7 +3,11 @@
Nexus is the operations platform for the Noveria ecosystem. OpenClaw is an Nexus is the operations platform for the Noveria ecosystem. OpenClaw is an
adapter-backed agent runtime, not a dependency of the frontend or domain model. adapter-backed agent runtime, not a dependency of the frontend or domain model.
> CI/CD auto-deploy enabled — every push to main triggers build → test → deploy. > CI runs automatically on every push. CD can run **automatically after successful CI**
> on main (patch-bump default) or can be triggered **manually** (workflow_dispatch) with
> full parameter control. Main deploys bump/tag a release; arbitrary `git_ref` deploys
> stay read-only. Rollback and database backup are separate manual workflows.
> See [phases/deployment.md](phases/deployment.md) for full CD documentation.
## Current foundation ## Current foundation
@@ -11,10 +15,9 @@ adapter-backed agent runtime, not a dependency of the frontend or domain model.
- ASP.NET Core 10 REST API (Minimal API pattern) - ASP.NET Core 10 REST API (Minimal API pattern)
- Entity Framework Core and PostgreSQL - Entity Framework Core and PostgreSQL
- JWT owner authentication with rotating refresh sessions - JWT owner authentication with rotating refresh sessions
- `IAgentRuntime` abstraction with an OpenClaw adapter - `IAgentRuntime` abstraction with an OpenClaw adapter (Ollama and NVIDIA removed — OpenClaw-only)
- `IModelProvider` abstractions for Ollama and NVIDIA
- Responsive dark-mode operations dashboard - Responsive dark-mode operations dashboard
- Container-only entry point on `127.0.0.1:18880` - Traefik reverse-proxy with Let's Encrypt TLS on `nexus.noveria.net`
## Local/container start ## Local/container start
@@ -27,12 +30,11 @@ curl http://127.0.0.1:18880/health
``` ```
On an empty database the API creates exactly one owner from `OWNER_EMAIL`, On an empty database the API creates exactly one owner from `OWNER_EMAIL`,
`OWNER_PASSWORD` and `OWNER_DISPLAY_NAME`. The password must contain at least 14 `OWNER_PASSWORD` and `OWNER_DISPLAY_NAME`. The password must contain at least 10
characters. Existing databases are never overwritten by the bootstrap process. characters. Existing databases are never overwritten by the bootstrap process.
The web service is loopback-only. Public reverse-proxy activation for The API is exposed via Traefik reverse-proxy with automatic Let's Encrypt TLS.
`nexus.noveria.net` remains a separate infrastructure change and must terminate Health checks, rate limiting, and security headers are active.
TLS before forwarding to port `18880`.
## Workspace mounts ## Workspace mounts
@@ -41,12 +43,12 @@ and the config editor. These are mounted under `/mnt/workspace-{agentId}`:
| Host path | Container mount | | Host path | Container mount |
|---|---| |---|---|
| `/opt/openclaw/data/openclaw/workspace-iris` | `/mnt/workspace-iris` | | `/home/projekte_bao/openclaw/data/openclaw/workspace-iris` | `/mnt/workspace-iris` |
| `/opt/openclaw/data/openclaw/workspace-programmer` | `/mnt/workspace-programmer` | | `/home/projekte_bao/openclaw/data/openclaw/workspace-programmer` | `/mnt/workspace-programmer` |
| `/opt/openclaw/data/openclaw/workspace-reviewer` | `/mnt/workspace-reviewer` | | `/home/projekte_bao/openclaw/data/openclaw/workspace-reviewer` | `/mnt/workspace-reviewer` |
| `/opt/openclaw/data/openclaw/workspace-architekt` | `/mnt/workspace-architekt` | | `/home/projekte_bao/openclaw/data/openclaw/workspace-architekt` | `/mnt/workspace-architekt` |
| `/opt/openclaw/data/openclaw/workspace-researcher` | `/mnt/workspace-researcher` | | `/home/projekte_bao/openclaw/data/openclaw/workspace-researcher` | `/mnt/workspace-researcher` |
| `/opt/openclaw/data/openclaw/workspace-executor` | `/mnt/workspace-executor` | | `/home/projekte_bao/openclaw/data/openclaw/workspace-executor` | `/mnt/workspace-executor` |
## Frontend architecture ## Frontend architecture
@@ -279,12 +281,72 @@ Backlog → Blocked → In progress / Done
provider key. Conversation IDs are stable per browser and Iris is the default provider key. Conversation IDs are stable per browser and Iris is the default
agent target. agent target.
The configured model-routing policy is: The configured model-routing policy routes through the OpenClaw Gateway only.
Ollama and NVIDIA providers have been removed. Currently active models:
1. `qwen3:4b` through Ollama for routine and monitoring work | Agent | Model |
2. `moonshotai/kimi-k2.6` through NVIDIA for primary work |-------|-------|
3. `gpt-5.5` through OpenClaw for strategic and critical review | Iris | `openai/gpt-5.4` |
| Programmer, Executor | `deepseek/deepseek-v4-flash` |
| Reviewer, Architekt, Researcher | `deepseek/deepseek-v4-pro` |
Claude models (Sonnet 4.6, Opus 4.6/4.7/4.8) are available via `claude-cli` backend.
The Settings module reports runtime and provider state without exposing The Settings module reports runtime and provider state without exposing
credentials. credentials.
# Trigger CI
## CI/CD
### CI — Automatic
Every push to `main` triggers `.gitea/workflows/ci.yaml`:
- **Backend**: .NET restore → build → test
- **Frontend**: pnpm install → type-check → test → build
- **Security**: Scan for hardcoded secrets in source code
CI must never break. If it does, Reviewer fixes.
### CD — Auto + Manual (CD v3)
Deployment can happen automatically or manually:
#### Auto-Deploy (after successful CI on main)
- Triggered by `workflow_run` after `CI - Build & Test` succeeds on `main`
- Uses safe defaults: `patch` bump, all services, main ref
- Skips automatically if the triggering commit contains `[skip ci]` (version-bump commits)
- The version-bump commit itself uses `[skip ci]` → no infinite CI→Deploy→Bump→CI loops
#### Manual Deploy (`workflow_dispatch`)
1. DevOps triggers `Deploy to Production` in Gitea Actions (or Iris auto-approves)
2. Chooses version bump type: patch (default) / minor / major
3. Optionally scopes to a single service or specific git ref
4. Workflow bumps VERSION, creates git tag, builds and deploys
5. Health check + smoke test verify the deployment
#### Rollback (`workflow_dispatch`)
1. DevOps triggers `Rollback to Previous Version` in Gitea Actions
2. Enters target git tag (e.g. `v0.2.49`) + confirmation `ROLLBACK`
3. Workflow checks out the tag, rebuilds with `--no-cache`, redeploys
4. Health check + smoke test verify the rollback
#### Database Backup (`workflow_dispatch`)
1. DevOps triggers `Database Backup` in Gitea Actions
2. Optionally also copies backup to a host path (`/home/projekte_bao/backups`)
3. Workflow dumps PostgreSQL via `pg_dumpall`, gzips, and uploads as a Gitea artifact
4. Artifacts are retained for 90 days (configurable)
5. Optional nightly schedule (uncomment the cron trigger in `backup.yaml`)
#### Failure Handling
When deploy or rollback fails:
- **DevOps (Architekt)** analyses the error
- **Reviewer (Code-Fixer)** fixes the problem
- **DevOps** re-deploys to verify the fix
The workflow outputs a formatted handoff message with the job URL.
Full CD documentation: [phases/deployment.md](phases/deployment.md)
+1 -1
View File
@@ -1 +1 @@
0.2.43 0.2.56
+52 -18
View File
@@ -11,12 +11,8 @@ public class AgentServiceTests
[Fact] [Fact]
public async Task GetAgentsAsync_ReturnsCorrectCount() public async Task GetAgentsAsync_ReturnsCorrectCount()
{ {
var config = new ConfigurationBuilder() var configPath = CreateAgentConfigFile();
.AddInMemoryCollection(new Dictionary<string, string?> var config = CreateConfiguration(configPath);
{
["AgentConfigPath"] = "/home/node/.openclaw/openclaw.json"
})
.Build();
var runtime = new FakeRuntime(); var runtime = new FakeRuntime();
var service = new AgentService(config, runtime); var service = new AgentService(config, runtime);
@@ -27,12 +23,8 @@ public class AgentServiceTests
[Fact] [Fact]
public async Task GetAgentAsync_Iris_ReturnsOrchestrator() public async Task GetAgentAsync_Iris_ReturnsOrchestrator()
{ {
var config = new ConfigurationBuilder() var configPath = CreateAgentConfigFile();
.AddInMemoryCollection(new Dictionary<string, string?> var config = CreateConfiguration(configPath);
{
["AgentConfigPath"] = "/home/node/.openclaw/openclaw.json"
})
.Build();
var runtime = new FakeRuntime(); var runtime = new FakeRuntime();
var service = new AgentService(config, runtime); var service = new AgentService(config, runtime);
@@ -44,18 +36,60 @@ public class AgentServiceTests
[Fact] [Fact]
public async Task GetAgentAsync_Unknown_ReturnsNull() public async Task GetAgentAsync_Unknown_ReturnsNull()
{ {
var config = new ConfigurationBuilder() var configPath = CreateAgentConfigFile();
.AddInMemoryCollection(new Dictionary<string, string?> var config = CreateConfiguration(configPath);
{
["AgentConfigPath"] = "/home/node/.openclaw/openclaw.json"
})
.Build();
var runtime = new FakeRuntime(); var runtime = new FakeRuntime();
var service = new AgentService(config, runtime); var service = new AgentService(config, runtime);
var agent = await service.GetAgentAsync("nonexistent", CancellationToken.None); var agent = await service.GetAgentAsync("nonexistent", CancellationToken.None);
Assert.Null(agent); Assert.Null(agent);
} }
private static IConfiguration CreateConfiguration(string configPath)
=> new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["AgentConfigPath"] = configPath
})
.Build();
private static string CreateAgentConfigFile()
{
var path = Path.Combine(Path.GetTempPath(), $"agent-config-{Guid.NewGuid():N}.json");
File.WriteAllText(path,
"""
{
"agents": {
"defaults": {
"workspace": "/workspace/default",
"model": {
"primary": "deepseek/deepseek-v4-flash"
}
},
"list": [
{
"id": "iris",
"name": "iris"
},
{
"id": "programmer",
"name": "programmer"
},
{
"id": "reviewer",
"name": "reviewer"
},
{
"id": "architekt",
"name": "architekt"
}
]
}
}
""");
return path;
}
} }
public sealed class FakeRuntime : IAgentRuntime public sealed class FakeRuntime : IAgentRuntime
+146
View File
@@ -0,0 +1,146 @@
using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using Nexus.Api.Controllers;
using Nexus.Api.Data;
using Nexus.Api.Integrations;
using Nexus.Api.Repositories;
using Nexus.Api.Services;
using Xunit;
namespace Nexus.Api.Tests;
public class OperationsSnapshotTests
{
[Fact]
public void GetSnapshot_RequiresAuthorization()
{
var method = typeof(OperationsController).GetMethod(nameof(OperationsController.GetSnapshot), BindingFlags.Instance | BindingFlags.Public);
Assert.NotNull(method);
Assert.NotNull(method!.GetCustomAttribute<AuthorizeAttribute>());
}
[Fact]
public async Task GetSnapshotAsync_DoesNotOverlapRepositoryReads()
{
var guard = new RepositoryConcurrencyGuard();
var runtime = new SnapshotRuntimeStub();
var agentService = new SnapshotAgentServiceStub();
var projectRepo = new GuardedProjectRepository(guard);
var taskRepo = new GuardedTaskRepository(guard);
var activityRepo = new GuardedActivityRepository(guard);
var service = new OperationsService(runtime, agentService, projectRepo, taskRepo, activityRepo);
await service.GetSnapshotAsync(CancellationToken.None);
Assert.Equal(1, guard.MaxConcurrentCalls);
}
}
internal sealed class RepositoryConcurrencyGuard
{
private readonly Lock sync = new();
private int currentCalls;
public int MaxConcurrentCalls { get; private set; }
public async Task<T> RunAsync<T>(T value, CancellationToken ct)
{
lock (sync)
{
currentCalls++;
MaxConcurrentCalls = Math.Max(MaxConcurrentCalls, currentCalls);
}
try
{
await Task.Delay(25, ct);
return value;
}
finally
{
lock (sync)
{
currentCalls--;
}
}
}
}
internal sealed class GuardedProjectRepository(RepositoryConcurrencyGuard guard) : IProjectRepository
{
public Task<List<Project>> GetAllAsync(CancellationToken ct = default)
=> guard.RunAsync(new List<Project>
{
new() { Name = "Alpha", Status = OperationalStatus.Online, Progress = 75 }
}, ct);
public ValueTask<Project?> GetByIdAsync(Guid id, CancellationToken ct = default) => throw new NotSupportedException();
public Task<Project> AddAsync(Project project, CancellationToken ct = default) => throw new NotSupportedException();
public Task UpdateAsync(Project project, CancellationToken ct = default) => throw new NotSupportedException();
public Task DeleteAsync(Project project, CancellationToken ct = default) => throw new NotSupportedException();
public Task<bool> HasTasksAsync(Guid projectId, CancellationToken ct = default) => throw new NotSupportedException();
}
internal sealed class GuardedTaskRepository(RepositoryConcurrencyGuard guard) : ITaskRepository
{
public Task<List<WorkTask>> GetAllAsync(CancellationToken ct = default)
=> guard.RunAsync(new List<WorkTask>
{
new() { Title = "Blocked task", State = TaskStateHelper.ToStateString(TaskState.Blocked), UpdatedAt = DateTimeOffset.UtcNow },
new() { Title = "Done task", State = TaskStateHelper.ToStateString(TaskState.Done), UpdatedAt = DateTimeOffset.UtcNow }
}, ct);
public ValueTask<WorkTask?> GetByIdAsync(Guid id, CancellationToken ct = default) => throw new NotSupportedException();
public Task<List<WorkTask>> GetPendingApprovalAsync(CancellationToken ct = default) => throw new NotSupportedException();
public Task<WorkTask> AddAsync(WorkTask task, CancellationToken ct = default) => throw new NotSupportedException();
public Task UpdateAsync(WorkTask task, CancellationToken ct = default) => throw new NotSupportedException();
public Task DeleteAsync(WorkTask task, CancellationToken ct = default) => throw new NotSupportedException();
public Task<int> CountAsync(CancellationToken ct = default) => throw new NotSupportedException();
public Task<int> CountByStateAsync(string state, CancellationToken ct = default) => throw new NotSupportedException();
public Task<WorkTask?> GetLastBlockedAsync(CancellationToken ct = default) => throw new NotSupportedException();
}
internal sealed class GuardedActivityRepository(RepositoryConcurrencyGuard guard) : IActivityRepository
{
public Task<List<ActivityEvent>> GetRecentAsync(int take, CancellationToken ct = default)
=> guard.RunAsync(new List<ActivityEvent>
{
new() { Id = 1, Type = "agent", Message = "recent activity", CreatedAt = DateTimeOffset.UtcNow }
}, ct);
public Task<List<ActivityEvent>> GetRecentForTasksAsync(IEnumerable<Guid> taskIds, CancellationToken ct = default)
=> guard.RunAsync(new List<ActivityEvent>(), ct);
public Task<(List<ActivityEvent> Items, int TotalCount)> GetPagedAsync(string? type, string? sort, int page, int pageSize, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task<List<ActivityEvent>> GetByAgentAsync(string agentId, int take, CancellationToken ct = default)
=> throw new NotSupportedException();
public Task<ActivityEvent> AddAsync(ActivityEvent activity, CancellationToken ct = default)
=> throw new NotSupportedException();
}
internal sealed class SnapshotRuntimeStub : IAgentRuntime
{
public string Name => "stub";
public Task<AgentRuntimeStatus> GetStatusAsync(CancellationToken cancellationToken = default)
=> Task.FromResult(new AgentRuntimeStatus("OpenClaw", OperationalStatus.Online, TimeSpan.FromMilliseconds(5), "ok"));
public Task<AgentChatResult> ChatAsync(string message, string conversationId, string agentId, CancellationToken cancellationToken = default)
=> throw new NotSupportedException();
}
internal sealed class SnapshotAgentServiceStub : IAgentService
{
public Task<IReadOnlyCollection<AgentInfo>> GetAgentsAsync(CancellationToken cancellationToken)
=> Task.FromResult<IReadOnlyCollection<AgentInfo>>(
[
new AgentInfo("iris", "Iris", "Orchestrator", "model", OperationalStatus.Online, DateTimeOffset.UtcNow, "/workspace", "ops")
]);
public Task<AgentDetail?> GetAgentAsync(string id, CancellationToken cancellationToken)
=> throw new NotSupportedException();
}
+253
View File
@@ -0,0 +1,253 @@
using Nexus.Api.Data;
using Xunit;
namespace Nexus.Api.Tests;
public class TaskBoardTests
{
// ── TaskStateHelper: BoardGroupKey ──
[Theory]
[InlineData("Backlog", "offen")]
[InlineData("In progress", "inProgress")]
[InlineData("Delegated", "delegated")]
[InlineData("Review", "review")]
[InlineData("Blocked", "blocked")]
[InlineData("Done", "done")]
[InlineData("backlog", "offen")]
[InlineData("in progress", "inProgress")]
[InlineData("delegated", "delegated")]
[InlineData("review", "review")]
[InlineData("blocked", "blocked")]
[InlineData("done", "done")]
[InlineData("", "offen")]
[InlineData(null, "offen")]
[InlineData("unknown", "offen")]
public void BoardGroupKey_ReturnsExpectedGroup(string? state, string expected)
{
var result = TaskStateHelper.BoardGroupKey(state);
Assert.Equal(expected, result);
}
// ── TaskStateHelper: BoardGroupToState ──
[Theory]
[InlineData("offen", "Backlog")]
[InlineData("inProgress", "In progress")]
[InlineData("inprogress", "In progress")]
[InlineData("delegated", "Delegated")]
[InlineData("review", "Review")]
[InlineData("blocked", "Blocked")]
[InlineData("done", "Done")]
[InlineData("Offen", "Backlog")]
[InlineData("", null)]
[InlineData(null, null)]
[InlineData("unknown", null)]
public void BoardGroupToState_ReturnsExpectedState(string? groupKey, string? expected)
{
var result = TaskStateHelper.BoardGroupToState(groupKey);
Assert.Equal(expected, result);
}
// ── TaskStateHelper: AllStates has 6 entries ──
[Fact]
public void AllStates_ContainsAllSixStates()
{
var states = TaskStateHelper.AllStates;
Assert.Equal(6, states.Length);
Assert.Contains("Backlog", states);
Assert.Contains("In progress", states);
Assert.Contains("Delegated", states);
Assert.Contains("Review", states);
Assert.Contains("Blocked", states);
Assert.Contains("Done", states);
}
// ── TaskStateHelper: IsValidState ──
[Theory]
[InlineData("Backlog", true)]
[InlineData("In progress", true)]
[InlineData("Delegated", true)]
[InlineData("Review", true)]
[InlineData("Blocked", true)]
[InlineData("Done", true)]
[InlineData("backlog", true)]
[InlineData("offen", false)]
[InlineData("", false)]
[InlineData(null, false)]
[InlineData("unknown", false)]
public void IsValidState_ReturnsCorrectResult(string? state, bool expected)
{
Assert.Equal(expected, TaskStateHelper.IsValidState(state));
}
// ── TaskStateHelper: IsInProgressOrBlocked ──
[Theory]
[InlineData("In progress", true)]
[InlineData("Blocked", true)]
[InlineData("Backlog", false)]
[InlineData("Delegated", false)]
[InlineData("Review", false)]
[InlineData("Done", false)]
[InlineData(null, false)]
public void IsInProgressOrBlocked_ReturnsCorrectResult(string? state, bool expected)
{
Assert.Equal(expected, TaskStateHelper.IsInProgressOrBlocked(state));
}
// ── TaskStateHelper: IsDoneOrBacklog ──
[Theory]
[InlineData("Done", true)]
[InlineData("Backlog", true)]
[InlineData("In progress", false)]
[InlineData("Delegated", false)]
[InlineData("Review", false)]
[InlineData("Blocked", false)]
[InlineData(null, false)]
public void IsDoneOrBacklog_ReturnsCorrectResult(string? state, bool expected)
{
Assert.Equal(expected, TaskStateHelper.IsDoneOrBacklog(state));
}
// ── TaskStateHelper: ToDisplayString ──
[Theory]
[InlineData("Backlog", "Offen")]
[InlineData("In progress", "In Bearbeitung")]
[InlineData("Delegated", "Delegiert")]
[InlineData("Review", "Review")]
[InlineData("Blocked", "Blockiert")]
[InlineData("Done", "Erledigt")]
[InlineData("backlog", "Offen")]
[InlineData("", "")]
[InlineData(null, "")]
[InlineData("unknown", "unknown")]
public void ToDisplayString_ReturnsGermanLabel(string? state, string expected)
{
Assert.Equal(expected, TaskStateHelper.ToDisplayString(state));
}
// ── TaskState helper: ToStateString and ToTaskState roundtrip ──
[Fact]
public void ToStateString_And_ToTaskState_RoundTrip()
{
var states = new[] { TaskState.Backlog, TaskState.InProgress, TaskState.Delegated, TaskState.Review, TaskState.Blocked, TaskState.Done };
foreach (var state in states)
{
var str = state.ToStateString();
var parsed = str.ToTaskState();
Assert.Equal(state, parsed);
}
}
[Fact]
public void ToTaskState_DefaultsToBacklog_ForUnknownString()
{
Assert.Equal(TaskState.Backlog, "unknown".ToTaskState());
}
// ── TaskStateHelper: CanChangeState (Iris + Bao policy) ──
[Fact]
public void CanChangeState_Iris_CanChangeAnyTask()
{
var agentTask = new WorkTask { Title = "test", IsAgentTask = true, Source = "iris" };
var normalTask = new WorkTask { Title = "test", IsAgentTask = false, Source = "bao" };
Assert.True(TaskStateHelper.CanChangeState("iris", agentTask));
Assert.True(TaskStateHelper.CanChangeState("iris", normalTask));
}
[Fact]
public void CanChangeState_Bao_CanChangeAnyTask()
{
var agentTask = new WorkTask { Title = "test", IsAgentTask = true, Source = "iris" };
var normalTask = new WorkTask { Title = "test", IsAgentTask = false, Source = "bao" };
Assert.True(TaskStateHelper.CanChangeState("bao", agentTask));
Assert.True(TaskStateHelper.CanChangeState("bao", normalTask));
}
[Fact]
public void CanChangeState_SubAgents_NeverAllowed()
{
var task = new WorkTask { Title = "test", IsAgentTask = false, Source = "bao" };
Assert.False(TaskStateHelper.CanChangeState("programmer", task));
Assert.False(TaskStateHelper.CanChangeState("reviewer", task));
Assert.False(TaskStateHelper.CanChangeState("architekt", task));
}
[Fact]
public void CanChangeState_SubAgents_NeverAllowed_EvenForAgentTasks()
{
var agentTask = new WorkTask { Title = "test", IsAgentTask = true, Source = "iris" };
Assert.False(TaskStateHelper.CanChangeState("programmer", agentTask));
Assert.False(TaskStateHelper.CanChangeState("reviewer", agentTask));
Assert.False(TaskStateHelper.CanChangeState("architekt", agentTask));
}
[Fact]
public void CanChangeState_NexusSystem_IsAllowed()
{
var task = new WorkTask { Title = "test", IsAgentTask = false };
Assert.True(TaskStateHelper.CanChangeState("nexus-system", task));
var agentTask = new WorkTask { Title = "test", IsAgentTask = true };
Assert.True(TaskStateHelper.CanChangeState("nexus-system", agentTask));
}
[Fact]
public void CanChangeState_UnknownCaller_Rejected()
{
var task = new WorkTask { Title = "test", IsAgentTask = false };
var agentTask = new WorkTask { Title = "test", IsAgentTask = true };
Assert.False(TaskStateHelper.CanChangeState("", task));
Assert.False(TaskStateHelper.CanChangeState("", agentTask));
Assert.False(TaskStateHelper.CanChangeState("unknown", task));
Assert.False(TaskStateHelper.CanChangeState(null, task));
}
// ── TaskStateHelper: CanEditContent ──
[Fact]
public void CanEditContent_Iris_IsAllowed()
{
Assert.True(TaskStateHelper.CanEditContent("iris"));
}
[Fact]
public void CanEditContent_Bao_IsAllowed()
{
Assert.True(TaskStateHelper.CanEditContent("bao"));
}
[Fact]
public void CanEditContent_SubAgents_AreAllowed()
{
Assert.True(TaskStateHelper.CanEditContent("programmer"));
Assert.True(TaskStateHelper.CanEditContent("reviewer"));
Assert.True(TaskStateHelper.CanEditContent("architekt"));
}
[Fact]
public void CanEditContent_NexusSystem_IsAllowed()
{
Assert.True(TaskStateHelper.CanEditContent("nexus-system"));
}
[Fact]
public void CanEditContent_UnknownCaller_Rejected()
{
Assert.False(TaskStateHelper.CanEditContent(""));
Assert.False(TaskStateHelper.CanEditContent(null));
Assert.False(TaskStateHelper.CanEditContent(" "));
}
}
+184
View File
@@ -0,0 +1,184 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Data;
using Nexus.Api.DTOs;
using Nexus.Api.Repositories;
using Nexus.Api.Services;
namespace Nexus.Api.Controllers;
/// <summary>
/// Admin/User-Management erreichbar für owner und admin-Rollen.
///
/// Sicherheitsregeln:
/// - Nur owner und admin dürfen User verwalten.
/// - Die Rolle "owner" kann weder vergeben noch überschrieben werden sie ist
/// eine Sonderrolle, die nur bei der initialen Seed-Erstellung gesetzt wird.
/// - Über die API sind nur die Rollen "admin", "user" und "viewer" wählbar.
/// </summary>
[ApiController]
[Route("api/v1/admin")]
[Authorize(Roles = "owner,admin")]
public class AdminController(
IUserRepository userRepository,
ILogger<AdminController> logger) : ControllerBase
{
private static readonly string[] SettableRoles = ["admin", "user", "viewer"];
/// <summary>
/// Alle registrierten User auflisten.
/// </summary>
[HttpGet("users")]
public async Task<IResult> GetUsers(CancellationToken ct)
{
var users = await userRepository.GetAllAsync(ct);
var result = users.Select(u => new AdminUserInfo
{
Id = u.Id,
Email = u.Email,
DisplayName = u.DisplayName,
Role = u.Role,
CreatedAt = u.CreatedAt,
LastLoginAt = u.LastLoginAt,
}).ToList();
return Results.Ok(result);
}
/// <summary>
/// Neuen User anlegen.
/// Die Rolle "owner" kann NICHT gesetzt werden.
/// </summary>
[HttpPost("users")]
public async Task<IResult> CreateUser([FromBody] AdminCreateUserRequest request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["request"] = ["Email and password are required."]
});
if (request.Password.Length < 10)
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["password"] = ["Password must be at least 10 characters."]
});
// Role validieren owner ist nicht über API setzbar
var targetRole = string.IsNullOrWhiteSpace(request.Role) ? "user" : request.Role.Trim().ToLowerInvariant();
if (!SettableRoles.Contains(targetRole))
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["role"] = [$"Invalid role. Valid roles: {string.Join(", ", SettableRoles)}."]
});
var normalizedEmail = AuthService.NormalizeEmail(request.Email);
var existing = await userRepository.GetByEmailAsync(normalizedEmail, ct);
if (existing is not null)
return Results.Conflict(new { error = "A user with this email already exists." });
var user = new NexusUser
{
Email = request.Email.Trim(),
NormalizedEmail = normalizedEmail,
DisplayName = string.IsNullOrWhiteSpace(request.DisplayName)
? request.Email.Split('@')[0]
: request.DisplayName.Trim(),
PasswordHash = PasswordSecurity.Hash(request.Password),
Role = targetRole,
};
await userRepository.AddAsync(user, ct);
logger.LogInformation("User {Role} created user {Email} with role {Role}", UserRole(), user.Email, user.Role);
return Results.Created($"/api/v1/admin/users/{user.Id}", new AdminUserInfo
{
Id = user.Id,
Email = user.Email,
DisplayName = user.DisplayName,
Role = user.Role,
CreatedAt = user.CreatedAt,
});
}
/// <summary>
/// User löschen. Eigene owner-User und der eigene Account sind geschützt.
/// </summary>
[HttpDelete("users/{id:guid}")]
public async Task<IResult> DeleteUser(Guid id, CancellationToken ct)
{
var user = await userRepository.GetByIdAsync(id, ct);
if (user is null)
return Results.NotFound(new { error = "User not found." });
if (string.Equals(user.Role, "owner", StringComparison.OrdinalIgnoreCase))
return Results.Problem("Owner accounts cannot be deleted via API.", statusCode: 403);
if (user.Id.ToString() == CurrentUserId())
return Results.Problem("You cannot delete your own account.", statusCode: 403);
await userRepository.DeleteAsync(user, ct);
logger.LogInformation("User {Role} deleted user {Email}", UserRole(), user.Email);
return Results.NoContent();
}
/// <summary>
/// Rolle eines Users ändern. "owner" kann weder gesetzt noch überschrieben werden.
/// </summary>
[HttpPatch("users/{id:guid}/role")]
public async Task<IResult> UpdateUserRole(Guid id, [FromBody] AdminUpdateRoleRequest request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Role))
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["role"] = ["Role is required."]
});
var newRole = request.Role.Trim().ToLowerInvariant();
if (!SettableRoles.Contains(newRole))
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["role"] = [$"Invalid role. Valid: {string.Join(", ", SettableRoles)}. Owner is reserved."]
});
var user = await userRepository.GetByIdAsync(id, ct);
if (user is null)
return Results.NotFound(new { error = "User not found." });
// Niemals owner überschreiben
if (string.Equals(user.Role, "owner", StringComparison.OrdinalIgnoreCase))
return Results.Problem("Owner role cannot be modified via API.", statusCode: 403);
// admin darf andere admins nicht ändern (nur owner)
var callerRole = UserRole();
if (callerRole == "admin" && string.Equals(user.Role, "admin", StringComparison.OrdinalIgnoreCase))
return Results.Problem("Admin users can only be managed by the owner.", statusCode: 403);
// admin darf sich nicht selbst herabstufen
if (callerRole == "admin" && user.Id.ToString() == CurrentUserId() && newRole != "admin")
return Results.Problem("You cannot demote yourself.", statusCode: 403);
user.Role = newRole;
user.UpdatedAt = DateTimeOffset.UtcNow;
await userRepository.UpdateAsync(user, ct);
logger.LogInformation("User {Role} changed role for {Email} from {OldRole} to {NewRole}",
callerRole, user.Email, user.Role, newRole);
return Results.Ok(new AdminUserInfo
{
Id = user.Id,
Email = user.Email,
DisplayName = user.DisplayName,
Role = user.Role,
CreatedAt = user.CreatedAt,
LastLoginAt = user.LastLoginAt,
});
}
/// <summary>Liefert die Rolle des aufrufenden Users.</summary>
private string UserRole()
=> User.FindFirst(System.Security.Claims.ClaimTypes.Role)?.Value?.ToLowerInvariant() ?? "unknown";
/// <summary>Liefert die Subject-ID des aufrufenden Users.</summary>
private string? CurrentUserId()
=> User.FindFirst(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub)?.Value;
}
+28 -60
View File
@@ -1,8 +1,6 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using Nexus.Api.Data;
using Nexus.Api.DTOs; using Nexus.Api.DTOs;
using Nexus.Api.Helpers;
using Nexus.Api.Integrations; using Nexus.Api.Integrations;
using Nexus.Api.Repositories; using Nexus.Api.Repositories;
using Nexus.Api.Services; using Nexus.Api.Services;
@@ -15,6 +13,7 @@ public class AgentsController(
IAgentService agentService, IAgentService agentService,
IAgentRuntime runtime, IAgentRuntime runtime,
IActivityRepository activityRepo, IActivityRepository activityRepo,
IAgentConfigService agentConfigService,
ILogger<AgentsController> logger) : ControllerBase ILogger<AgentsController> logger) : ControllerBase
{ {
[HttpGet] [HttpGet]
@@ -22,8 +21,7 @@ public class AgentsController(
{ {
var agents = await agentService.GetAgentsAsync(ct); var agents = await agentService.GetAgentsAsync(ct);
return Results.Ok(agents.Select(a => new AgentListResponse( return Results.Ok(agents.Select(a => new AgentListResponse(
a.Id, a.Name, a.Role, a.Model, a.Status.ToString(), a.LastSeen, a.Workspace, a.Description a.Id, a.Name, a.Role, a.Model, a.Status.ToString(), a.LastSeen, a.Workspace, a.Description)));
)));
} }
[HttpGet("{id}")] [HttpGet("{id}")]
@@ -34,8 +32,7 @@ public class AgentsController(
return Results.Ok(new AgentDetailResponse( return Results.Ok(new AgentDetailResponse(
agent.Id, agent.Name, agent.Role, agent.Model, agent.Status.ToString(), agent.Id, agent.Name, agent.Role, agent.Model, agent.Status.ToString(),
agent.LastSeen, agent.Workspace, agent.AgentDir, agent.Description, agent.LastSeen, agent.Workspace, agent.AgentDir, agent.Description,
agent.SubAgents, agent.IdentityName agent.SubAgents, agent.IdentityName));
));
} }
[HttpGet("{id}/activity")] [HttpGet("{id}/activity")]
@@ -58,9 +55,7 @@ public class AgentsController(
try try
{ {
var result = await runtime.ChatAsync(message, conversationId, id, ct); var result = await runtime.ChatAsync(message, conversationId, id, ct);
await activityRepo.AddAsync(new Data.ActivityEvent { Type = "agent", Message = $"Command sent to agent {id}: {message[..Math.Min(message.Length, 80)]}" }, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "agent", Message = $"Command sent to agent {id}: {message[..Math.Min(message.Length, 80)]}" }, ct);
return Results.Ok(new AgentCommandResponse(result.Runtime, result.AgentId, result.ConversationId, result.Content)); return Results.Ok(new AgentCommandResponse(result.Runtime, result.AgentId, result.ConversationId, result.Content));
} }
catch (Exception exception) catch (Exception exception)
@@ -73,79 +68,52 @@ public class AgentsController(
} }
} }
// ========== Agent Config Editor ========== // ── Config Editor ──
[HttpGet("{id}/config")] [HttpGet("{id}/config")]
public IResult GetConfig(string id) public IResult GetConfig(string id)
{ => Results.Ok(agentConfigService.GetConfigFiles(id));
var workspacePath = $"/mnt/workspace-{id}";
if (!Directory.Exists(workspacePath))
return Results.Ok(Array.Empty<object>());
var allowedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"IDENTITY.md", "SOUL.md", "AGENTS.md", "TOOLS.md", "HEARTBEAT.md", "USER.md", "MEMORY.md"
};
var files = Directory.GetFiles(workspacePath, "*.md")
.Select(f => new FileInfo(f))
.Where(f => allowedFiles.Contains(f.Name))
.OrderBy(f => f.Name)
.Select(f => new
{
fileName = f.Name,
size = f.Length,
modifiedAt = f.LastWriteTimeUtc
})
.ToList();
return Results.Ok(files);
}
[HttpGet("{id}/config/{fileName}")] [HttpGet("{id}/config/{fileName}")]
public async Task<IResult> GetConfigFile(string id, string fileName, CancellationToken ct) public async Task<IResult> GetConfigFile(string id, string fileName, CancellationToken ct)
{ {
if (!PathSecurityHelper.IsValidConfigFileName(fileName)) var file = await agentConfigService.GetConfigFileAsync(id, fileName, ct);
return Results.BadRequest(new { error = "Invalid filename. Only .md files with alphanumeric characters, dots, hyphens, and underscores are allowed." }); return file is null
? Results.NotFound()
var workspacePath = $"/mnt/workspace-{id}"; : Results.Ok(new { file.FileName, file.Content, file.Size, file.ModifiedAt });
if (!PathSecurityHelper.TryResolveSafePath(workspacePath, fileName, out var safePath) || !System.IO.File.Exists(safePath))
return Results.NotFound();
var content = await System.IO.File.ReadAllTextAsync(safePath!, ct);
var fi = new FileInfo(safePath!);
return Results.Ok(new { fileName, content, size = fi.Length, modifiedAt = fi.LastWriteTimeUtc });
} }
[HttpPut("{id}/config/{fileName}")] [HttpPut("{id}/config/{fileName}")]
public async Task<IResult> SaveConfigFile(string id, string fileName, [FromBody] SaveConfigRequest request, CancellationToken ct) public async Task<IResult> SaveConfigFile(string id, string fileName, [FromBody] SaveConfigRequest request, CancellationToken ct)
{ {
if (!PathSecurityHelper.IsValidConfigFileName(fileName))
return Results.BadRequest(new { error = "Invalid filename. Only .md files with alphanumeric characters, dots, hyphens, and underscores are allowed." });
if (request.Content is null) if (request.Content is null)
return Results.BadRequest(new { error = "Content is required." }); return Results.BadRequest(new { error = "Content is required." });
if (request.Content.Length > 500 * 1024) if (request.Content.Length > 500 * 1024)
return Results.BadRequest(new { error = "Content exceeds maximum size of 500KB." }); return Results.BadRequest(new { error = "Content exceeds maximum size of 500KB." });
var workspacePath = $"/mnt/workspace-{id}";
if (!PathSecurityHelper.TryResolveSafePath(workspacePath, fileName, out var safePath))
return Results.NotFound();
var tempPath = safePath + ".tmp";
try try
{ {
await System.IO.File.WriteAllTextAsync(tempPath, request.Content, ct); var result = await agentConfigService.SaveConfigFileAsync(id, fileName, request.Content, ct);
System.IO.File.Move(tempPath, safePath, overwrite: true); return result is null
? Results.BadRequest(new { error = "Invalid filename or path." })
: Results.Ok(new { result.FileName, result.Size, result.ModifiedAt });
} }
catch catch (UnauthorizedAccessException ex)
{ {
if (System.IO.File.Exists(tempPath)) System.IO.File.Delete(tempPath); logger.LogError(ex, "Permission denied saving config file {FileName} for agent {AgentId}", fileName, id);
throw; return Results.Problem(
title: "Permission denied",
detail: $"Cannot write config file '{fileName}' for agent '{id}'. The target path may be owned by a different user.",
statusCode: StatusCodes.Status500InternalServerError);
}
catch (IOException ex)
{
logger.LogError(ex, "I/O error saving config file {FileName} for agent {AgentId}", fileName, id);
return Results.Problem(
title: "File write error",
detail: $"Failed to write config file '{fileName}' for agent '{id}': {ex.Message}",
statusCode: StatusCodes.Status500InternalServerError);
} }
var fi = new FileInfo(safePath);
return Results.Ok(new { fileName, size = fi.Length, modifiedAt = fi.LastWriteTimeUtc });
} }
} }
+34 -3
View File
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks;
using Nexus.Api.DTOs; using Nexus.Api.DTOs;
using Nexus.Api.Integrations; using Nexus.Api.Integrations;
using Nexus.Api.RateLimiting;
using Nexus.Api.Services; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
@@ -14,7 +15,8 @@ public class AuthController(
IAuthService authService, IAuthService authService,
IAntiforgery antiforgery, IAntiforgery antiforgery,
IConfiguration config, IConfiguration config,
IHostEnvironment env) : ControllerBase IHostEnvironment env,
LoginAttemptTracker attemptTracker) : ControllerBase
{ {
[HttpGet("csrf")] [HttpGet("csrf")]
public IActionResult GetCsrfToken() public IActionResult GetCsrfToken()
@@ -30,11 +32,38 @@ public class AuthController(
if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password)) if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
return Results.ValidationProblem(new Dictionary<string, string[]> { ["credentials"] = ["Email and password are required."] }); return Results.ValidationProblem(new Dictionary<string, string[]> { ["credentials"] = ["Email and password are required."] });
var session = await authService.LoginAsync(request, ct); var ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
if (session is null) return Results.Unauthorized();
var session = await authService.LoginAsync(request, ct);
if (session is null)
{
var remaining = attemptTracker.RecordFailedAttempt(ip);
var retryAfterSeconds = attemptTracker.GetRetryAfterSeconds(ip);
// Attach remaining info to the 401 response via headers only
// (the frontend can also parse the 429 body)
HttpContext.Response.Headers["X-RateLimit-Remaining"] = remaining.ToString();
HttpContext.Response.Headers["X-RateLimit-Limit"] = "5";
if (retryAfterSeconds > 0)
HttpContext.Response.Headers["X-RateLimit-Reset"] =
DateTimeOffset.UtcNow.AddSeconds(retryAfterSeconds).ToUnixTimeSeconds().ToString();
// Return a structured body so the frontend can display remaining attempts
return Results.Json(new
{
error = "invalid_credentials",
message = "Invalid email or password.",
remaining,
retryAfterSeconds
}, statusCode: 401);
}
// Success — reset attempt counter
attemptTracker.Reset(ip);
SetRefreshCookie(Response, session.RefreshToken); SetRefreshCookie(Response, session.RefreshToken);
Response.Headers.CacheControl = "no-store"; Response.Headers.CacheControl = "no-store";
Response.Headers["X-RateLimit-Remaining"] = "5";
Response.Headers["X-RateLimit-Limit"] = "5";
return Results.Ok(ToAuthResponse(session)); return Results.Ok(ToAuthResponse(session));
} }
@@ -54,6 +83,8 @@ public class AuthController(
SetRefreshCookie(Response, session.RefreshToken); SetRefreshCookie(Response, session.RefreshToken);
Response.Headers.CacheControl = "no-store"; Response.Headers.CacheControl = "no-store";
Response.Headers["X-RateLimit-Remaining"] = "5";
Response.Headers["X-RateLimit-Limit"] = "5";
return Results.Ok(ToAuthResponse(session)); return Results.Ok(ToAuthResponse(session));
} }
+4 -67
View File
@@ -1,80 +1,17 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.DTOs; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/calendar")] [Route("api/v1/calendar")]
public class CalendarController(IConfiguration config, IHttpClientFactory httpClientFactory, ILogger<CalendarController> logger) : ControllerBase public class CalendarController(ICalendarService calendarService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public async Task<IResult> GetAll(CancellationToken ct) public async Task<IResult> GetAll(CancellationToken ct)
{ => Results.Ok(await calendarService.GetCronJobsAsync(ct));
var gatewayToken = config["Integrations:OpenClaw:Token"] ?? "";
try
{
var httpClient = httpClientFactory.CreateClient("gateway");
if (!string.IsNullOrWhiteSpace(gatewayToken))
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", gatewayToken);
var response = await httpClient.GetAsync("/api/cron", ct);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadFromJsonAsync<List<CronJobEntry>>(ct);
return Results.Ok(data ?? new List<CronJobEntry>());
}
}
catch (Exception ex)
{
logger.LogDebug(ex, "Gateway cron endpoint not reachable, using fallback data.");
}
var fallbackJobs = new List<object>
{
new { id = "health-check", name = "Health Check", schedule = "*/5 * * * *", lastRun = DateTimeOffset.UtcNow.AddMinutes(-3).ToString("O"), nextRun = DateTimeOffset.UtcNow.AddMinutes(2).ToString("O"), status = "completed" },
new { id = "memory-sync", name = "Memory Sync", schedule = "0 */6 * * *", lastRun = DateTimeOffset.UtcNow.AddHours(-2).ToString("O"), nextRun = DateTimeOffset.UtcNow.AddHours(4).ToString("O"), status = "completed" },
new { id = "task-cleanup", name = "Task Cleanup", schedule = "0 3 * * *", lastRun = DateTimeOffset.UtcNow.AddDays(-1).ToString("O"), nextRun = DateTimeOffset.UtcNow.AddDays(1).AddHours(3).ToString("O"), status = "completed" },
new { id = "backup", name = "Database Backup", schedule = "0 4 * * *", lastRun = DateTimeOffset.UtcNow.AddDays(-1).AddHours(-1).ToString("O"), nextRun = DateTimeOffset.UtcNow.AddDays(1).AddHours(4).ToString("O"), status = "completed" },
new { id = "model-routing-refresh", name = "Model Routing Refresh", schedule = "*/30 * * * *", lastRun = DateTimeOffset.UtcNow.AddMinutes(-12).ToString("O"), nextRun = DateTimeOffset.UtcNow.AddMinutes(18).ToString("O"), status = "running" },
};
return Results.Ok(fallbackJobs);
}
[HttpGet("upcoming")] [HttpGet("upcoming")]
public async Task<IResult> GetUpcoming(CancellationToken ct) public async Task<IResult> GetUpcoming(CancellationToken ct)
{ => Results.Ok(await calendarService.GetUpcomingCronJobsAsync(ct));
var gatewayToken = config["Integrations:OpenClaw:Token"] ?? "";
try
{
var httpClient = httpClientFactory.CreateClient("gateway");
if (!string.IsNullOrWhiteSpace(gatewayToken))
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", gatewayToken);
var response = await httpClient.GetAsync("/api/cron/upcoming", ct);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadFromJsonAsync<List<UpcomingCronEntry>>(ct);
return Results.Ok(data ?? new List<UpcomingCronEntry>());
}
}
catch (Exception ex)
{
logger.LogDebug(ex, "Gateway upcoming cron endpoint not reachable, using fallback data.");
}
var now = DateTimeOffset.UtcNow;
var fallback = new List<object>
{
new { id = "health-check", name = "Health Check", nextRun = now.AddMinutes(2).ToString("O"), schedule = "*/5 * * * *" },
new { id = "model-routing-refresh", name = "Model Routing Refresh", nextRun = now.AddMinutes(18).ToString("O"), schedule = "*/30 * * * *" },
new { id = "memory-sync", name = "Memory Sync", nextRun = now.AddHours(4).ToString("O"), schedule = "0 */6 * * *" },
new { id = "task-cleanup", name = "Task Cleanup", nextRun = now.AddDays(1).AddHours(3).ToString("O"), schedule = "0 3 * * *" },
new { id = "backup", name = "Database Backup", nextRun = now.AddDays(1).AddHours(4).ToString("O"), schedule = "0 4 * * *" },
};
return Results.Ok(fallback);
}
} }
+277 -191
View File
@@ -1,267 +1,353 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Data;
using Nexus.Api.Models; using Nexus.Api.Models;
using Nexus.Api.Repositories;
using Nexus.Api.Services; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[Authorize]
[ApiController] [ApiController]
[Route("api/dashboard")] [Route("api/dashboard")]
public class DashboardController(OpenClawGatewayClient gateway, ILogger<DashboardController> logger) public class DashboardController(
: ControllerBase IDashboardService dashboardService,
ITaskService taskService,
IActivityRepository activityService,
IHttpContextAccessor httpContextAccessor) : ControllerBase
{ {
/// <summary>
/// Gateway health + session_status + subagents count.
/// Returns HTTP 200 even when gateway is down (gatewayOk: false).
/// </summary>
[HttpGet("status")] [HttpGet("status")]
public async Task<DashboardStatus> GetStatus() public async Task<DashboardStatus> GetStatus()
{ => await dashboardService.GetStatusAsync();
try
{
return await gateway.GetStatusAsync();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard status check failed");
return new DashboardStatus(false, "Offline", 0, 0);
}
}
/// <summary>
/// Returns all agents with their current status.
/// Combines sessions_list + sub_agents_list.
/// </summary>
[HttpGet("agents")] [HttpGet("agents")]
public async Task<List<DashboardAgentInfo>> GetAgents() public async Task<List<DashboardAgentInfo>> GetAgents()
{ => await dashboardService.GetAgentsAsync();
try
{
return await gateway.GetAgentsAsync();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard agents fetch failed");
return new List<DashboardAgentInfo>();
}
}
/// <summary>
/// Returns the latest assistant messages (operations/feed) from the Iris session.
/// Filtered to role == "assistant" — those are the work feed entries.
/// </summary>
[HttpGet("operations")] [HttpGet("operations")]
public async Task<List<FeedEntry>> GetOperations([FromQuery] int limit = 20) public async Task<List<FeedEntry>> GetOperations(
{ [FromQuery] int limit = 20,
try [FromQuery] string? agent = null)
{ => await dashboardService.GetOperationsAsync(limit, agent);
var messages = await gateway.GetSessionHistoryAsync("iris", Math.Clamp(limit, 1, 100));
var feed = new List<FeedEntry>();
foreach (var msg in messages)
{
if (!string.Equals(msg.Role, "assistant", StringComparison.OrdinalIgnoreCase))
continue;
if (string.IsNullOrWhiteSpace(msg.Content))
continue;
// Parse timestamp for display-friendly "time ago"
var ts = ParseTimestamp(msg.Timestamp);
var timeAgo = FormatTimeAgo(ts);
// Extract a short agent indicator and action from content
var (agent, action) = ExtractAgentAction(msg.Content);
feed.Add(new FeedEntry(agent, action, msg.Timestamp, timeAgo));
}
return feed;
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard operations fetch failed");
return new List<FeedEntry>();
}
}
/// <summary>
/// Send a chat message to the Iris session.
/// </summary>
[HttpPost("chat/send")] [HttpPost("chat/send")]
public async Task<ChatResponse> SendChat([FromBody] ChatRequest request) public async Task<ChatResponse> SendChat([FromBody] ChatRequest request)
{ {
if (string.IsNullOrWhiteSpace(request.Message)) if (string.IsNullOrWhiteSpace(request.Message))
return new ChatResponse(false, null, "Message is required"); return new ChatResponse(false, null, "Message is required");
try var agentId = string.IsNullOrWhiteSpace(request.AgentId) ? "iris" : request.AgentId.Trim();
{ return await dashboardService.SendChatAsync(agentId, request.Message.Trim());
var agentId = string.IsNullOrWhiteSpace(request.AgentId)
? "iris"
: request.AgentId.Trim();
return await gateway.SendChatMessageAsync(agentId, request.Message.Trim());
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard chat send failed");
return new ChatResponse(false, null, "Gateway nicht erreichbar");
}
} }
/// <summary>
/// Returns chat messages (user + assistant only, not tool messages).
/// </summary>
[HttpGet("chat/messages")] [HttpGet("chat/messages")]
public async Task<List<MessageEntry>> GetMessages( public async Task<List<MessageEntry>> GetMessages(
[FromQuery] string? sessionKey, [FromQuery] string? sessionKey,
[FromQuery] int limit = 50, [FromQuery] int limit = 50,
[FromQuery] int offset = 0) [FromQuery] int offset = 0)
{ => await dashboardService.GetMessagesAsync(sessionKey, limit, offset);
try
{
var key = string.IsNullOrWhiteSpace(sessionKey) ? "agent:iris:main" : sessionKey.Trim();
var messages = await gateway.GetSessionHistoryAsync(key, Math.Clamp(limit, 1, 200), Math.Max(0, offset));
return messages
.Where(m => string.Equals(m.Role, "user", StringComparison.OrdinalIgnoreCase)
|| string.Equals(m.Role, "assistant", StringComparison.OrdinalIgnoreCase))
.ToList();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard messages fetch failed");
return new List<MessageEntry>();
}
}
/// <summary>
/// Returns the cron queue / pending tasks.
/// </summary>
[HttpGet("queue")] [HttpGet("queue")]
public async Task<List<QueueItem>> GetQueue() public async Task<List<QueueItem>> GetQueue(CancellationToken ct)
=> await dashboardService.GetQueueAsync(ct);
[HttpDelete("queue/{id}")]
public async Task<ActionResult> DeleteQueueItem(string id, [FromQuery] string? source, CancellationToken ct)
{ {
try var result = await dashboardService.DeleteQueueItemAsync(id, source, ct);
return result.Outcome switch
{ {
return await gateway.GetQueueAsync(); QueueDeleteOutcome.Deleted => NoContent(),
} QueueDeleteOutcome.NotFound => NotFound(new { error = "Queue item not found" }),
catch (Exception ex) QueueDeleteOutcome.GatewayError => StatusCode(502, new { error = "Gateway could not delete cron job" }),
{ QueueDeleteOutcome.TaskNotFound => NotFound(new { error = "Task not found" }),
logger.LogWarning(ex, "Dashboard queue fetch failed"); QueueDeleteOutcome.InvalidTaskId => BadRequest(new { error = "Invalid task id" }),
return new List<QueueItem>(); _ => StatusCode(500, new { error = "Internal error" })
} };
}
[HttpPut("queue/{id}/priority")]
public async Task<ActionResult> ChangeQueuePriority(string id, CancellationToken ct)
{
var result = await dashboardService.CycleQueuePriorityAsync(id, ct);
return result.Outcome switch
{
QueuePriorityOutcome.Ignored => Ok(new { status = "ignored", reason = "Cron job priorities are managed by the gateway" }),
QueuePriorityOutcome.TaskNotFound => NotFound(new { error = "Task not found" }),
QueuePriorityOutcome.InvalidTaskId => BadRequest(new { error = "Invalid task id" }),
_ => Ok(new { status = "ok", priority = result.NewPriority })
};
} }
/// <summary>
/// Returns the current model and provider for a specific agent session.
/// Calls session_status with the agent's session key.
/// </summary>
[HttpGet("agents/{id}/model")] [HttpGet("agents/{id}/model")]
public async Task<ActionResult<AgentModelInfo>> GetAgentModel(string id) public async Task<ActionResult<AgentModelInfo>> GetAgentModel(string id)
{ {
try var info = await dashboardService.GetAgentModelAsync(id);
{ return info is null
var info = await gateway.GetAgentModelAsync(id); ? NotFound(new { error = $"Agent '{id}' not found or gateway unreachable" })
if (info is null) : Ok(info);
return NotFound(new { error = $"Agent '{id}' not found or gateway unreachable" });
return Ok(info);
}
catch (Exception ex)
{
logger.LogWarning(ex, "GetAgentModel failed for {AgentId}", id);
return StatusCode(500, new { error = "Internal error" });
}
} }
/// <summary>
/// Sets the model for a specific agent session.
/// Calls session_status with model parameter.
/// </summary>
[HttpPut("agents/{id}/model")] [HttpPut("agents/{id}/model")]
public async Task<ActionResult> SetAgentModel(string id, [FromBody] SetModelRequest request) public async Task<ActionResult> SetAgentModel(string id, [FromBody] SetModelRequest request)
{ {
if (string.IsNullOrWhiteSpace(request.Model)) if (string.IsNullOrWhiteSpace(request.Model))
return BadRequest(new { error = "Model is required" }); return BadRequest(new { error = "Model is required" });
var ok = await dashboardService.SetAgentModelAsync(id, request.Model);
return ok ? Ok(new { status = "ok", model = request.Model }) : StatusCode(502, new { error = "Gateway did not accept the change" });
}
[HttpGet("agents/{id}/activity")]
public async Task<List<AgentActivityEntry>> GetAgentActivity(string id, [FromQuery] int limit = 5)
=> await dashboardService.GetAgentActivityAsync(id, limit);
[HttpGet("models")]
public ActionResult<List<ModelOption>> GetAvailableModels()
=> Ok(dashboardService.GetAvailableModels());
// ── Task Endpoints ──
[HttpGet("tasks")]
public async Task<List<DashboardTaskDto>> GetTasks(CancellationToken ct)
{
var tasks = await taskService.GetOpenAsync(ct);
return tasks.Select(MapToDto).ToList();
}
[HttpPost("tasks")]
public async Task<ActionResult<DashboardTaskDto>> CreateTask(
[FromBody] CreateDashboardTaskRequest request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Title))
return BadRequest(new { error = "Title is required." });
try try
{ {
var ok = await gateway.SetAgentModelAsync(id, request.Model); var task = await taskService.CreateDashboardTaskAsync(
if (!ok) request.Title, request.Detail, request.Source, request.Priority, request.AssignedTo, request.ParentTaskId, ct);
return StatusCode(502, new { error = "Gateway did not accept the change" }); return Created($"/api/dashboard/tasks/{task.Id}", MapToDto(task));
return Ok(new { status = "ok", model = request.Model });
} }
catch (Exception ex) catch (ArgumentException ex)
{ {
logger.LogWarning(ex, "SetAgentModel failed for {AgentId}", id); return BadRequest(new { error = ex.Message });
return StatusCode(500, new { error = "Internal error" });
} }
} }
[HttpPut("tasks/{id:guid}")]
public async Task<ActionResult<DashboardTaskDto>> UpdateTask(
Guid id, [FromBody] UpdateDashboardTaskRequest request, CancellationToken ct)
{
var result = await taskService.UpdateDashboardTaskAsync(
id, request.Title, request.Detail, request.Source, request.Priority, request.AssignedTo, request.DueDate, ct);
return result.Outcome switch
{
TaskOperationOutcome.NotFound => NotFound(new { error = "Task not found." }),
_ => Ok(MapToDto(result.Task!))
};
}
[HttpDelete("tasks/{id:guid}")]
public async Task<ActionResult> DeleteTask(Guid id, CancellationToken ct)
{
var result = await taskService.DeleteAsync(id, ct);
return result.Outcome switch
{
TaskOperationOutcome.NotFound => NotFound(new { error = "Task not found." }),
TaskOperationOutcome.InvalidState => StatusCode(403, new { error = "Only tasks in 'Done' or 'Backlog' state can be deleted." }),
_ => NoContent()
};
}
[HttpPatch("tasks/{id:guid}/status")]
public async Task<ActionResult<DashboardTaskDto>> UpdateTaskStatus(
Guid id, [FromBody] UpdateDashboardTaskStatusRequest request, CancellationToken ct)
{
// Enforce workflow rules based on caller agent
var currentTask = await taskService.GetByIdAsync(id, ct);
if (currentTask is null)
return NotFound(new { error = "Task not found." });
// Resolve caller agent from header or JWT
var callerAgent = ResolveCallerAgent();
// Nur Iris und Bao dürfen Status ändern
if (!TaskStateHelper.CanChangeState(callerAgent, currentTask))
{
return StatusCode(403, new { error = "Statusänderungen sind nur Iris und Bao vorbehalten. Sub-Agenten können Tasks nicht verschieben." });
}
var result = await taskService.UpdateStatusAsync(id, request.Status, ct);
return result.Outcome switch
{
TaskOperationOutcome.InvalidState => BadRequest(new { error = $"Unsupported status: '{request.Status}'. Valid: {string.Join(", ", TaskStateHelper.AllStates)}" }),
TaskOperationOutcome.NotFound => NotFound(new { error = "Task not found." }),
_ => Ok(MapToDto(result.Task!))
};
}
// ── Task Board Endpoints ──
[HttpGet("tasks/board")]
public async Task<BoardResponse> GetBoard(CancellationToken ct)
=> await taskService.GetBoardAsync(ct);
[HttpPatch("tasks/{id:guid}/move")]
public async Task<ActionResult<DashboardTaskDto>> MoveTask(
Guid id, [FromBody] MoveTaskRequest request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.State))
return BadRequest(new { error = "State is required." });
// Enforce workflow rules based on caller agent
var currentTask = await taskService.GetByIdAsync(id, ct);
if (currentTask is null)
return NotFound(new { error = "Task not found." });
// Resolve caller agent from header or JWT
var callerAgent = ResolveCallerAgent();
// Nur Iris und Bao dürfen Status ändern
if (!TaskStateHelper.CanChangeState(callerAgent, currentTask))
{
return StatusCode(403, new { error = "Statusänderungen sind nur Iris und Bao vorbehalten. Sub-Agenten können Tasks nicht verschieben." });
}
var result = await taskService.MoveTaskAsync(id, request.State, ct);
return result.Outcome switch
{
TaskOperationOutcome.InvalidState => BadRequest(new { error = $"Unsupported state: '{request.State}'. Valid: {string.Join(", ", TaskStateHelper.AllStates)}" }),
TaskOperationOutcome.NotFound => NotFound(new { error = "Task not found." }),
_ => Ok(MapToDto(result.Task!))
};
}
/// <summary> /// <summary>
/// Returns the list of available models that can be assigned to agents. /// Resolves the caller identity: checks X-Agent-Id header, then JWT name claim.
/// Falls back to empty string (which authorization helpers reject accordingly).
/// </summary> /// </summary>
[HttpGet("models")] private string ResolveCallerAgent()
public ActionResult<List<ModelOption>> GetAvailableModels()
{ {
var models = new List<ModelOption> var httpContext = httpContextAccessor.HttpContext;
if (httpContext is null) return "";
var agentHeader = httpContext.Request.Headers["X-Agent-Id"].FirstOrDefault();
if (!string.IsNullOrWhiteSpace(agentHeader))
return agentHeader.Trim().ToLowerInvariant();
var user = httpContext.User;
var nameClaim = user?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
return nameClaim?.ToLowerInvariant() ?? "";
}
// ── New Endpoints: Reset Stale, Children, Activity ──
[HttpPost("tasks/reset-stale")]
public async Task<ActionResult<ResetStaleResponse>> ResetStale(
[FromBody] ResetStaleRequest request, CancellationToken ct)
{ {
new ModelOption("openai/gpt-5.4", "GPT-5.4", "openai"), var threshold = TimeSpan.FromHours(Math.Max(1, request.StaleHours));
new ModelOption("deepseek/deepseek-v4-flash", "DeepSeek V4 Flash", "deepseek"), var count = await taskService.ResetStaleInProgressTasksAsync(threshold, ct);
new ModelOption("deepseek/deepseek-v4-pro", "DeepSeek V4 Pro", "deepseek") return Ok(new ResetStaleResponse(count));
}
[HttpGet("tasks/{id:guid}/children")]
public async Task<ActionResult<List<DashboardTaskDto>>> GetChildren(Guid id, CancellationToken ct)
{
var children = await taskService.GetChildTasksAsync(id, ct);
return Ok(children.Select(MapToDto).ToList());
}
[HttpGet("tasks/{id:guid}")]
public async Task<ActionResult<DashboardTaskDto>> GetTask(Guid id, CancellationToken ct)
{
var task = await taskService.GetDashboardTaskByIdAsync(id, ct);
if (task is null) return NotFound(new { error = "Task not found." });
return Ok(task);
}
[HttpGet("tasks/{id:guid}/activity")]
public async Task<ActionResult<List<ActivityEvent>>> GetTaskActivity(Guid id, CancellationToken ct)
{
var events = await taskService.GetTaskActivityAsync(id, ct);
return Ok(events);
}
[HttpPost("tasks/{id:guid}/activity")]
public async Task<ActionResult<ActivityEvent>> PostTaskActivity(
Guid id, [FromBody] PostActivityRequest request, CancellationToken ct)
{
var task = await taskService.GetByIdAsync(id, ct);
if (task is null) return NotFound(new { error = "Task not found." });
if (string.IsNullOrWhiteSpace(request.Message))
return BadRequest(new { error = "Message is required." });
var ev = new ActivityEvent
{
Type = request.Type ?? "comment",
Message = request.Message.Trim(),
TaskId = id
}; };
return Ok(models);
await activityService.AddAsync(ev, ct);
return Created($"/api/dashboard/tasks/{id}/activity/{ev.Id}", ev);
} }
// ========== Helpers ========== // ── Agent Workflow Endpoints (Iris Overview) ──
private static DateTimeOffset ParseTimestamp(string timestamp) /// <summary>
/// Returns agent-tasks that are still open and waiting for input.
/// Iris uses this to see who she is waiting for.
/// </summary>
[HttpGet("tasks/agent-waiting")]
public async Task<ActionResult<List<DashboardTaskDto>>> GetAgentWaitingTasks(CancellationToken ct)
{ {
if (DateTimeOffset.TryParse(timestamp, null, System.Globalization.DateTimeStyles.None, out var dt)) var waiting = await taskService.GetWaitingTasksAsync(ct);
return dt; return Ok(waiting.Select(MapToDto).ToList());
return DateTimeOffset.UtcNow;
} }
private static string FormatTimeAgo(DateTimeOffset ts) /// <summary>
/// Returns a complete agent-workflow overview grouped by expected respondent
/// + stale detection. This is the main Iris dashboard data.
/// </summary>
[HttpGet("tasks/agent-overview")]
public async Task<ActionResult<AgentWorkflowOverview>> GetAgentOverview(
CancellationToken ct, [FromQuery] int staleHours = 2)
{ {
var diff = DateTimeOffset.UtcNow - ts; var threshold = TimeSpan.FromHours(Math.Max(1, staleHours));
if (diff.TotalMinutes < 1) return "just now"; return Ok(await taskService.GetAgentWorkflowOverviewAsync(threshold, ct));
if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m ago";
if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h ago";
if (diff.TotalDays < 7) return $"{(int)diff.TotalDays}d ago";
return ts.ToString("MMM dd");
} }
private static (string Agent, string Action) ExtractAgentAction(string content) /// <summary>
/// Creates an agent-task: a task that is tracked as originating from the agent workflow.
/// Sub-agents (programmer, reviewer) can only CREATE, not move state.
/// </summary>
[HttpPost("tasks/agent")]
public async Task<ActionResult<DashboardTaskDto>> CreateAgentTask(
[FromBody] CreateAgentTaskRequest request, CancellationToken ct)
{ {
// Take first line or first ~80 chars as the action summary if (string.IsNullOrWhiteSpace(request.Title))
var firstLine = content.Split('\n', 2)[0].Trim(); return BadRequest(new { error = "Title is required." });
var summary = firstLine.Length > 80 ? firstLine[..80] + "…" : firstLine;
// Try to identify which agent this came from try
var agent = "Iris";
foreach (var marker in new[] { "**Agent:**", "**Agent:** ", "*Agent:* ", "Agent:" })
{ {
var idx = content.IndexOf(marker, StringComparison.OrdinalIgnoreCase); var task = await taskService.CreateAgentTaskAsync(
if (idx >= 0) request.Title, request.Detail, request.Source ?? "iris",
{ request.Priority, request.AssignedTo, request.ExpectedFrom,
var after = content[(idx + marker.Length)..].TrimStart(); request.ParentTaskId, ct);
var end = after.IndexOfAny(['\n', '\r', ',', '.']);
var found = end > 0 ? after[..end].Trim() : after.Split('\n', 2)[0].Trim(); return Created($"/api/dashboard/tasks/{task.Id}", MapToDto(task));
if (!string.IsNullOrWhiteSpace(found) && found.Length < 30)
{
agent = found;
break;
} }
catch (ArgumentException ex)
{
return BadRequest(new { error = ex.Message });
} }
} }
// Try to find agent name at the start in brackets like [Agent: Iris] private static DashboardTaskDto MapToDto(WorkTask t) => new(
if (agent == "Iris") t.Id, t.Title, t.Detail, t.Source, t.State, t.Priority, t.AssignedTo,
{ t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt,
var bracketMatch = System.Text.RegularExpressions.Regex.Match(content, @"\[Agent:\s*([^\]]+)\]"); t.IsAgentTask, t.ExpectedFrom);
if (bracketMatch.Success)
agent = bracketMatch.Groups[1].Value.Trim();
}
return (agent, summary);
}
} }
+5 -51
View File
@@ -1,47 +1,15 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Helpers; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/docs")] [Route("api/v1/docs")]
public class DocsController : ControllerBase public class DocsController(IDocService docService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public IResult GetAll() public IResult GetAll()
{ => Results.Ok(docService.GetAll());
var workspaceRoot = "/mnt/workspace-iris";
var results = new List<object>();
void ScanDir(string dir, string category)
{
if (!Directory.Exists(dir)) return;
foreach (var file in Directory.GetFiles(dir, "*.*"))
{
var ext = Path.GetExtension(file).ToLowerInvariant();
if (ext is not (".md" or ".json" or ".txt" or ".yaml" or ".yml" or ".html" or ".css"))
continue;
var fi = new FileInfo(file);
results.Add(new
{
name = fi.Name,
path = file.Replace(workspaceRoot, "").TrimStart('/'),
category,
type = ext.Replace(".", ""),
size = fi.Length,
modifiedAt = fi.LastWriteTimeUtc
});
}
}
ScanDir("/mnt/workspace-iris/nexus-phases", "phases");
ScanDir("/mnt/workspace-iris/skills", "skills");
ScanDir("/mnt/workspace-iris", "workspace");
ScanDir("/home/node/.openclaw/workspace/nexus", "nexus");
ScanDir("/home/node/.openclaw/workspace/nexus/phases", "nexus-phases");
return Results.Ok(results.OrderByDescending(x => ((DateTime)((dynamic)x).modifiedAt)).Take(100));
}
[HttpGet("{**path}")] [HttpGet("{**path}")]
public async Task<IResult> GetFile(string path) public async Task<IResult> GetFile(string path)
@@ -49,21 +17,7 @@ public class DocsController : ControllerBase
if (string.IsNullOrWhiteSpace(path)) if (string.IsNullOrWhiteSpace(path))
return Results.BadRequest("Path required."); return Results.BadRequest("Path required.");
string? resolvedPath = null; var file = await docService.GetFileAsync(path);
foreach (var root in new[] { "/mnt/workspace-iris", "/home/node/.openclaw/workspace/nexus" }) return file is null ? Results.NotFound() : Results.Ok(file);
{
if (PathSecurityHelper.TryResolveSafePath(root, path, out var candidate) && System.IO.File.Exists(candidate))
{
resolvedPath = candidate;
break;
}
}
if (resolvedPath is null)
return Results.NotFound();
var content = await System.IO.File.ReadAllTextAsync(resolvedPath);
var fi = new FileInfo(resolvedPath);
return Results.Ok(new { name = fi.Name, path = resolvedPath.Replace("/mnt/workspace-iris/", "").Replace("/home/node/.openclaw/workspace/nexus/", ""), content, size = fi.Length, modifiedAt = fi.LastWriteTimeUtc });
} }
} }
+8
View File
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks;
using Nexus.Api.Integrations; using Nexus.Api.Integrations;
@@ -7,6 +8,13 @@ namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
public class HealthController(IAgentRuntime runtime, HealthCheckService healthChecks) : ControllerBase public class HealthController(IAgentRuntime runtime, HealthCheckService healthChecks) : ControllerBase
{ {
[AllowAnonymous]
[HttpGet("/health/live")]
public IResult Live()
{
return Results.Ok(new { status = "Healthy", timestamp = DateTimeOffset.UtcNow });
}
[HttpGet("/health")] [HttpGet("/health")]
public async Task<IResult> Get(CancellationToken ct) public async Task<IResult> Get(CancellationToken ct)
{ {
+5 -85
View File
@@ -1,100 +1,20 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Helpers; using Nexus.Api.Services;
using System.Text.RegularExpressions;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/incidents")] [Route("api/v1/incidents")]
public class IncidentsController : ControllerBase public class IncidentsController(IIncidentService incidentService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public async Task<IResult> GetAll() public async Task<IResult> GetAll()
{ => Results.Ok(await incidentService.GetAllAsync());
var basePath = "/mnt/workspace-iris/memory/incidents";
if (!Directory.Exists(basePath))
return Results.Ok(Array.Empty<object>());
var incidents = new List<object>();
foreach (var file in Directory.GetFiles(basePath, "*.md").OrderByDescending(f => f).Take(50))
{
var fi = new FileInfo(file);
if (fi.Length > 1_000_000) continue;
var name = Path.GetFileNameWithoutExtension(file);
var content = await System.IO.File.ReadAllTextAsync(file);
var title = name;
var titleMatch = Regex.Match(content, @"^#\s+(.+)$", RegexOptions.Multiline);
if (titleMatch.Success)
title = titleMatch.Groups[1].Value.Trim();
var date = (string?)null;
var dateMatch = Regex.Match(name, @"^(\d{4}-\d{2}-\d{2})");
if (dateMatch.Success)
date = dateMatch.Groups[1].Value;
var severity = "unknown";
var severityMatch = Regex.Match(content, @"\*\*Severity:\*\*\s*(.+)$", RegexOptions.Multiline);
if (severityMatch.Success)
severity = severityMatch.Groups[1].Value.Trim();
var excerptEnd = content.IndexOf("\n## ", StringComparison.Ordinal);
var excerpt = excerptEnd > 0
? content[..excerptEnd].Trim()
: content[..Math.Min(300, content.Length)].Trim();
if (excerpt.Length > 200)
excerpt = excerpt[..200] + "\u2026";
incidents.Add(new
{
name = Path.GetFileName(file),
title,
date,
severity,
excerpt,
size = fi.Length
});
}
return Results.Ok(incidents);
}
[HttpGet("{name}")] [HttpGet("{name}")]
public async Task<IResult> GetOne(string name) public async Task<IResult> GetOne(string name)
{ {
var basePath = "/mnt/workspace-iris/memory/incidents"; var incident = await incidentService.GetByNameAsync(name);
if (!PathSecurityHelper.TryResolveSafePath(basePath, name, out var filePath)) return incident is null ? Results.NotFound() : Results.Ok(incident);
return Results.BadRequest("Invalid filename.");
if (!System.IO.File.Exists(filePath!))
{
if (!name.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
filePath = Path.Combine(basePath, name + ".md");
if (!System.IO.File.Exists(filePath!))
return Results.NotFound();
}
var content = await System.IO.File.ReadAllTextAsync(filePath!);
var fi = new FileInfo(filePath!);
var fileName = Path.GetFileName(filePath!);
var title = fileName;
var titleMatch = Regex.Match(content, @"^#\s+(.+)$", RegexOptions.Multiline);
if (titleMatch.Success)
title = titleMatch.Groups[1].Value.Trim();
var date = (string?)null;
var dateMatch = Regex.Match(fileName, @"^(\d{4}-\d{2}-\d{2})");
if (dateMatch.Success)
date = dateMatch.Groups[1].Value;
return Results.Ok(new
{
name = fileName,
title,
date,
content,
size = fi.Length
});
} }
} }
+7 -86
View File
@@ -1,40 +1,15 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Helpers; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/memory")] [Route("api/v1/memory")]
public class MemoryController : ControllerBase public class MemoryController(IMemoryService memoryService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public IResult GetAll() public async Task<IResult> GetAll()
{ => Results.Ok(await memoryService.GetAllAsync());
var basePath = "/mnt/workspace-iris/memory";
if (!Directory.Exists(basePath))
return Results.Ok(Array.Empty<object>());
var files = Directory.GetFiles(basePath, "*.md")
.Select(f => new FileInfo(f))
.OrderByDescending(f => f.Name)
.Select(f => new
{
name = f.Name,
path = f.FullName.Replace(basePath, "").TrimStart('/'),
size = f.Length,
modifiedAt = f.LastWriteTimeUtc
})
.ToList();
var longTermPath = "/mnt/workspace-iris/MEMORY.md";
if (System.IO.File.Exists(longTermPath))
{
var fi = new FileInfo(longTermPath);
files.Insert(0, new { name = "MEMORY.md", path = "MEMORY.md", size = fi.Length, modifiedAt = fi.LastWriteTimeUtc });
}
return Results.Ok(files);
}
[HttpGet("search")] [HttpGet("search")]
public async Task<IResult> Search([FromQuery] string q) public async Task<IResult> Search([FromQuery] string q)
@@ -42,67 +17,13 @@ public class MemoryController : ControllerBase
if (string.IsNullOrWhiteSpace(q) || q.Length < 2) if (string.IsNullOrWhiteSpace(q) || q.Length < 2)
return Results.BadRequest("Query must be at least 2 characters."); return Results.BadRequest("Query must be at least 2 characters.");
var basePath = "/mnt/workspace-iris/memory"; return Results.Ok(await memoryService.SearchAsync(q));
var results = new List<object>();
const int maxFiles = 50;
const int maxFileSize = 1_000_000;
async Task SearchDir(string dir)
{
if (!Directory.Exists(dir)) return;
var files = Directory.GetFiles(dir, "*.md").Take(maxFiles);
foreach (var file in files)
{
var fi = new FileInfo(file);
if (fi.Length > maxFileSize) continue;
string content;
using (var reader = new StreamReader(file))
content = await reader.ReadToEndAsync();
if (content.Contains(q, StringComparison.OrdinalIgnoreCase))
{
var idx = content.IndexOf(q, StringComparison.OrdinalIgnoreCase);
var start = Math.Max(0, idx - 60);
var excerpt = (start > 0 ? "\u2026" : "") + content.Substring(start, Math.Min(200, content.Length - start)) + "\u2026";
results.Add(new { name = Path.GetFileName(file), path = file.Replace(basePath, "").TrimStart('/'), excerpt, size = fi.Length });
}
}
}
await SearchDir(basePath);
var longTermPath = "/mnt/workspace-iris/MEMORY.md";
if (System.IO.File.Exists(longTermPath))
{
string content;
using (var reader = new StreamReader(longTermPath))
content = await reader.ReadToEndAsync();
if (content.Contains(q, StringComparison.OrdinalIgnoreCase))
{
var idx = content.IndexOf(q, StringComparison.OrdinalIgnoreCase);
var start = Math.Max(0, idx - 60);
var excerpt = (start > 0 ? "\u2026" : "") + content.Substring(start, Math.Min(200, content.Length - start)) + "\u2026";
results.Insert(0, new { name = "MEMORY.md", path = "MEMORY.md", excerpt, size = content.Length });
}
}
return Results.Ok(results);
} }
[HttpGet("{name}")] [HttpGet("{name}")]
public async Task<IResult> GetFile(string name) public async Task<IResult> GetFile(string name)
{ {
if (!PathSecurityHelper.TryResolveSafePath("/mnt/workspace-iris/memory", name, out var filePath)) var file = await memoryService.GetFileAsync(name);
return Results.BadRequest("Invalid filename."); return file is null ? Results.NotFound() : Results.Ok(file);
var longTermPath = "/mnt/workspace-iris/MEMORY.md";
if (name.Equals("MEMORY.md", StringComparison.OrdinalIgnoreCase))
filePath = longTermPath;
if (!System.IO.File.Exists(filePath!))
return Results.NotFound();
var content = await System.IO.File.ReadAllTextAsync(filePath!);
return Results.Ok(new { name, path = name, content, size = content.Length, modifiedAt = System.IO.File.GetLastWriteTimeUtc(filePath!) });
} }
} }
@@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Data;
using Nexus.Api.Models;
using Nexus.Api.Services;
namespace Nexus.Api.Controllers;
[Authorize]
[ApiController]
[Route("api/dashboard/notifications")]
public class NotificationsController(INotificationService notificationService) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<List<NotificationDto>>> GetNotifications(
[FromQuery] string forUser = "bao",
[FromQuery] int limit = 50,
[FromQuery] bool unreadOnly = false,
CancellationToken ct = default)
{
var notifications = await notificationService.GetForUserAsync(forUser, limit, unreadOnly, ct);
return Ok(notifications.Select(MapToDto).ToList());
}
[HttpGet("unread-count")]
public async Task<ActionResult<UnreadCountDto>> GetUnreadCount(
[FromQuery] string forUser = "bao",
CancellationToken ct = default)
{
var count = await notificationService.GetUnreadCountAsync(forUser, ct);
return Ok(new UnreadCountDto(count));
}
[HttpPatch("{id:guid}/read")]
public async Task<ActionResult> MarkAsRead(Guid id, CancellationToken ct = default)
{
var ok = await notificationService.MarkAsReadAsync(id, ct);
return ok ? NoContent() : NotFound(new { error = "Notification not found." });
}
[HttpPatch("read-all")]
public async Task<ActionResult> MarkAllAsRead(
[FromQuery] string forUser = "bao",
CancellationToken ct = default)
{
var count = await notificationService.MarkAllAsReadAsync(forUser, ct);
return Ok(new { marked = count });
}
private static NotificationDto MapToDto(Notification n) => new(
n.Id, n.Type, n.Title, n.Message,
n.ForUser, n.TaskId, n.IsRead, n.CreatedAt);
}
+4 -60
View File
@@ -1,71 +1,15 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Data;
using Nexus.Api.Integrations;
using Nexus.Api.Repositories;
using Nexus.Api.Services; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/operations")] [Route("api/v1/operations")]
public class OperationsController( public class OperationsController(IOperationsService operationsService) : ControllerBase
IAgentRuntime runtime,
IAgentService agentService,
IProjectRepository projectRepo,
ITaskRepository taskRepo,
IActivityRepository activityRepo) : ControllerBase
{ {
[HttpGet("snapshot")] [HttpGet("snapshot")]
[Authorize]
public async Task<IResult> GetSnapshot(CancellationToken ct) public async Task<IResult> GetSnapshot(CancellationToken ct)
{ => Results.Ok(await operationsService.GetSnapshotAsync(ct));
var runtimeTask = runtime.GetStatusAsync(ct);
var agentsTask = agentService.GetAgentsAsync(ct);
var projectsTask = projectRepo.GetAllAsync(ct);
var tasksTask = taskRepo.GetAllAsync(ct);
var activityTask = activityRepo.GetRecentAsync(20, ct);
await Task.WhenAll(runtimeTask, agentsTask, projectsTask, tasksTask, activityTask);
var tasks = tasksTask.Result;
var projects = projectsTask.Result;
var agents = agentsTask.Result;
var completedTasks = tasks.Count(x => x.State == TaskStateHelper.ToStateString(TaskState.Done));
var runtimeStatus = runtimeTask.Result;
var runtimeHealthy = runtimeStatus.Status == OperationalStatus.Online;
var lastIncident = tasks
.Where(x => x.State == TaskStateHelper.ToStateString(TaskState.Blocked))
.OrderByDescending(x => x.UpdatedAt)
.Select(x => new { TaskId = (Guid?)x.Id, Title = (string?)x.Title, Since = (DateTimeOffset?)x.UpdatedAt })
.FirstOrDefault();
var projectHealth = new
{
Online = projects.Count(x => x.Status == OperationalStatus.Online),
Offline = projects.Count(x => x.Status == OperationalStatus.Offline),
Degraded = projects.Count(x => x.Status == OperationalStatus.Degraded),
Unknown = projects.Count(x => x.Status == OperationalStatus.Unknown)
};
return Results.Ok(new
{
generatedAt = DateTimeOffset.UtcNow,
runtime = runtimeStatus,
models = Array.Empty<object>(),
runtimeHealthy,
metrics = new
{
activeAgents = agents.Count,
queuedTasks = tasks.Count - completedTasks,
successRate = tasks.Count == 0 ? 100 : Math.Round(completedTasks * 100d / tasks.Count, 1),
incidents = tasks.Count(x => x.State == TaskStateHelper.ToStateString(TaskState.Blocked))
},
lastIncident,
projectHealth,
agents = agents.Select(x => new { x.Id, x.Name, x.Role, x.Status, x.Model }),
projects = projects.Select(x => new { x.Id, x.Name, x.Status, x.Progress, x.UpdatedAt }),
tasks = tasks.Select(x => new { x.Id, x.Title, x.State, x.Priority, x.ProjectId, x.UpdatedAt }),
activity = activityTask.Result.Select(x => new { x.Id, x.Type, x.Message, at = x.CreatedAt })
});
}
} }
+19 -46
View File
@@ -1,17 +1,23 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Data;
using Nexus.Api.DTOs; using Nexus.Api.DTOs;
using Nexus.Api.Repositories; using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/projects")] [Route("api/v1/projects")]
public class ProjectsController(IProjectRepository projectRepo, IActivityRepository activityRepo) : ControllerBase public class ProjectsController(IProjectService projectService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public async Task<IResult> GetAll(CancellationToken ct) public async Task<IResult> GetAll(CancellationToken ct)
=> Results.Ok(await projectRepo.GetAllAsync(ct)); => Results.Ok(await projectService.GetAllAsync(ct));
[HttpGet("{id:guid}")]
public async Task<IResult> GetById(Guid id, CancellationToken ct)
{
var project = await projectService.GetByIdAsync(id, ct);
return project is null ? Results.NotFound() : Results.Ok(project);
}
[HttpPost] [HttpPost]
public async Task<IResult> Create([FromBody] CreateProjectRequest request, CancellationToken ct) public async Task<IResult> Create([FromBody] CreateProjectRequest request, CancellationToken ct)
@@ -19,59 +25,26 @@ public class ProjectsController(IProjectRepository projectRepo, IActivityReposit
if (string.IsNullOrWhiteSpace(request.Name)) if (string.IsNullOrWhiteSpace(request.Name))
return Results.ValidationProblem(new Dictionary<string, string[]> { ["name"] = ["Name is required."] }); return Results.ValidationProblem(new Dictionary<string, string[]> { ["name"] = ["Name is required."] });
var project = new Project var project = await projectService.CreateAsync(request, ct);
{
Name = request.Name.Trim(),
Description = request.Description?.Trim() ?? string.Empty,
Status = OperationalStatus.Online
};
await projectRepo.AddAsync(project, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} created" }, ct);
return Results.Created($"/api/v1/projects/{project.Id}", project); return Results.Created($"/api/v1/projects/{project.Id}", project);
} }
[HttpGet("{id:guid}")]
public async Task<IResult> GetById(Guid id, CancellationToken ct)
{
var project = await projectRepo.GetByIdAsync(id, ct);
return project is null ? Results.NotFound() : Results.Ok(project);
}
[HttpPatch("{id:guid}")] [HttpPatch("{id:guid}")]
public async Task<IResult> Update(Guid id, [FromBody] UpdateProjectRequest request, CancellationToken ct) public async Task<IResult> Update(Guid id, [FromBody] UpdateProjectRequest request, CancellationToken ct)
{ {
var project = await projectRepo.GetByIdAsync(id, ct); var project = await projectService.UpdateAsync(id, request, ct);
if (project is null) return Results.NotFound(); return project is null ? Results.NotFound() : Results.Ok(project);
if (!string.IsNullOrWhiteSpace(request.Name))
project.Name = request.Name.Trim();
if (request.Description is not null)
project.Description = request.Description.Trim();
if (!string.IsNullOrWhiteSpace(request.Status) && Enum.TryParse<OperationalStatus>(request.Status, true, out var parsedStatus))
project.Status = parsedStatus;
await projectRepo.UpdateAsync(project, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} updated" }, ct);
return Results.Ok(project);
} }
[HttpDelete("{id:guid}")] [HttpDelete("{id:guid}")]
public async Task<IResult> Delete(Guid id, CancellationToken ct) public async Task<IResult> Delete(Guid id, CancellationToken ct)
{ {
var project = await projectRepo.GetByIdAsync(id, ct); var result = await projectService.DeleteAsync(id, ct);
if (project is null) return Results.NotFound(); return result.Outcome switch
var hasTasks = await projectRepo.HasTasksAsync(id, ct);
if (hasTasks)
{ {
project.Status = OperationalStatus.Offline; ProjectDeleteOutcome.NotFound => Results.NotFound(),
await projectRepo.UpdateAsync(project, ct); ProjectDeleteOutcome.Archived => Results.Ok(result.Project),
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} archived" }, ct); _ => Results.NoContent()
return Results.Ok(project); };
}
await projectRepo.DeleteAsync(project, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} deleted" }, ct);
return Results.NoContent();
} }
} }
+75 -69
View File
@@ -1,17 +1,19 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Data; using Nexus.Api.Data;
using Nexus.Api.DTOs; using Nexus.Api.DTOs;
using Nexus.Api.Repositories; using Nexus.Api.Models;
using Nexus.Api.Services;
namespace Nexus.Api.Controllers; namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/tasks")] [Route("api/v1/tasks")]
public class TasksController(ITaskRepository taskRepo, IActivityRepository activityRepo) : ControllerBase public class TasksController(ITaskService taskService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public async Task<IResult> GetAll(CancellationToken ct) public async Task<IResult> GetAll(CancellationToken ct)
=> Results.Ok(await taskRepo.GetAllAsync(ct)); => Results.Ok(await taskService.GetAllAsync(ct));
[HttpPost] [HttpPost]
public async Task<IResult> Create([FromBody] CreateTaskRequest request, CancellationToken ct) public async Task<IResult> Create([FromBody] CreateTaskRequest request, CancellationToken ct)
@@ -19,107 +21,111 @@ public class TasksController(ITaskRepository taskRepo, IActivityRepository activ
if (string.IsNullOrWhiteSpace(request.Title)) if (string.IsNullOrWhiteSpace(request.Title))
return Results.ValidationProblem(new Dictionary<string, string[]> { ["title"] = ["Title is required."] }); return Results.ValidationProblem(new Dictionary<string, string[]> { ["title"] = ["Title is required."] });
var task = new WorkTask var task = await taskService.CreateAsync(request, ct);
{
Title = request.Title.Trim(),
Priority = string.IsNullOrWhiteSpace(request.Priority) ? "Normal" : request.Priority.Trim(),
ProjectId = request.ProjectId
};
await taskRepo.AddAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} created" }, ct);
return Results.Created($"/api/v1/tasks/{task.Id}", task); return Results.Created($"/api/v1/tasks/{task.Id}", task);
} }
[HttpGet("pending-approval")] [HttpGet("pending-approval")]
public async Task<IResult> GetPendingApproval(CancellationToken ct) public async Task<IResult> GetPendingApproval(CancellationToken ct)
{ {
var pending = await taskRepo.GetPendingApprovalAsync(ct); var pending = await taskService.GetPendingApprovalAsync(ct);
return Results.Ok(pending.Select(x => new { x.Id, x.Title, x.State, x.Priority, x.ProjectId, x.UpdatedAt })); return Results.Ok(pending.Select(x => new { x.Id, x.Title, x.State, x.Priority, x.ProjectId, x.UpdatedAt }));
} }
[HttpPost("{id:guid}/approve")] [HttpPost("{id:guid}/approve")]
public async Task<IResult> Approve(Guid id, CancellationToken ct) public async Task<IResult> Approve(Guid id, CancellationToken ct)
{ {
var task = await taskRepo.GetByIdAsync(id, ct); var result = await taskService.ApproveAsync(id, ct);
if (task is null) return Results.NotFound(); return result.Outcome switch
{
if (!TaskStateHelper.IsInProgressOrBlocked(task.State)) TaskOperationOutcome.NotFound => Results.NotFound(),
return Results.Problem( TaskOperationOutcome.InvalidState => Results.Problem(
title: "Approval denied", title: "Approval denied",
detail: "Only tasks in 'In progress' or 'Blocked' state can be approved.", detail: "Only tasks in 'In progress' or 'Blocked' state can be approved.",
statusCode: StatusCodes.Status403Forbidden); statusCode: StatusCodes.Status403Forbidden),
_ => Results.Ok(result.Task)
task.State = TaskStateHelper.ToStateString(TaskState.Done); };
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} approved" }, ct);
return Results.Ok(task);
} }
[HttpPost("{id:guid}/reject")] [HttpPost("{id:guid}/reject")]
public async Task<IResult> Reject(Guid id, CancellationToken ct) public async Task<IResult> Reject(Guid id, CancellationToken ct)
{ {
var task = await taskRepo.GetByIdAsync(id, ct); var result = await taskService.RejectAsync(id, ct);
if (task is null) return Results.NotFound(); return result.Outcome switch
{
if (!TaskStateHelper.IsInProgressOrBlocked(task.State)) TaskOperationOutcome.NotFound => Results.NotFound(),
return Results.Problem( TaskOperationOutcome.InvalidState => Results.Problem(
title: "Rejection denied", title: "Rejection denied",
detail: "Only tasks in 'In progress' or 'Blocked' state can be rejected.", detail: "Only tasks in 'In progress' or 'Blocked' state can be rejected.",
statusCode: StatusCodes.Status403Forbidden); statusCode: StatusCodes.Status403Forbidden),
_ => Results.Ok(result.Task)
task.State = TaskStateHelper.ToStateString(TaskState.Backlog); };
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} rejected, returned to backlog" }, ct);
return Results.Ok(task);
} }
[HttpPatch("{id:guid}/state")] [HttpPatch("{id:guid}/state")]
public async Task<IResult> UpdateState(Guid id, [FromBody] UpdateTaskStateRequest request, CancellationToken ct) public async Task<IResult> UpdateState(Guid id, [FromBody] UpdateTaskStateRequest request, CancellationToken ct)
{ {
var allowedStates = TaskStateHelper.AllStates; if (!TaskStateHelper.IsValidState(request.State))
if (!allowedStates.Contains(request.State, StringComparer.OrdinalIgnoreCase))
return Results.ValidationProblem(new Dictionary<string, string[]> { ["state"] = ["Unsupported task state."] }); return Results.ValidationProblem(new Dictionary<string, string[]> { ["state"] = ["Unsupported task state."] });
var task = await taskRepo.GetByIdAsync(id, ct); var result = await taskService.UpdateStateAsync(id, request.State, ct);
if (task is null) return Results.NotFound(); return result.Outcome switch
task.State = allowedStates.First(x => x.Equals(request.State, StringComparison.OrdinalIgnoreCase));
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} moved to {task.State}" }, ct);
return Results.Ok(task);
}
[HttpDelete("{id:guid}")]
public async Task<IResult> Delete(Guid id, CancellationToken ct)
{ {
var task = await taskRepo.GetByIdAsync(id, ct); TaskOperationOutcome.NotFound => Results.NotFound(),
if (task is null) return Results.NotFound(); TaskOperationOutcome.InvalidState => Results.Problem(
title: "Action denied",
if (!TaskStateHelper.IsDoneOrBacklog(task.State)) detail: "Statusänderungen sind nur Iris und Bao vorbehalten. Sub-Agenten können Tasks nicht verschieben.",
return Results.Problem( statusCode: StatusCodes.Status403Forbidden),
title: "Task deletion denied", _ => Results.Ok(result.Task)
detail: "Only tasks in 'Done' or 'Backlog' state can be deleted.", };
statusCode: StatusCodes.Status403Forbidden);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} deleted" }, ct);
await taskRepo.DeleteAsync(task, ct);
return Results.NoContent();
} }
[HttpPatch("{id:guid}")] [HttpPatch("{id:guid}")]
public async Task<IResult> Update(Guid id, [FromBody] UpdateTaskRequest request, CancellationToken ct) public async Task<IResult> Update(Guid id, [FromBody] UpdateTaskRequest request, CancellationToken ct)
{ {
var task = await taskRepo.GetByIdAsync(id, ct); var result = await taskService.UpdateAsync(id, request, ct);
if (task is null) return Results.NotFound(); return result.Outcome switch
{
TaskOperationOutcome.NotFound => Results.NotFound(),
_ => Results.Ok(result.Task)
};
}
if (!string.IsNullOrWhiteSpace(request.Title)) [HttpDelete("{id:guid}")]
task.Title = request.Title.Trim(); public async Task<IResult> Delete(Guid id, CancellationToken ct)
if (!string.IsNullOrWhiteSpace(request.Priority)) {
task.Priority = request.Priority.Trim(); var result = await taskService.DeleteAsync(id, ct);
if (request.ProjectId.HasValue) return result.Outcome switch
task.ProjectId = request.ProjectId.Value == Guid.Empty ? null : request.ProjectId; {
TaskOperationOutcome.NotFound => Results.NotFound(),
TaskOperationOutcome.InvalidState => Results.Problem(
title: "Task deletion denied",
detail: "Only tasks in 'Done' or 'Backlog' state can be deleted.",
statusCode: StatusCodes.Status403Forbidden),
_ => Results.NoContent()
};
}
await taskRepo.UpdateAsync(task, ct); // ── Board & Stale-Reset (für Iris Autonomous Worker) ──
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} updated" }, ct);
return Results.Ok(task); /// <summary>
/// Gibt das Task-Board zurück (gruppiert nach Status, priorisiert sortiert).
/// Wird vom Iris Autonomous Worker genutzt.
/// </summary>
[AllowAnonymous]
[HttpGet("board")]
public async Task<IResult> GetBoard(CancellationToken ct)
=> Results.Ok(await taskService.GetBoardAsync(ct));
/// <summary>
/// Setzt stale Tasks (InProgress/Delegated, älter als N Stunden) zurück auf Backlog.
/// Wird vom Iris Autonomous Worker genutzt.
/// </summary>
[AllowAnonymous]
[HttpPost("reset-stale")]
public async Task<IResult> ResetStale([FromBody] ResetStaleRequest request, CancellationToken ct)
{
var count = await taskService.ResetStaleAsync(request.StaleHours, ct);
return Results.Ok(new ResetStaleResponse(count));
} }
} }
+2 -29
View File
@@ -5,36 +5,9 @@ namespace Nexus.Api.Controllers;
[ApiController] [ApiController]
[Route("api/v1/team")] [Route("api/v1/team")]
public class TeamController(IAgentService agentService) : ControllerBase public class TeamController(ITeamService teamService) : ControllerBase
{ {
[HttpGet] [HttpGet]
public async Task<IResult> GetTeam(CancellationToken ct) public async Task<IResult> GetTeam(CancellationToken ct)
{ => Results.Ok(await teamService.GetTeamAsync(ct));
var agents = await agentService.GetAgentsAsync(ct);
var team = new List<object>();
foreach (var agent in agents)
{
string identity = "";
string workspace = agent.Workspace ?? "";
if (!string.IsNullOrWhiteSpace(workspace) && Directory.Exists(workspace))
{
var identityFile = Path.Combine(workspace, "IDENTITY.md");
if (System.IO.File.Exists(identityFile))
{
var content = await System.IO.File.ReadAllTextAsync(identityFile, ct);
var lines = content.Split('\n').Where(l => l.StartsWith("- **")).Take(8);
identity = string.Join("\n", lines);
}
}
team.Add(new
{
agent.Id, agent.Name, agent.Role, agent.Model, agent.Status, agent.LastSeen, agent.Workspace, agent.Description,
identity
});
}
return Results.Ok(team);
}
} }
+23
View File
@@ -26,6 +26,29 @@ public sealed record UserInfo
public string Role { get; init; } = string.Empty; public string Role { get; init; } = string.Empty;
} }
public sealed record AdminUserInfo
{
public Guid Id { get; init; }
public string Email { get; init; } = string.Empty;
public string DisplayName { get; init; } = string.Empty;
public string Role { get; init; } = string.Empty;
public DateTimeOffset CreatedAt { get; init; }
public DateTimeOffset? LastLoginAt { get; init; }
}
public sealed record AdminCreateUserRequest
{
public string Email { get; init; } = string.Empty;
public string Password { get; init; } = string.Empty;
public string? DisplayName { get; init; }
public string? Role { get; init; }
}
public sealed record AdminUpdateRoleRequest
{
public string Role { get; init; } = string.Empty;
}
public sealed record UpdateProfileRequest public sealed record UpdateProfileRequest
{ {
[MaxLength(100)] [MaxLength(100)]
+1
View File
@@ -12,3 +12,4 @@ public sealed record IncidentInfoDto(
string? Title, string? Title,
DateTimeOffset? Since DateTimeOffset? Since
); );
+130 -4
View File
@@ -18,8 +18,10 @@ public enum TaskState
{ {
Backlog, Backlog,
InProgress, InProgress,
Delegated,
Blocked, Blocked,
Done Done,
Review
} }
public static class TaskStateHelper public static class TaskStateHelper
@@ -28,20 +30,35 @@ public static class TaskStateHelper
{ {
[TaskState.Backlog] = "Backlog", [TaskState.Backlog] = "Backlog",
[TaskState.InProgress] = "In progress", [TaskState.InProgress] = "In progress",
[TaskState.Delegated] = "Delegated",
[TaskState.Blocked] = "Blocked", [TaskState.Blocked] = "Blocked",
[TaskState.Done] = "Done" [TaskState.Done] = "Done",
[TaskState.Review] = "Review"
}; };
private static readonly Dictionary<string, TaskState> StringToState = new(StringComparer.OrdinalIgnoreCase) private static readonly Dictionary<string, TaskState> StringToState = new(StringComparer.OrdinalIgnoreCase)
{ {
["Backlog"] = TaskState.Backlog, ["Backlog"] = TaskState.Backlog,
["In progress"] = TaskState.InProgress, ["In progress"] = TaskState.InProgress,
["Delegated"] = TaskState.Delegated,
["Blocked"] = TaskState.Blocked, ["Blocked"] = TaskState.Blocked,
["Done"] = TaskState.Done ["Done"] = TaskState.Done,
["Review"] = TaskState.Review
};
/// <summary>Mapping from state string to display label.</summary>
private static readonly Dictionary<string, string> DisplayLabels = new(StringComparer.OrdinalIgnoreCase)
{
["Backlog"] = "Offen",
["In progress"] = "In Bearbeitung",
["Delegated"] = "Delegiert",
["Review"] = "Review",
["Blocked"] = "Blockiert",
["Done"] = "Erledigt"
}; };
/// <summary>Valid task-state string values for API validation.</summary> /// <summary>Valid task-state string values for API validation.</summary>
public static readonly string[] AllStates = ["Backlog", "In progress", "Blocked", "Done"]; public static readonly string[] AllStates = ["Backlog", "In progress", "Delegated", "Blocked", "Done", "Review"];
/// <summary>Convert a TaskState enum to its API string representation.</summary> /// <summary>Convert a TaskState enum to its API string representation.</summary>
public static string ToStateString(this TaskState state) => StateToString[state]; public static string ToStateString(this TaskState state) => StateToString[state];
@@ -54,6 +71,10 @@ public static class TaskStateHelper
public static bool IsValidState(string? state) => public static bool IsValidState(string? state) =>
!string.IsNullOrWhiteSpace(state) && StringToState.ContainsKey(state); !string.IsNullOrWhiteSpace(state) && StringToState.ContainsKey(state);
/// <summary>Returns the German display label for a state string.</summary>
public static string ToDisplayString(string? state) =>
state is not null && DisplayLabels.TryGetValue(state, out var label) ? label : state ?? "";
public static bool IsInProgressOrBlocked(string? state) => public static bool IsInProgressOrBlocked(string? state) =>
string.Equals(state, "In progress", StringComparison.OrdinalIgnoreCase) string.Equals(state, "In progress", StringComparison.OrdinalIgnoreCase)
|| string.Equals(state, "Blocked", StringComparison.OrdinalIgnoreCase); || string.Equals(state, "Blocked", StringComparison.OrdinalIgnoreCase);
@@ -61,6 +82,77 @@ public static class TaskStateHelper
public static bool IsDoneOrBacklog(string? state) => public static bool IsDoneOrBacklog(string? state) =>
string.Equals(state, "Done", StringComparison.OrdinalIgnoreCase) string.Equals(state, "Done", StringComparison.OrdinalIgnoreCase)
|| string.Equals(state, "Backlog", StringComparison.OrdinalIgnoreCase); || string.Equals(state, "Backlog", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Returns true if the caller is allowed to change this task's state.
/// POLICY:
/// - **Iris und Bao** dürfen Status ändern / verschieben.
/// - Sub-agents (programmer, reviewer, architekt) dürfen NIEMALS Status ändern.
/// - 'nexus-system' ist ein technischer Fallback für automatische Cron/Reset-Workflows.
/// - Jeder andere (unbekannt, leer) wird abgewiesen.
/// </summary>
public static bool CanChangeState(string? callerAgent, WorkTask task)
{
var caller = callerAgent?.Trim().ToLowerInvariant() ?? "";
// Sub-agents must never move state
var subAgents = new HashSet<string> { "programmer", "reviewer", "architekt" };
if (subAgents.Contains(caller)) return false;
// Technischer Fallback: nur für interne System-Operationen (Cron, ResetStale)
if (caller == "nexus-system") return true;
// Iris und Bao dürfen Status ändern
return caller == "iris" || caller == "bao";
}
/// <summary>
/// Returns true if the caller is allowed to edit a task's content fields
/// (title, detail, priority, assignedTo, dueDate).
/// POLICY:
/// - Alle (iris, bao, sub-agents, nexus-system) dürfen inhaltlich bearbeiten.
/// - Nur unbekannte/leere Caller werden abgewiesen.
/// </summary>
public static bool CanEditContent(string? callerAgent)
{
var caller = callerAgent?.Trim().ToLowerInvariant() ?? "";
if (string.IsNullOrWhiteSpace(caller)) return false;
return true;
}
/// <summary>Group key for board responses (lowercased English state).</summary>
public static string BoardGroupKey(string? state)
{
if (string.IsNullOrWhiteSpace(state)) return "offen";
var lower = state.ToLowerInvariant();
return lower switch
{
"backlog" => "offen",
"in progress" => "inProgress",
"delegated" => "delegated",
"review" => "review",
"blocked" => "blocked",
"done" => "done",
_ => "offen"
};
}
/// <summary>Map a board group key back to the canonical state string.</summary>
public static string? BoardGroupToState(string? groupKey)
{
if (string.IsNullOrWhiteSpace(groupKey)) return null;
var lower = groupKey.ToLowerInvariant();
return lower switch
{
"offen" => "Backlog",
"inprogress" => "In progress",
"delegated" => "Delegated",
"review" => "Review",
"blocked" => "Blocked",
"done" => "Done",
_ => null
};
}
} }
public sealed class Project public sealed class Project
@@ -77,16 +169,50 @@ public sealed class WorkTask
{ {
public Guid Id { get; init; } = Guid.NewGuid(); public Guid Id { get; init; } = Guid.NewGuid();
public required string Title { get; set; } public required string Title { get; set; }
public string? Detail { get; set; }
public string State { get; set; } = "Backlog"; public string State { get; set; } = "Backlog";
public string Priority { get; set; } = "Normal"; public string Priority { get; set; } = "Normal";
public string Source { get; set; } = "bao";
public string? AssignedTo { get; set; }
/// <summary>
/// True if this task was created programmatically by an agent (not manually by Bao).
/// Agent-tasks in the board are subject to stricter workflow rules.
/// </summary>
public bool IsAgentTask { get; set; } = false;
/// <summary>
/// Which agent/user is expected to respond next.
/// Helps Iris see who she is waiting for.
/// </summary>
public string? ExpectedFrom { get; set; }
public Guid? ParentTaskId { get; set; }
public WorkTask? ParentTask { get; set; }
public ICollection<WorkTask> ChildTasks { get; set; } = new List<WorkTask>();
public Guid? ProjectId { get; set; } public Guid? ProjectId { get; set; }
public DateTimeOffset? DueDate { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
} }
public sealed class Notification
{
public Guid Id { get; init; } = Guid.NewGuid();
public required string Type { get; set; } // "task_assigned", "task_review", "task_blocked"
public required string Title { get; set; } // "Neue Aufgabe: Memory-Index reparieren"
public string? Message { get; set; } // Detailtext
public required string ForUser { get; set; } // "bao" oder "iris"
public Guid? TaskId { get; set; } // Verknüpfte Task
public bool IsRead { get; set; } = false;
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public sealed class ActivityEvent public sealed class ActivityEvent
{ {
public long Id { get; init; } public long Id { get; init; }
public required string Type { get; set; } public required string Type { get; set; }
public required string Message { get; set; } public required string Message { get; set; }
public Guid? TaskId { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
} }
+15
View File
@@ -1,4 +1,5 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Nexus.Api.Data; namespace Nexus.Api.Data;
@@ -28,6 +29,20 @@ public class NexusUser
public ICollection<RefreshToken> RefreshTokens { get; set; } = new List<RefreshToken>(); public ICollection<RefreshToken> RefreshTokens { get; set; } = new List<RefreshToken>();
} }
/// <summary>
/// Tracks one-time seed operations so they are never re-executed — even
/// if the underlying data is deleted. This is the single guard that
/// prevents owner-password drift after DB resets or volume recreations.
/// </summary>
public class SeedAudit
{
[Key]
[MaxLength(80)]
public string Key { get; set; } = string.Empty;
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public class RefreshToken public class RefreshToken
{ {
public Guid Id { get; set; } = Guid.NewGuid(); public Guid Id { get; set; } = Guid.NewGuid();
@@ -0,0 +1,240 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Nexus.Api.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Nexus.Api.Migrations
{
[DbContext(typeof(NexusDbContext))]
[Migration("20260611154800_AddTaskDetailFields")]
partial class AddTaskDetailFields
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Nexus.Api.Data.ActivityEvent", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Activity");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("Nexus.Api.Data.Project", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<int>("Progress")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FamilyId")
.HasColumnType("uuid");
b.Property<string>("ReplacedByTokenHash")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId", "FamilyId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssignedTo")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<string>("Priority")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ProjectId")
.HasColumnType("uuid");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssignedTo");
b.HasIndex("Source");
b.ToTable("Tasks");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.HasOne("Nexus.Api.Data.NexusUser", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,81 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddTaskDetailFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "AssignedTo",
table: "Tasks",
type: "character varying(60)",
maxLength: 60,
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "CreatedAt",
table: "Tasks",
type: "timestamp with time zone",
nullable: false,
defaultValueSql: "NOW()");
migrationBuilder.AddColumn<string>(
name: "Detail",
table: "Tasks",
type: "character varying(2000)",
maxLength: 2000,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Source",
table: "Tasks",
type: "character varying(60)",
maxLength: 60,
nullable: false,
defaultValue: "bao");
migrationBuilder.CreateIndex(
name: "IX_Tasks_AssignedTo",
table: "Tasks",
column: "AssignedTo");
migrationBuilder.CreateIndex(
name: "IX_Tasks_Source",
table: "Tasks",
column: "Source");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tasks_AssignedTo",
table: "Tasks");
migrationBuilder.DropIndex(
name: "IX_Tasks_Source",
table: "Tasks");
migrationBuilder.DropColumn(
name: "AssignedTo",
table: "Tasks");
migrationBuilder.DropColumn(
name: "CreatedAt",
table: "Tasks");
migrationBuilder.DropColumn(
name: "Detail",
table: "Tasks");
migrationBuilder.DropColumn(
name: "Source",
table: "Tasks");
}
}
}
@@ -0,0 +1,311 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Nexus.Api.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Nexus.Api.Migrations
{
[DbContext(typeof(NexusDbContext))]
[Migration("20260618214335_AddNotifications")]
partial class AddNotifications
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Nexus.Api.Data.ActivityEvent", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("TaskId");
b.ToTable("Activity");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("Nexus.Api.Data.Notification", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ForUser")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("Message")
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.HasKey("Id");
b.HasIndex("ForUser", "IsRead", "CreatedAt");
b.ToTable("Notifications");
});
modelBuilder.Entity("Nexus.Api.Data.Project", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<int>("Progress")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FamilyId")
.HasColumnType("uuid");
b.Property<string>("ReplacedByTokenHash")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId", "FamilyId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssignedTo")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("ParentTaskId")
.HasColumnType("uuid");
b.Property<string>("Priority")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ProjectId")
.HasColumnType("uuid");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssignedTo");
b.HasIndex("ParentTaskId");
b.HasIndex("Source");
b.ToTable("Tasks");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.HasOne("Nexus.Api.Data.NexusUser", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.HasOne("Nexus.Api.Data.WorkTask", "ParentTask")
.WithMany("ChildTasks")
.HasForeignKey("ParentTaskId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("ParentTask");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Navigation("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Navigation("ChildTasks");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,45 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddNotifications : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Notifications",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Type = table.Column<string>(type: "character varying(60)", maxLength: 60, nullable: false),
Title = table.Column<string>(type: "character varying(240)", maxLength: 240, nullable: false),
Message = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
ForUser = table.Column<string>(type: "character varying(60)", maxLength: 60, nullable: false),
TaskId = table.Column<Guid>(type: "uuid", nullable: true),
IsRead = table.Column<bool>(type: "boolean", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Notifications", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Notifications_ForUser_IsRead_CreatedAt",
table: "Notifications",
columns: new[] { "ForUser", "IsRead", "CreatedAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Notifications");
}
}
}
@@ -0,0 +1,49 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddTaskParentChild : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ParentTaskId",
table: "Tasks",
type: "uuid",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Tasks_ParentTaskId",
table: "Tasks",
column: "ParentTaskId");
migrationBuilder.AddForeignKey(
name: "FK_Tasks_Tasks_ParentTaskId",
table: "Tasks",
column: "ParentTaskId",
principalTable: "Tasks",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Tasks_Tasks_ParentTaskId",
table: "Tasks");
migrationBuilder.DropIndex(
name: "IX_Tasks_ParentTaskId",
table: "Tasks");
migrationBuilder.DropColumn(
name: "ParentTaskId",
table: "Tasks");
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddTaskDueDate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTimeOffset>(
name: "DueDate",
table: "Tasks",
type: "timestamp with time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DueDate",
table: "Tasks");
}
}
}
@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddActivityTaskReference : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "TaskId",
table: "Activity",
type: "uuid",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Activity_TaskId",
table: "Activity",
column: "TaskId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Activity_TaskId",
table: "Activity");
migrationBuilder.DropColumn(
name: "TaskId",
table: "Activity");
}
}
}
@@ -0,0 +1,270 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Nexus.Api.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Nexus.Api.Migrations
{
[DbContext(typeof(NexusDbContext))]
[Migration("20260618233003_AddDelegatedState")]
partial class AddDelegatedState
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Nexus.Api.Data.ActivityEvent", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("TaskId");
b.ToTable("Activity");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("Nexus.Api.Data.Project", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<int>("Progress")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FamilyId")
.HasColumnType("uuid");
b.Property<string>("ReplacedByTokenHash")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId", "FamilyId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssignedTo")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("ParentTaskId")
.HasColumnType("uuid");
b.Property<string>("Priority")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ProjectId")
.HasColumnType("uuid");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssignedTo");
b.HasIndex("ParentTaskId");
b.HasIndex("Source");
b.ToTable("Tasks");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.HasOne("Nexus.Api.Data.NexusUser", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.HasOne("Nexus.Api.Data.WorkTask", "ParentTask")
.WithMany("ChildTasks")
.HasForeignKey("ParentTaskId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("ParentTask");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Navigation("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Navigation("ChildTasks");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,24 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddDelegatedState : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// Delegated state is a pure code change to the TaskState enum and
// TaskStateHelper. No schema change required since the State column
// is already a free-form string column.
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
// No schema to revert.
}
}
}
@@ -0,0 +1,322 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Nexus.Api.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Nexus.Api.Migrations
{
[DbContext(typeof(NexusDbContext))]
[Migration("20260620174200_AddAgentTaskFields")]
partial class AddAgentTaskFields
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Nexus.Api.Data.ActivityEvent", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("TaskId");
b.ToTable("Activity");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("Nexus.Api.Data.Notification", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ForUser")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("Message")
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.HasKey("Id");
b.HasIndex("ForUser", "IsRead", "CreatedAt");
b.ToTable("Notifications");
});
modelBuilder.Entity("Nexus.Api.Data.Project", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<int>("Progress")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FamilyId")
.HasColumnType("uuid");
b.Property<string>("ReplacedByTokenHash")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId", "FamilyId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssignedTo")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExpectedFrom")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsAgentTask")
.HasColumnType("boolean");
b.Property<Guid?>("ParentTaskId")
.HasColumnType("uuid");
b.Property<string>("Priority")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ProjectId")
.HasColumnType("uuid");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssignedTo");
b.HasIndex("ExpectedFrom");
b.HasIndex("IsAgentTask");
b.HasIndex("ParentTaskId");
b.HasIndex("Source");
b.ToTable("Tasks");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.HasOne("Nexus.Api.Data.NexusUser", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.HasOne("Nexus.Api.Data.WorkTask", "ParentTask")
.WithMany("ChildTasks")
.HasForeignKey("ParentTaskId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("ParentTask");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Navigation("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Navigation("ChildTasks");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,58 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddAgentTaskFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsAgentTask",
table: "Tasks",
type: "boolean",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<string>(
name: "ExpectedFrom",
table: "Tasks",
type: "character varying(60)",
maxLength: 60,
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Tasks_IsAgentTask",
table: "Tasks",
column: "IsAgentTask");
migrationBuilder.CreateIndex(
name: "IX_Tasks_ExpectedFrom",
table: "Tasks",
column: "ExpectedFrom");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tasks_IsAgentTask",
table: "Tasks");
migrationBuilder.DropIndex(
name: "IX_Tasks_ExpectedFrom",
table: "Tasks");
migrationBuilder.DropColumn(
name: "ExpectedFrom",
table: "Tasks");
migrationBuilder.DropColumn(
name: "IsAgentTask",
table: "Tasks");
}
}
}
@@ -0,0 +1,336 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Nexus.Api.Data;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Nexus.Api.Migrations
{
[DbContext(typeof(NexusDbContext))]
[Migration("20260621081500_AddSeedAudit")]
partial class AddSeedAudit
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Nexus.Api.Data.ActivityEvent", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("TaskId");
b.ToTable("Activity");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset?>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("Nexus.Api.Data.Notification", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ForUser")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("Message")
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.HasKey("Id");
b.HasIndex("ForUser", "IsRead", "CreatedAt");
b.ToTable("Notifications");
});
modelBuilder.Entity("Nexus.Api.Data.Project", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(160)
.HasColumnType("character varying(160)");
b.Property<int>("Progress")
.HasColumnType("integer");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("FamilyId")
.HasColumnType("uuid");
b.Property<string>("ReplacedByTokenHash")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserId", "FamilyId");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.SeedAudit", b =>
{
b.Property<string>("Key")
.HasMaxLength(80)
.HasColumnType("character varying(80)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Key");
b.ToTable("SeedAudit");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AssignedTo")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExpectedFrom")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsAgentTask")
.HasColumnType("boolean");
b.Property<Guid?>("ParentTaskId")
.HasColumnType("uuid");
b.Property<string>("Priority")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ProjectId")
.HasColumnType("uuid");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<string>("State")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("AssignedTo");
b.HasIndex("ExpectedFrom");
b.HasIndex("IsAgentTask");
b.HasIndex("ParentTaskId");
b.HasIndex("Source");
b.ToTable("Tasks");
});
modelBuilder.Entity("Nexus.Api.Data.RefreshToken", b =>
{
b.HasOne("Nexus.Api.Data.NexusUser", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.HasOne("Nexus.Api.Data.WorkTask", "ParentTask")
.WithMany("ChildTasks")
.HasForeignKey("ParentTaskId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("ParentTask");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{
b.Navigation("RefreshTokens");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Navigation("ChildTasks");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,33 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Nexus.Api.Migrations
{
/// <inheritdoc />
public partial class AddSeedAudit : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SeedAudit",
columns: table => new
{
Key = table.Column<string>(type: "character varying(80)", maxLength: 80, nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SeedAudit", x => x.Key);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SeedAudit");
}
}
}
@@ -38,12 +38,19 @@ namespace Nexus.Api.Migrations
.HasMaxLength(1000) .HasMaxLength(1000)
.HasColumnType("character varying(1000)"); .HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Type") b.Property<string>("Type")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("TaskId");
b.ToTable("Activity"); b.ToTable("Activity");
}); });
@@ -93,6 +100,47 @@ namespace Nexus.Api.Migrations
b.ToTable("Users"); b.ToTable("Users");
}); });
modelBuilder.Entity("Nexus.Api.Data.Notification", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ForUser")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("Message")
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<Guid?>("TaskId")
.HasColumnType("uuid");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(240)
.HasColumnType("character varying(240)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.HasKey("Id");
b.HasIndex("ForUser", "IsRead", "CreatedAt");
b.ToTable("Notifications");
});
modelBuilder.Entity("Nexus.Api.Data.Project", b => modelBuilder.Entity("Nexus.Api.Data.Project", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
@@ -166,12 +214,50 @@ namespace Nexus.Api.Migrations
b.ToTable("RefreshTokens"); b.ToTable("RefreshTokens");
}); });
modelBuilder.Entity("Nexus.Api.Data.SeedAudit", b =>
{
b.Property<string>("Key")
.HasMaxLength(80)
.HasColumnType("character varying(80)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Key");
b.ToTable("SeedAudit");
});
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b => modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("uuid"); .HasColumnType("uuid");
b.Property<string>("AssignedTo")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Detail")
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTimeOffset?>("DueDate")
.HasColumnType("timestamp with time zone");
b.Property<string>("ExpectedFrom")
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<bool>("IsAgentTask")
.HasColumnType("boolean");
b.Property<Guid?>("ParentTaskId")
.HasColumnType("uuid");
b.Property<string>("Priority") b.Property<string>("Priority")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@@ -179,6 +265,11 @@ namespace Nexus.Api.Migrations
b.Property<Guid?>("ProjectId") b.Property<Guid?>("ProjectId")
.HasColumnType("uuid"); .HasColumnType("uuid");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(60)
.HasColumnType("character varying(60)");
b.Property<string>("State") b.Property<string>("State")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@@ -193,6 +284,16 @@ namespace Nexus.Api.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("AssignedTo");
b.HasIndex("ExpectedFrom");
b.HasIndex("IsAgentTask");
b.HasIndex("ParentTaskId");
b.HasIndex("Source");
b.ToTable("Tasks"); b.ToTable("Tasks");
}); });
@@ -207,10 +308,25 @@ namespace Nexus.Api.Migrations
b.Navigation("User"); b.Navigation("User");
}); });
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.HasOne("Nexus.Api.Data.WorkTask", "ParentTask")
.WithMany("ChildTasks")
.HasForeignKey("ParentTaskId")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("ParentTask");
});
modelBuilder.Entity("Nexus.Api.Data.NexusUser", b => modelBuilder.Entity("Nexus.Api.Data.NexusUser", b =>
{ {
b.Navigation("RefreshTokens"); b.Navigation("RefreshTokens");
}); });
modelBuilder.Entity("Nexus.Api.Data.WorkTask", b =>
{
b.Navigation("ChildTasks");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }
+32 -2
View File
@@ -6,15 +6,45 @@ public sealed class NexusDbContext(DbContextOptions<NexusDbContext> options) : D
{ {
public DbSet<Project> Projects => Set<Project>(); public DbSet<Project> Projects => Set<Project>();
public DbSet<WorkTask> Tasks => Set<WorkTask>(); public DbSet<WorkTask> Tasks => Set<WorkTask>();
public DbSet<Notification> Notifications => Set<Notification>();
public DbSet<ActivityEvent> Activity => Set<ActivityEvent>(); public DbSet<ActivityEvent> Activity => Set<ActivityEvent>();
public DbSet<NexusUser> Users => Set<NexusUser>(); public DbSet<NexusUser> Users => Set<NexusUser>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>(); public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<SeedAudit> SeedAudits => Set<SeedAudit>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<Project>().Property(x => x.Name).HasMaxLength(160); modelBuilder.Entity<Project>().Property(x => x.Name).HasMaxLength(160);
modelBuilder.Entity<WorkTask>().Property(x => x.Title).HasMaxLength(240); modelBuilder.Entity<WorkTask>(entity =>
modelBuilder.Entity<ActivityEvent>().Property(x => x.Message).HasMaxLength(1000); {
entity.Property(x => x.Title).HasMaxLength(240);
entity.Property(x => x.Detail).HasMaxLength(2000);
entity.Property(x => x.Source).HasMaxLength(60);
entity.Property(x => x.AssignedTo).HasMaxLength(60);
entity.Property(x => x.ExpectedFrom).HasMaxLength(60);
entity.HasIndex(x => x.Source);
entity.HasIndex(x => x.AssignedTo);
entity.HasIndex(x => x.IsAgentTask);
entity.HasIndex(x => x.ExpectedFrom);
entity.HasOne(x => x.ParentTask)
.WithMany(x => x.ChildTasks)
.HasForeignKey(x => x.ParentTaskId)
.OnDelete(DeleteBehavior.SetNull);
});
modelBuilder.Entity<Notification>(entity =>
{
entity.Property(x => x.Title).HasMaxLength(240);
entity.Property(x => x.Message).HasMaxLength(1000);
entity.Property(x => x.Type).HasMaxLength(60);
entity.Property(x => x.ForUser).HasMaxLength(60);
entity.HasIndex(x => new { x.ForUser, x.IsRead, x.CreatedAt });
});
modelBuilder.Entity<ActivityEvent>(entity =>
{
entity.Property(x => x.Message).HasMaxLength(1000);
entity.HasIndex(x => x.TaskId);
});
modelBuilder.Entity<NexusUser>().HasIndex(u => u.NormalizedEmail).IsUnique(); modelBuilder.Entity<NexusUser>().HasIndex(u => u.NormalizedEmail).IsUnique();
modelBuilder.Entity<RefreshToken>().HasIndex(r => r.TokenHash).IsUnique(); modelBuilder.Entity<RefreshToken>().HasIndex(r => r.TokenHash).IsUnique();
modelBuilder.Entity<RefreshToken>().HasIndex(r => new { r.UserId, r.FamilyId }); modelBuilder.Entity<RefreshToken>().HasIndex(r => new { r.UserId, r.FamilyId });
+1
View File
@@ -8,6 +8,7 @@ RUN dotnet publish -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine
WORKDIR /app WORKDIR /app
COPY --from=build /app/publish . COPY --from=build /app/publish .
RUN apk add --no-cache curl
USER $APP_UID USER $APP_UID
EXPOSE 8080 EXPOSE 8080
ENTRYPOINT ["dotnet", "Nexus.Api.dll"] ENTRYPOINT ["dotnet", "Nexus.Api.dll"]
@@ -0,0 +1,96 @@
using Microsoft.EntityFrameworkCore;
using Nexus.Api.Data;
using Nexus.Api.Helpers;
using Nexus.Api.Middleware;
using Nexus.Api.Services;
namespace Nexus.Api.Extensions;
/// <summary>
/// Extension methods for configuring the Nexus application pipeline and startup.
/// </summary>
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Applies pending EF Core migrations and seeds the initial owner account if none exist.
/// Uses a <see cref="SeedAudit"/> guard so the owner is never re-created even if all users
/// are deleted — the DB is the single source of truth for the owner password after first seed.
/// </summary>
public static async Task EnsureDatabaseAsync(this WebApplication app)
{
var configuration = app.Configuration;
await using (var scope = app.Services.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService<NexusDbContext>();
await db.Database.MigrateAsync();
const string seedKey = "owner_created";
var alreadySeeded = await db.SeedAudits.AnyAsync(s => s.Key == seedKey);
if (alreadySeeded)
return;
var ownerEmail = configuration["Owner:Email"]?.Trim().ToLowerInvariant();
var ownerPassword = configuration["Owner:Password"];
var ownerDisplayName = configuration["Owner:DisplayName"]?.Trim();
var hasUsers = await db.Users.AnyAsync();
if (!hasUsers)
{
if (string.IsNullOrWhiteSpace(ownerEmail))
throw new InvalidOperationException("Owner:Email is required for initial setup.");
var initialDisplayName = string.IsNullOrWhiteSpace(ownerDisplayName)
? PasswordHelper.BuildOwnerDisplayName(ownerEmail)
: ownerDisplayName;
var initialPassword = string.IsNullOrWhiteSpace(ownerPassword)
? PasswordHelper.GenerateTemporaryPassword()
: ownerPassword;
if (!string.IsNullOrWhiteSpace(ownerPassword) && ownerPassword.Length < 10)
throw new InvalidOperationException("Owner:Password must be at least 10 characters when provided explicitly.");
db.Users.Add(new NexusUser
{
Email = ownerEmail,
NormalizedEmail = AuthService.NormalizeEmail(ownerEmail),
DisplayName = initialDisplayName,
PasswordHash = PasswordSecurity.Hash(initialPassword),
Role = "owner"
});
await db.SaveChangesAsync();
if (string.IsNullOrWhiteSpace(ownerPassword))
{
Console.Error.WriteLine($"[nexus] Initial owner credentials generated: displayName={initialDisplayName}, password={initialPassword}");
}
}
// Record the seed attempt regardless of whether users already existed.
// This prevents re-seeding even if the Users table is wiped.
db.SeedAudits.Add(new SeedAudit { Key = seedKey });
await db.SaveChangesAsync();
}
}
/// <summary>
/// Configures the HTTP middleware pipeline: forwarded headers, rate limiting, auth, security headers, and Swagger in development.
/// </summary>
public static IApplicationBuilder UseNexusPipeline(this IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseForwardedHeaders();
app.UseRateLimiter();
app.UseApiKeyAuthentication();
app.UseAuthentication();
app.UseAuthorization();
app.UseSecurityHeaders();
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
return app;
}
}
@@ -0,0 +1,249 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.IdentityModel.Tokens;
using Nexus.Api.Data;
using Nexus.Api.Integrations;
using Nexus.Api.RateLimiting;
using Nexus.Api.Repositories;
using Nexus.Api.Routing;
using Nexus.Api.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
namespace Nexus.Api.Extensions;
/// <summary>
/// Extension methods for registering Nexus application services in the DI container.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Configures JWT authentication, authorization, and antiforgery.
/// </summary>
public static IServiceCollection AddNexusAuth(this IServiceCollection services, IConfiguration configuration)
{
var jwtKey = configuration["Jwt:Key"];
var jwtIssuer = configuration["Jwt:Issuer"] ?? "nexus";
var jwtAudience = configuration["Jwt:Audience"] ?? "nexus-web";
if (string.IsNullOrWhiteSpace(jwtKey) || Encoding.UTF8.GetByteCount(jwtKey) < 32)
throw new InvalidOperationException("Jwt:Key must be configured with at least 32 bytes.");
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
NameClaimType = JwtRegisteredClaimNames.Sub,
RoleClaimType = System.Security.Claims.ClaimTypes.Role,
ClockSkew = TimeSpan.FromSeconds(30)
};
});
services.AddAuthorization();
services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.Cookie.Name = "nexus-csrf";
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.HttpOnly = false;
});
return services;
}
/// <summary>
/// Configures rate limiting policies (auth and agents).
/// </summary>
public static IServiceCollection AddNexusRateLimiting(this IServiceCollection services)
{
services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, ct) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.HttpContext.Response.Headers.ContentType = "application/json";
var retryAfterSeconds = 60;
// Try to read retry-after info from the metadata
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
retryAfterSeconds = (int)retryAfter.TotalSeconds;
}
// Set standard headers
context.HttpContext.Response.Headers.RetryAfter = retryAfterSeconds.ToString();
context.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
context.HttpContext.Response.Headers["X-RateLimit-Reset"] =
DateTimeOffset.UtcNow.AddSeconds(retryAfterSeconds).ToUnixTimeSeconds().ToString();
var body = new
{
error = "rate_limit_exceeded",
message = $"Too many attempts. Try again in {retryAfterSeconds} second(s).",
remaining = 0,
retryAfterSeconds
};
await context.HttpContext.Response.WriteAsJsonAsync(body, ct);
};
options.AddPolicy("auth", context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
options.AddPolicy("agents", context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 30,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
});
return services;
}
/// <summary>
/// Configures forwarded headers for reverse proxy scenarios.
/// </summary>
public static IServiceCollection AddNexusForwardedHeaders(this IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
});
return services;
}
/// <summary>
/// Configures Swagger and JSON serialization options.
/// </summary>
public static IServiceCollection AddNexusSwagger(this IServiceCollection services)
{
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
return services;
}
/// <summary>
/// Registers the Entity Framework Core DbContext with Npgsql.
/// </summary>
public static IServiceCollection AddNexusDatabase(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<NexusDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("Nexus"))
.ConfigureWarnings(w => w.Ignore(
Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning)));
return services;
}
/// <summary>
/// Registers typed and named HTTP clients for OpenClaw integration.
/// </summary>
public static IServiceCollection AddNexusHttpClients(this IServiceCollection services, IConfiguration configuration)
{
services.AddHttpClient<IAgentRuntime, OpenClawRuntime>(client =>
{
client.BaseAddress = new(configuration["Integrations:OpenClaw:BaseUrl"]
?? "http://127.0.0.1:18789");
client.Timeout = TimeSpan.FromSeconds(120);
});
services.AddHttpClient("gateway", client =>
{
client.BaseAddress = new(configuration["Integrations:OpenClaw:BaseUrl"]
?? "http://127.0.0.1:18789");
client.Timeout = TimeSpan.FromSeconds(120);
});
services.AddHttpClient<IOpenClawGatewayClient, OpenClawGatewayClient>(client =>
{
client.BaseAddress = new(configuration["Integrations:OpenClaw:BaseUrl"]
?? "http://127.0.0.1:18789");
client.Timeout = TimeSpan.FromSeconds(120);
});
return services;
}
/// <summary>
/// Registers application domain services (transient, scoped, singleton).
/// </summary>
public static IServiceCollection AddNexusApplicationServices(this IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddSingleton<LoginAttemptTracker>();
services.AddTransient<ModelRoutingService>();
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IAgentService, AgentService>();
services.AddScoped<IDashboardService, DashboardService>();
services.AddScoped<IProjectService, ProjectService>();
services.AddScoped<ITaskService, TaskService>();
services.AddScoped<IOperationsService, OperationsService>();
services.AddScoped<ITeamService, TeamService>();
services.AddSingleton<IAgentConfigService, AgentConfigService>();
services.AddSingleton<IMemoryService, MemoryService>();
services.AddSingleton<IIncidentService, IncidentService>();
services.AddSingleton<IDocService, DocService>();
services.AddScoped<INotificationService, NotificationService>();
services.AddScoped<ICalendarService, CalendarService>();
return services;
}
/// <summary>
/// Registers data repositories.
/// </summary>
public static IServiceCollection AddNexusRepositories(this IServiceCollection services)
{
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<ITaskRepository, TaskRepository>();
services.AddScoped<IActivityRepository, ActivityRepository>();
return services;
}
/// <summary>
/// Configures health checks (PostgreSQL connectivity and runtime status).
/// </summary>
public static IServiceCollection AddNexusHealthChecks(this IServiceCollection services, IConfiguration configuration)
{
services.AddHealthChecks()
.AddNpgSql(configuration.GetConnectionString("Nexus")!, name: "postgresql", tags: ["database"])
.AddCheck("runtime", () => HealthCheckResult.Healthy("Runtime configured"), tags: ["runtime"]);
return services;
}
}
+37
View File
@@ -0,0 +1,37 @@
using System.Security.Cryptography;
namespace Nexus.Api.Helpers;
/// <summary>
/// Helper methods for password generation and name construction.
/// </summary>
public static class PasswordHelper
{
/// <summary>
/// Generates a cryptographically random temporary password (30 chars, URL-safe base64).
/// </summary>
public static string GenerateTemporaryPassword()
=> Convert.ToBase64String(RandomNumberGenerator.GetBytes(18))
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
/// <summary>
/// Builds a human-readable display name from an email address.
/// </summary>
public static string BuildOwnerDisplayName(string email)
{
var localPart = email.Split('@', 2)[0].Trim();
if (string.IsNullOrWhiteSpace(localPart)) return "Owner";
var words = localPart
.Replace('.', ' ')
.Replace('_', ' ')
.Replace('-', ' ')
.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(word => char.ToUpperInvariant(word[0]) + word[1..].ToLowerInvariant());
var displayName = string.Join(' ', words);
return string.IsNullOrWhiteSpace(displayName) ? "Owner" : displayName;
}
}
+39
View File
@@ -0,0 +1,39 @@
using System.Security.Claims;
namespace Nexus.Api.Middleware;
/// <summary>
/// Middleware that authenticates requests via the X-Nexus-Api-Key header.
/// On match, sets a ClaimsPrincipal with role "Service".
/// On mismatch or absent header, passes through to next middleware (JWT auth).
/// </summary>
public sealed class ApiKeyMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
var configuration = context.RequestServices.GetRequiredService<IConfiguration>();
var apiKey = configuration["NexusApiKey"];
if (!string.IsNullOrWhiteSpace(apiKey) &&
context.Request.Headers.TryGetValue("X-Nexus-Api-Key", out var providedKey) &&
string.Equals(apiKey, providedKey, StringComparison.Ordinal))
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, "service"),
new Claim(ClaimTypes.Name, "ApiService"),
new Claim(ClaimTypes.Role, "Service")
};
var identity = new ClaimsIdentity(claims, "ApiKey");
context.User = new ClaimsPrincipal(identity);
}
await next(context);
}
}
public static class ApiKeyMiddlewareExtensions
{
public static IApplicationBuilder UseApiKeyAuthentication(this IApplicationBuilder builder)
=> builder.UseMiddleware<ApiKeyMiddleware>();
}
+124 -3
View File
@@ -8,7 +8,15 @@ public sealed record DashboardAgentInfo(
bool IsActive, bool IsActive,
string? CurrentTask, string? CurrentTask,
string? Description, string? Description,
string[] Tags string[] Tags,
int Progress = 0,
int Workload = 0,
string? Goal = null,
string RoleBadge = "badge-slate",
string StatusLabel = "Bereit",
string? Elapsed = null,
string? Think = null,
string? Next = null
); );
public sealed record MessageEntry( public sealed record MessageEntry(
@@ -32,7 +40,9 @@ public sealed record FeedEntry(
string Agent, string Agent,
string Action, string Action,
string Timestamp, string Timestamp,
string Time string Time,
string? AgentId = null,
string? Type = null
); );
public sealed record DashboardStatus( public sealed record DashboardStatus(
@@ -45,7 +55,10 @@ public sealed record DashboardStatus(
public sealed record QueueItem( public sealed record QueueItem(
string Id, string Id,
string Name, string Name,
string Status string Status,
string Priority,
string Source,
string WaitTime
); );
public sealed record AgentModelInfo( public sealed record AgentModelInfo(
@@ -62,3 +75,111 @@ public sealed record ModelOption(
string Name, string Name,
string Provider string Provider
); );
// ── Dashboard Task DTOs ──
public sealed record DashboardTaskDto(
Guid Id,
string Title,
string? Detail,
string Source,
string State,
string Priority,
string? AssignedTo,
Guid? ParentTaskId,
DateTimeOffset? DueDate,
DateTimeOffset CreatedAt,
DateTimeOffset UpdatedAt,
bool IsAgentTask = false,
string? ExpectedFrom = null,
string? LastActivityMessage = null,
DateTimeOffset? LastActivityAt = null
);
public sealed record CreateDashboardTaskRequest(
string Title,
string? Detail,
string? Source,
string? Priority,
string? AssignedTo,
Guid? ParentTaskId = null
);
public sealed record CreateAgentTaskRequest(
string Title,
string? Detail,
string? Source,
string? Priority,
string? AssignedTo,
string? ExpectedFrom,
Guid? ParentTaskId = null
);
public sealed record UpdateDashboardTaskRequest(
string? Title,
string? Detail,
string? Source,
string? Priority,
string? AssignedTo,
DateTimeOffset? DueDate = null
);
public sealed record UpdateDashboardTaskStatusRequest(
string Status
);
public sealed record AgentActivityEntry(
string Time,
string Text
);
// ── Task Board DTOs ──
public sealed record BoardResponse(
List<DashboardTaskDto> Offen,
List<DashboardTaskDto> InProgress,
List<DashboardTaskDto> Delegated,
List<DashboardTaskDto> Review,
List<DashboardTaskDto> Blocked,
List<DashboardTaskDto> Done
);
public sealed record MoveTaskRequest(
string State
);
public sealed record ResetStaleRequest(
int StaleHours = 2
);
public sealed record ResetStaleResponse(
int ResetCount
);
public sealed record PostActivityRequest(
string Message,
string? Type = null
);
// ── Agent Workflow DTOs ──
/// <summary>
/// Overview of the agent workflow state, grouping tasks by expected respondent
/// and highlighting stale tasks. Used by Iris to see who she is waiting for.
/// </summary>
public sealed record AgentWorkflowOverview(
List<DashboardTaskDto> WaitingForBao,
List<DashboardTaskDto> WaitingForIris,
List<DashboardTaskDto> WaitingForOthers,
List<DashboardTaskDto> StaleTasks,
TimeSpan StaleThreshold
);
// ── Notification DTOs ──
public sealed record NotificationDto(
Guid Id, string Type, string Title, string? Message,
string ForUser, Guid? TaskId, bool IsRead, DateTimeOffset CreatedAt
);
public sealed record UnreadCountDto(int Count);
+20
View File
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Nexus.Api.Data;
namespace Nexus.Api;
public class NexusDbContextFactory : IDesignTimeDbContextFactory<NexusDbContext>
{
public NexusDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<NexusDbContext>();
var connectionString = args.Length > 0
? args[0]
: Environment.GetEnvironmentVariable("ConnectionStrings__Nexus")
?? "Host=localhost;Port=5432;Database=nexus;Username=nexus;Password=nexus";
optionsBuilder.UseNpgsql(connectionString);
return new NexusDbContext(optionsBuilder.Options);
}
}
+14 -212
View File
@@ -1,224 +1,26 @@
using Microsoft.AspNetCore.Authentication.JwtBearer; using Nexus.Api.Extensions;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.IdentityModel.Tokens;
using Nexus.Api.Data;
using Nexus.Api.Integrations;
using Nexus.Api.Middleware;
using Nexus.Api.Repositories;
using Nexus.Api.Routing;
using Nexus.Api.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// --- JWT Configuration --- // --- Service Registration ---
var jwtKey = builder.Configuration["Jwt:Key"]; builder.Services.AddNexusAuth(builder.Configuration);
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "nexus"; builder.Services.AddNexusRateLimiting();
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "nexus-web"; builder.Services.AddNexusForwardedHeaders();
if (string.IsNullOrWhiteSpace(jwtKey) || Encoding.UTF8.GetByteCount(jwtKey) < 32) builder.Services.AddNexusSwagger();
throw new InvalidOperationException("Jwt:Key must be configured with at least 32 bytes."); builder.Services.AddNexusDatabase(builder.Configuration);
builder.Services.AddNexusHttpClients(builder.Configuration);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) builder.Services.AddNexusApplicationServices();
.AddJwtBearer(options => builder.Services.AddNexusRepositories();
{ builder.Services.AddNexusHealthChecks(builder.Configuration);
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
NameClaimType = JwtRegisteredClaimNames.Sub,
RoleClaimType = System.Security.Claims.ClaimTypes.Role,
ClockSkew = TimeSpan.FromSeconds(30)
};
});
builder.Services.AddAuthorization();
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.Cookie.Name = "nexus-csrf";
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.HttpOnly = false;
});
// --- Rate Limiting ---
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("auth", context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
options.AddPolicy("agents", context => RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 30,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0,
AutoReplenishment = true
}));
});
// --- Forwarded Headers ---
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
});
// --- Swagger & JSON ---
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
// --- Database ---
builder.Services.AddDbContext<NexusDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Nexus"))
.ConfigureWarnings(w => w.Ignore(Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning)));
// --- HTTP Clients ---
builder.Services.AddHttpClient<IAgentRuntime, OpenClawRuntime>(client =>
{
client.BaseAddress = new(builder.Configuration["Integrations:OpenClaw:BaseUrl"]
?? "http://127.0.0.1:18789");
client.Timeout = TimeSpan.FromSeconds(120);
});
builder.Services.AddHttpClient("gateway", client =>
{
client.BaseAddress = new(builder.Configuration["Integrations:OpenClaw:BaseUrl"]
?? "http://127.0.0.1:18789");
client.Timeout = TimeSpan.FromSeconds(120);
});
builder.Services.AddHttpClient<OpenClawGatewayClient>(client =>
{
client.BaseAddress = new(builder.Configuration["Integrations:OpenClaw:BaseUrl"]
?? "http://127.0.0.1:18789");
client.Timeout = TimeSpan.FromSeconds(120);
});
// --- Application Services ---
builder.Services.AddTransient<ModelRoutingService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IAgentService, AgentService>();
// --- Repositories ---
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IProjectRepository, ProjectRepository>();
builder.Services.AddScoped<ITaskRepository, TaskRepository>();
builder.Services.AddScoped<IActivityRepository, ActivityRepository>();
// --- Health Checks ---
builder.Services.AddHealthChecks()
.AddNpgSql(builder.Configuration.GetConnectionString("Nexus")!, name: "postgresql", tags: ["database"])
.AddCheck("runtime", () => HealthCheckResult.Healthy("Runtime configured"), tags: ["runtime"]);
// --- Controllers ---
builder.Services.AddControllers(); builder.Services.AddControllers();
var app = builder.Build(); var app = builder.Build();
// --- Database Migration & Owner Seeding --- // --- Database Migration & Seeding ---
await using (var scope = app.Services.CreateAsyncScope()) await app.EnsureDatabaseAsync();
{
var db = scope.ServiceProvider.GetRequiredService<NexusDbContext>();
await db.Database.MigrateAsync();
var ownerEmail = builder.Configuration["Owner:Email"]?.Trim().ToLowerInvariant();
var ownerPassword = builder.Configuration["Owner:Password"];
var ownerDisplayName = builder.Configuration["Owner:DisplayName"]?.Trim();
var hasUsers = await db.Users.AnyAsync();
if (!hasUsers)
{
if (string.IsNullOrWhiteSpace(ownerEmail))
throw new InvalidOperationException("Owner:Email is required for initial setup.");
var initialDisplayName = string.IsNullOrWhiteSpace(ownerDisplayName)
? BuildOwnerDisplayName(ownerEmail)
: ownerDisplayName;
var initialPassword = string.IsNullOrWhiteSpace(ownerPassword)
? GenerateTemporaryPassword()
: ownerPassword;
if (!string.IsNullOrWhiteSpace(ownerPassword) && ownerPassword.Length < 10)
throw new InvalidOperationException("Owner:Password must be at least 10 characters when provided explicitly.");
db.Users.Add(new NexusUser
{
Email = ownerEmail,
NormalizedEmail = AuthService.NormalizeEmail(ownerEmail),
DisplayName = initialDisplayName,
PasswordHash = PasswordSecurity.Hash(initialPassword),
Role = "owner"
});
await db.SaveChangesAsync();
if (string.IsNullOrWhiteSpace(ownerPassword))
{
Console.Error.WriteLine($"[nexus] Initial owner credentials generated: displayName={initialDisplayName}, password={initialPassword}");
}
}
}
// --- Middleware Pipeline --- // --- Middleware Pipeline ---
app.UseForwardedHeaders(); app.UseNexusPipeline(app.Environment);
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.UseSecurityHeaders();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapControllers(); app.MapControllers();
app.Run(); app.Run();
// --- Helpers ---
static string GenerateTemporaryPassword()
=> Convert.ToBase64String(RandomNumberGenerator.GetBytes(18))
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
static string BuildOwnerDisplayName(string email)
{
var localPart = email.Split('@', 2)[0].Trim();
if (string.IsNullOrWhiteSpace(localPart)) return "Owner";
var words = localPart
.Replace('.', ' ')
.Replace('_', ' ')
.Replace('-', ' ')
.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(word => char.ToUpperInvariant(word[0]) + word[1..].ToLowerInvariant());
var displayName = string.Join(' ', words);
return string.IsNullOrWhiteSpace(displayName) ? "Owner" : displayName;
}
@@ -0,0 +1,84 @@
using System.Collections.Concurrent;
namespace Nexus.Api.RateLimiting;
/// <summary>
/// Simple in-memory tracking of login attempts per IP,
/// aligned with the fixed-window rate limiter (5 attempts / 1 minute).
///
/// Provides remaining-attempt count that can be passed back to the frontend.
/// </summary>
public sealed class LoginAttemptTracker
{
private const int MaxAttempts = 5;
private static readonly TimeSpan Window = TimeSpan.FromMinutes(1);
// IP → (count, windowStartTicks)
private static readonly ConcurrentDictionary<string, (int Count, long WindowStartTicks)> _store = new();
/// <summary>
/// Registers a failed attempt for the given IP.
/// Returns remaining attempts (0 = locked out until reset).
/// </summary>
public int RecordFailedAttempt(string ip)
{
var now = Environment.TickCount64;
var windowTicks = (long)Window.TotalMilliseconds;
var (count, windowStart) = _store.AddOrUpdate(ip,
_ => (1, now),
(_, entry) =>
{
if (now - entry.WindowStartTicks >= windowTicks)
return (1, now);
return (entry.Count + 1, entry.WindowStartTicks);
});
return Math.Max(0, MaxAttempts - count);
}
/// <summary>
/// Returns the remaining attempts for the given IP without recording.
/// </summary>
public int GetRemaining(string ip)
{
var now = Environment.TickCount64;
var windowTicks = (long)Window.TotalMilliseconds;
if (_store.TryGetValue(ip, out var entry))
{
if (now - entry.WindowStartTicks >= windowTicks)
return MaxAttempts;
return Math.Max(0, MaxAttempts - entry.Count);
}
return MaxAttempts;
}
/// <summary>
/// Returns the number of seconds until the rate-limit window resets,
/// or 0 if the window has already expired / no attempts recorded.
/// </summary>
public int GetRetryAfterSeconds(string ip)
{
var now = Environment.TickCount64;
var windowTicks = (long)Window.TotalMilliseconds;
if (!_store.TryGetValue(ip, out var entry))
return 0;
var elapsed = now - entry.WindowStartTicks;
if (elapsed >= windowTicks)
return 0;
return (int)Math.Ceiling((windowTicks - elapsed) / 1000.0);
}
/// <summary>
/// Resets attempt count for the given IP (e.g. on success).
/// </summary>
public void Reset(string ip)
{
_store.TryRemove(ip, out _);
}
}
@@ -8,6 +8,18 @@ public sealed class ActivityRepository(NexusDbContext db) : IActivityRepository
public Task<List<ActivityEvent>> GetRecentAsync(int take, CancellationToken ct = default) public Task<List<ActivityEvent>> GetRecentAsync(int take, CancellationToken ct = default)
=> db.Activity.AsNoTracking().OrderByDescending(x => x.CreatedAt).Take(take).ToListAsync(ct); => db.Activity.AsNoTracking().OrderByDescending(x => x.CreatedAt).Take(take).ToListAsync(ct);
public Task<List<ActivityEvent>> GetRecentForTasksAsync(IEnumerable<Guid> taskIds, CancellationToken ct = default)
{
var ids = taskIds.Distinct().ToList();
if (ids.Count == 0)
return Task.FromResult(new List<ActivityEvent>());
return db.Activity.AsNoTracking()
.Where(x => x.TaskId.HasValue && ids.Contains(x.TaskId.Value))
.OrderByDescending(x => x.CreatedAt)
.ToListAsync(ct);
}
public async Task<(List<ActivityEvent> Items, int TotalCount)> GetPagedAsync( public async Task<(List<ActivityEvent> Items, int TotalCount)> GetPagedAsync(
string? type, string? sort, int page, int pageSize, CancellationToken ct = default) string? type, string? sort, int page, int pageSize, CancellationToken ct = default)
{ {
@@ -5,6 +5,7 @@ namespace Nexus.Api.Repositories;
public interface IActivityRepository public interface IActivityRepository
{ {
Task<List<ActivityEvent>> GetRecentAsync(int take, CancellationToken ct = default); Task<List<ActivityEvent>> GetRecentAsync(int take, CancellationToken ct = default);
Task<List<ActivityEvent>> GetRecentForTasksAsync(IEnumerable<Guid> taskIds, CancellationToken ct = default);
Task<(List<ActivityEvent> Items, int TotalCount)> GetPagedAsync( Task<(List<ActivityEvent> Items, int TotalCount)> GetPagedAsync(
string? type, string? sort, int page, int pageSize, CancellationToken ct = default); string? type, string? sort, int page, int pageSize, CancellationToken ct = default);
Task<List<ActivityEvent>> GetByAgentAsync(string agentId, int take, CancellationToken ct = default); Task<List<ActivityEvent>> GetByAgentAsync(string agentId, int take, CancellationToken ct = default);
+4 -3
View File
@@ -7,15 +7,16 @@ public interface IUserRepository
ValueTask<NexusUser?> GetByIdAsync(Guid userId, CancellationToken ct = default); ValueTask<NexusUser?> GetByIdAsync(Guid userId, CancellationToken ct = default);
Task<NexusUser?> GetByEmailAsync(string normalizedEmail, CancellationToken ct = default); Task<NexusUser?> GetByEmailAsync(string normalizedEmail, CancellationToken ct = default);
Task<bool> AnyUsersAsync(CancellationToken ct = default); Task<bool> AnyUsersAsync(CancellationToken ct = default);
Task<List<NexusUser>> GetAllAsync(CancellationToken ct = default);
Task<NexusUser> AddAsync(NexusUser user, CancellationToken ct = default); Task<NexusUser> AddAsync(NexusUser user, CancellationToken ct = default);
Task UpdateAsync(NexusUser user, CancellationToken ct = default); Task UpdateAsync(NexusUser user, CancellationToken ct = default);
Task DeleteAsync(NexusUser user, CancellationToken ct = default);
// Refresh token operations
Task<RefreshToken?> GetRefreshTokenByHashAsync(string tokenHash, CancellationToken ct = default); Task<RefreshToken?> GetRefreshTokenByHashAsync(string tokenHash, CancellationToken ct = default);
Task<List<RefreshToken>> GetActiveTokensByFamilyAsync(Guid familyId, CancellationToken ct = default); Task<List<RefreshToken>> GetActiveTokensByFamilyAsync(Guid familyId, CancellationToken ct = default);
Task AddRefreshTokenAsync(RefreshToken token, CancellationToken ct = default); Task AddRefreshTokenAsync(RefreshToken token, CancellationToken ct = default);
Task UpdateRefreshTokenAsync(RefreshToken token, CancellationToken ct = default); Task UpdateRefreshTokenAsync(RefreshToken token, CancellationToken ct = default);
Task RevokeTokenAsync(string tokenHash, CancellationToken ct = default);
Task RevokeFamilyAsync(Guid familyId, CancellationToken ct = default);
Task RemoveExpiredTokensAsync(Guid userId, CancellationToken ct = default); Task RemoveExpiredTokensAsync(Guid userId, CancellationToken ct = default);
Task SaveChangesAsync(CancellationToken ct = default);
} }
+1
View File
@@ -30,6 +30,7 @@ public sealed class TaskRepository(NexusDbContext db) : ITaskRepository
public async Task UpdateAsync(WorkTask task, CancellationToken ct = default) public async Task UpdateAsync(WorkTask task, CancellationToken ct = default)
{ {
task.UpdatedAt = DateTimeOffset.UtcNow; task.UpdatedAt = DateTimeOffset.UtcNow;
db.Tasks.Update(task);
await db.SaveChangesAsync(ct); await db.SaveChangesAsync(ct);
} }
+44 -3
View File
@@ -11,6 +11,9 @@ public sealed class UserRepository(NexusDbContext db) : IUserRepository
public Task<NexusUser?> GetByEmailAsync(string normalizedEmail, CancellationToken ct = default) public Task<NexusUser?> GetByEmailAsync(string normalizedEmail, CancellationToken ct = default)
=> db.Users.FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, ct); => db.Users.FirstOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, ct);
public Task<List<NexusUser>> GetAllAsync(CancellationToken ct = default)
=> db.Users.OrderBy(u => u.CreatedAt).ToListAsync(ct);
public Task<bool> AnyUsersAsync(CancellationToken ct = default) public Task<bool> AnyUsersAsync(CancellationToken ct = default)
=> db.Users.AnyAsync(ct); => db.Users.AnyAsync(ct);
@@ -24,6 +27,17 @@ public sealed class UserRepository(NexusDbContext db) : IUserRepository
public Task UpdateAsync(NexusUser user, CancellationToken ct = default) public Task UpdateAsync(NexusUser user, CancellationToken ct = default)
=> db.SaveChangesAsync(ct); => db.SaveChangesAsync(ct);
public async Task DeleteAsync(NexusUser user, CancellationToken ct = default)
{
// Remove refresh tokens first
var tokens = await db.RefreshTokens
.Where(r => r.UserId == user.Id)
.ToListAsync(ct);
db.RefreshTokens.RemoveRange(tokens);
db.Users.Remove(user);
await db.SaveChangesAsync(ct);
}
public Task<RefreshToken?> GetRefreshTokenByHashAsync(string tokenHash, CancellationToken ct = default) public Task<RefreshToken?> GetRefreshTokenByHashAsync(string tokenHash, CancellationToken ct = default)
=> db.RefreshTokens => db.RefreshTokens
.Include(r => r.User) .Include(r => r.User)
@@ -43,6 +57,33 @@ public sealed class UserRepository(NexusDbContext db) : IUserRepository
public Task UpdateRefreshTokenAsync(RefreshToken token, CancellationToken ct = default) public Task UpdateRefreshTokenAsync(RefreshToken token, CancellationToken ct = default)
=> db.SaveChangesAsync(ct); => db.SaveChangesAsync(ct);
public async Task RevokeTokenAsync(string tokenHash, CancellationToken ct = default)
{
var token = await db.RefreshTokens.FirstOrDefaultAsync(r => r.TokenHash == tokenHash, ct);
if (token is null || token.RevokedAt is not null) return;
token.RevokedAt = DateTimeOffset.UtcNow;
token.ConcurrencyStamp = Guid.NewGuid();
await db.SaveChangesAsync(ct);
}
public async Task RevokeFamilyAsync(Guid familyId, CancellationToken ct = default)
{
var activeTokens = await db.RefreshTokens
.Where(r => r.FamilyId == familyId && r.RevokedAt == null)
.ToListAsync(ct);
if (activeTokens.Count == 0) return;
var now = DateTimeOffset.UtcNow;
foreach (var token in activeTokens)
{
token.RevokedAt = now;
token.ConcurrencyStamp = Guid.NewGuid();
}
await db.SaveChangesAsync(ct);
}
public async Task RemoveExpiredTokensAsync(Guid userId, CancellationToken ct = default) public async Task RemoveExpiredTokensAsync(Guid userId, CancellationToken ct = default)
{ {
var cutoff = DateTimeOffset.UtcNow.AddDays(-30); var cutoff = DateTimeOffset.UtcNow.AddDays(-30);
@@ -51,9 +92,9 @@ public sealed class UserRepository(NexusDbContext db) : IUserRepository
.ToListAsync(ct); .ToListAsync(ct);
if (oldTokens.Count > 0) if (oldTokens.Count > 0)
{
db.RefreshTokens.RemoveRange(oldTokens); db.RefreshTokens.RemoveRange(oldTokens);
await db.SaveChangesAsync(ct);
}
} }
public Task SaveChangesAsync(CancellationToken ct = default)
=> db.SaveChangesAsync(ct);
} }
+64
View File
@@ -0,0 +1,64 @@
using Nexus.Api.Helpers;
namespace Nexus.Api.Services;
public sealed class AgentConfigService : IAgentConfigService
{
private static readonly HashSet<string> AllowedFiles = new(StringComparer.OrdinalIgnoreCase)
{
"IDENTITY.md", "SOUL.md", "AGENTS.md", "TOOLS.md", "HEARTBEAT.md", "USER.md", "MEMORY.md"
};
public IReadOnlyList<AgentConfigFileInfo> GetConfigFiles(string agentId)
{
var workspacePath = $"/mnt/workspace-{agentId}";
if (!Directory.Exists(workspacePath))
return Array.Empty<AgentConfigFileInfo>();
return Directory.GetFiles(workspacePath, "*.md")
.Select(f => new FileInfo(f))
.Where(f => AllowedFiles.Contains(f.Name))
.OrderBy(f => f.Name)
.Select(f => new AgentConfigFileInfo(f.Name, f.Length, f.LastWriteTimeUtc))
.ToList();
}
public async Task<AgentConfigFileContent?> GetConfigFileAsync(string agentId, string fileName, CancellationToken ct = default)
{
if (!PathSecurityHelper.IsValidConfigFileName(fileName))
return null;
var workspacePath = $"/mnt/workspace-{agentId}";
if (!PathSecurityHelper.TryResolveSafePath(workspacePath, fileName, out var safePath) || !File.Exists(safePath))
return null;
var content = await File.ReadAllTextAsync(safePath!, ct);
var fi = new FileInfo(safePath!);
return new AgentConfigFileContent(fileName, content, fi.Length, fi.LastWriteTimeUtc);
}
public async Task<AgentConfigFileSaveResult?> SaveConfigFileAsync(string agentId, string fileName, string content, CancellationToken ct = default)
{
if (!PathSecurityHelper.IsValidConfigFileName(fileName))
return null;
var workspacePath = $"/mnt/workspace-{agentId}";
if (!PathSecurityHelper.TryResolveSafePath(workspacePath, fileName, out var safePath))
return null;
var tempPath = safePath + ".tmp";
try
{
await File.WriteAllTextAsync(tempPath, content, ct);
File.Move(tempPath, safePath!, overwrite: true);
}
catch
{
if (File.Exists(tempPath)) File.Delete(tempPath);
throw;
}
var fi = new FileInfo(safePath!);
return new AgentConfigFileSaveResult(fileName, fi.Length, fi.LastWriteTimeUtc);
}
}
+3 -27
View File
@@ -71,7 +71,7 @@ public sealed class AuthService : IAuthService
if (token.RevokedAt is not null) if (token.RevokedAt is not null)
{ {
await RevokeFamilyAsync(token.FamilyId, ct); await _users.RevokeFamilyAsync(token.FamilyId, ct);
_logger.LogWarning("Refresh token reuse detected for family {FamilyId}", token.FamilyId); _logger.LogWarning("Refresh token reuse detected for family {FamilyId}", token.FamilyId);
return null; return null;
} }
@@ -84,23 +84,12 @@ public sealed class AuthService : IAuthService
public async Task RevokeAsync(string refreshToken, CancellationToken ct = default) public async Task RevokeAsync(string refreshToken, CancellationToken ct = default)
{ {
if (string.IsNullOrWhiteSpace(refreshToken)) return; if (string.IsNullOrWhiteSpace(refreshToken)) return;
var tokenHash = HashToken(refreshToken); var tokenHash = HashToken(refreshToken);
var token = await _users.GetRefreshTokenByHashAsync(tokenHash, ct); await _users.RevokeTokenAsync(tokenHash, ct);
if (token is null || token.RevokedAt is not null) return;
token.RevokedAt = DateTimeOffset.UtcNow;
token.ConcurrencyStamp = Guid.NewGuid();
await _users.SaveChangesAsync(ct);
} }
public Task<NexusUser?> GetUserAsync(Guid userId, CancellationToken ct = default) public Task<NexusUser?> GetUserAsync(Guid userId, CancellationToken ct = default)
=> Task.Run(async () => => _users.GetByIdAsync(userId, ct).AsTask();
{
// AsNoTracking equivalent: UserRepository.GetByIdAsync uses FindAsync (tracked by default)
// For read-only access, we call it but the result shouldn't be mutated
return await _users.GetByIdAsync(userId, ct);
}, ct);
public async Task<NexusUser?> UpdateProfileAsync(Guid userId, UpdateProfileRequest request, CancellationToken ct = default) public async Task<NexusUser?> UpdateProfileAsync(Guid userId, UpdateProfileRequest request, CancellationToken ct = default)
{ {
@@ -228,19 +217,6 @@ public sealed class AuthService : IAuthService
return new JwtSecurityTokenHandler().WriteToken(token); return new JwtSecurityTokenHandler().WriteToken(token);
} }
private async Task RevokeFamilyAsync(Guid familyId, CancellationToken ct)
{
var activeTokens = await _users.GetActiveTokensByFamilyAsync(familyId, ct);
var now = DateTimeOffset.UtcNow;
foreach (var token in activeTokens)
{
token.RevokedAt = now;
token.ConcurrencyStamp = Guid.NewGuid();
}
await _users.SaveChangesAsync(ct);
}
private static string GenerateRefreshToken() private static string GenerateRefreshToken()
{ {
var value = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)); var value = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
+86
View File
@@ -0,0 +1,86 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Nexus.Api.DTOs;
namespace Nexus.Api.Services;
public sealed class CalendarService(
IHttpClientFactory httpClientFactory,
IConfiguration configuration,
ILogger<CalendarService> logger) : ICalendarService
{
public async Task<IReadOnlyList<CronJobEntry>> GetCronJobsAsync(CancellationToken ct = default)
{
try
{
var client = CreateGatewayClient();
var response = await client.GetAsync("/api/cron", ct);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadFromJsonAsync<List<CronJobEntry>>(ct);
return data ?? new List<CronJobEntry>();
}
}
catch (Exception ex)
{
logger.LogDebug(ex, "Gateway cron endpoint not reachable, using fallback data");
}
return BuildFallbackCronJobs();
}
public async Task<IReadOnlyList<UpcomingCronEntry>> GetUpcomingCronJobsAsync(CancellationToken ct = default)
{
try
{
var client = CreateGatewayClient();
var response = await client.GetAsync("/api/cron/upcoming", ct);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadFromJsonAsync<List<UpcomingCronEntry>>(ct);
return data ?? new List<UpcomingCronEntry>();
}
}
catch (Exception ex)
{
logger.LogDebug(ex, "Gateway upcoming cron endpoint not reachable, using fallback data");
}
return BuildFallbackUpcomingJobs();
}
private HttpClient CreateGatewayClient()
{
var client = httpClientFactory.CreateClient("gateway");
var token = configuration["Integrations:OpenClaw:Token"];
if (!string.IsNullOrWhiteSpace(token))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
private static IReadOnlyList<CronJobEntry> BuildFallbackCronJobs()
{
var now = DateTimeOffset.UtcNow;
return
[
new("health-check", "Health Check", "*/5 * * * *", now.AddMinutes(-3).ToString("O"), now.AddMinutes(2).ToString("O"), "completed"),
new("memory-sync", "Memory Sync", "0 */6 * * *", now.AddHours(-2).ToString("O"), now.AddHours(4).ToString("O"), "completed"),
new("task-cleanup", "Task Cleanup", "0 3 * * *", now.AddDays(-1).ToString("O"), now.AddDays(1).AddHours(3).ToString("O"), "completed"),
new("backup", "Database Backup", "0 4 * * *", now.AddDays(-1).AddHours(-1).ToString("O"), now.AddDays(1).AddHours(4).ToString("O"), "completed"),
new("model-routing-refresh", "Model Routing Refresh", "*/30 * * * *", now.AddMinutes(-12).ToString("O"), now.AddMinutes(18).ToString("O"), "running")
];
}
private static IReadOnlyList<UpcomingCronEntry> BuildFallbackUpcomingJobs()
{
var now = DateTimeOffset.UtcNow;
return
[
new("health-check", "Health Check", now.AddMinutes(2).ToString("O"), "*/5 * * * *"),
new("model-routing-refresh", "Model Routing Refresh", now.AddMinutes(18).ToString("O"), "*/30 * * * *"),
new("memory-sync", "Memory Sync", now.AddHours(4).ToString("O"), "0 */6 * * *"),
new("task-cleanup", "Task Cleanup", now.AddDays(1).AddHours(3).ToString("O"), "0 3 * * *"),
new("backup", "Database Backup", now.AddDays(1).AddHours(4).ToString("O"), "0 4 * * *")
];
}
}
+209
View File
@@ -0,0 +1,209 @@
using Nexus.Api.Models;
namespace Nexus.Api.Services;
public sealed class DashboardService(
IOpenClawGatewayClient gateway,
ITaskService taskService,
ILogger<DashboardService> logger) : IDashboardService
{
public async Task<DashboardStatus> GetStatusAsync()
{
try
{
return await gateway.GetStatusAsync();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard status check failed");
return new DashboardStatus(false, "Offline", 0, 0);
}
}
public async Task<List<DashboardAgentInfo>> GetAgentsAsync()
{
try
{
return await gateway.GetAgentsAsync();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard agents fetch failed");
return [];
}
}
public async Task<List<FeedEntry>> GetOperationsAsync(int limit, string? agentFilter)
{
try
{
var entries = await gateway.GetAllAgentOperationsAsync(Math.Clamp(limit, 1, 100));
if (!string.IsNullOrWhiteSpace(agentFilter))
{
entries = entries
.Where(e => string.Equals(e.AgentId, agentFilter, StringComparison.OrdinalIgnoreCase)
|| string.Equals(e.Agent, agentFilter, StringComparison.OrdinalIgnoreCase))
.ToList();
}
return entries;
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard operations fetch failed");
return [];
}
}
public async Task<ChatResponse> SendChatAsync(string agentId, string message)
{
try
{
return await gateway.SendChatMessageAsync(agentId, message);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard chat send failed");
return new ChatResponse(false, null, "Gateway nicht erreichbar");
}
}
public async Task<List<MessageEntry>> GetMessagesAsync(string? sessionKey, int limit, int offset)
{
try
{
var key = string.IsNullOrWhiteSpace(sessionKey) ? "agent:iris:main" : sessionKey.Trim();
var messages = await gateway.GetSessionHistoryAsync(key, Math.Clamp(limit, 1, 200), Math.Max(0, offset));
return messages
.Where(m => string.Equals(m.Role, "user", StringComparison.OrdinalIgnoreCase)
|| string.Equals(m.Role, "assistant", StringComparison.OrdinalIgnoreCase))
.ToList();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard messages fetch failed");
return [];
}
}
public async Task<List<QueueItem>> GetQueueAsync(CancellationToken ct)
{
try
{
var cronTask = gateway.GetQueueAsync();
var tasksTask = taskService.GetOpenAsync(ct);
await Task.WhenAll(cronTask, tasksTask);
var merged = new List<QueueItem>(cronTask.Result);
foreach (var t in tasksTask.Result)
{
merged.Add(new QueueItem("task-" + t.Id, t.Title, t.State, NormalizePriority(t.Priority), "task", "--"));
}
return merged
.OrderBy(q => PriorityOrder.GetValueOrDefault(q.Priority, 99))
.ToList();
}
catch (Exception ex)
{
logger.LogWarning(ex, "Dashboard queue fetch failed");
return [];
}
}
public async Task<QueueDeleteResult> DeleteQueueItemAsync(string id, string? source, CancellationToken ct)
{
if (string.Equals(source, "cron", StringComparison.OrdinalIgnoreCase))
{
var ok = await gateway.DeleteCronJobAsync(id);
return new QueueDeleteResult(ok ? QueueDeleteOutcome.Deleted : QueueDeleteOutcome.GatewayError);
}
if (string.Equals(source, "task", StringComparison.OrdinalIgnoreCase) || id.StartsWith("task-"))
{
if (!id.StartsWith("task-")) return new QueueDeleteResult(QueueDeleteOutcome.InvalidTaskId);
if (!Guid.TryParse(id["task-".Length..], out var guid))
return new QueueDeleteResult(QueueDeleteOutcome.InvalidTaskId);
var result = await taskService.CompleteViaQueueAsync(guid, ct);
return result.Outcome switch
{
TaskOperationOutcome.NotFound => new QueueDeleteResult(QueueDeleteOutcome.TaskNotFound),
_ => new QueueDeleteResult(QueueDeleteOutcome.Deleted)
};
}
var deleted = await gateway.DeleteCronJobAsync(id);
return new QueueDeleteResult(deleted ? QueueDeleteOutcome.Deleted : QueueDeleteOutcome.NotFound);
}
public async Task<QueuePriorityResult> CycleQueuePriorityAsync(string id, CancellationToken ct)
{
if (!id.StartsWith("task-"))
return new QueuePriorityResult(QueuePriorityOutcome.Ignored);
if (!Guid.TryParse(id["task-".Length..], out var guid))
return new QueuePriorityResult(QueuePriorityOutcome.InvalidTaskId);
var result = await taskService.CyclePriorityAsync(guid, ct);
return result.Outcome switch
{
TaskOperationOutcome.NotFound => new QueuePriorityResult(QueuePriorityOutcome.TaskNotFound),
_ => new QueuePriorityResult(QueuePriorityOutcome.Updated, result.Task?.Priority)
};
}
public async Task<AgentModelInfo?> GetAgentModelAsync(string agentId)
{
try
{
return await gateway.GetAgentModelAsync(agentId);
}
catch (Exception ex)
{
logger.LogWarning(ex, "GetAgentModel failed for {AgentId}", agentId);
return null;
}
}
public async Task<bool> SetAgentModelAsync(string agentId, string model)
{
try
{
return await gateway.SetAgentModelAsync(agentId, model);
}
catch (Exception ex)
{
logger.LogWarning(ex, "SetAgentModel failed for {AgentId}", agentId);
return false;
}
}
public async Task<List<AgentActivityEntry>> GetAgentActivityAsync(string agentId, int limit)
{
try
{
return await gateway.GetAgentActivityAsync(agentId, Math.Clamp(limit, 1, 20));
}
catch (Exception ex)
{
logger.LogWarning(ex, "GetAgentActivity failed for {AgentId}", agentId);
return [];
}
}
public List<ModelOption> GetAvailableModels() => gateway.GetAvailableModels();
private static string NormalizePriority(string priority) => priority.ToLowerInvariant() switch
{
"high" or "critical" or "urgent" => "high",
"low" or "minor" => "low",
_ => "medium"
};
private static readonly Dictionary<string, int> PriorityOrder = new(StringComparer.OrdinalIgnoreCase)
{
["high"] = 0, ["medium"] = 1, ["low"] = 2
};
}
+75
View File
@@ -0,0 +1,75 @@
using Nexus.Api.Helpers;
namespace Nexus.Api.Services;
public sealed class DocService : IDocService
{
private static readonly string[] AllowedExtensions = [".md", ".json", ".txt", ".yaml", ".yml", ".html", ".css"];
private static readonly string[] SearchRoots =
[
"/mnt/workspace-iris",
"/home/node/.openclaw/workspace/nexus"
];
private static readonly (string Dir, string Category)[] ScanDirectories =
[
("/mnt/workspace-iris/nexus-phases", "phases"),
("/mnt/workspace-iris/skills", "skills"),
("/mnt/workspace-iris", "workspace"),
("/home/node/.openclaw/workspace/nexus", "nexus"),
("/home/node/.openclaw/workspace/nexus/phases", "nexus-phases")
];
public IReadOnlyList<DocFileInfo> GetAll()
{
var results = new List<DocFileInfo>();
foreach (var (dir, category) in ScanDirectories)
{
if (!Directory.Exists(dir)) continue;
foreach (var file in Directory.GetFiles(dir, "*.*"))
{
var ext = Path.GetExtension(file).ToLowerInvariant();
if (!AllowedExtensions.Contains(ext)) continue;
var fi = new FileInfo(file);
results.Add(new DocFileInfo(
fi.Name,
file.Replace("/mnt/workspace-iris", "").TrimStart('/'),
category,
ext.Replace(".", ""),
fi.Length,
fi.LastWriteTimeUtc));
}
}
return results.OrderByDescending(x => x.ModifiedAt).Take(100).ToList();
}
public async Task<DocFileContent?> GetFileAsync(string path)
{
if (string.IsNullOrWhiteSpace(path))
return null;
string? resolvedPath = null;
foreach (var root in SearchRoots)
{
if (PathSecurityHelper.TryResolveSafePath(root, path, out var candidate) && File.Exists(candidate))
{
resolvedPath = candidate;
break;
}
}
if (resolvedPath is null)
return null;
var content = await File.ReadAllTextAsync(resolvedPath);
var fi = new FileInfo(resolvedPath);
var relativePath = resolvedPath
.Replace("/mnt/workspace-iris/", "")
.Replace("/home/node/.openclaw/workspace/nexus/", "");
return new DocFileContent(fi.Name, relativePath, content, fi.Length, fi.LastWriteTimeUtc);
}
}
+14
View File
@@ -0,0 +1,14 @@
namespace Nexus.Api.Services;
public sealed record AgentConfigFileInfo(string FileName, long Size, DateTime ModifiedAt);
public sealed record AgentConfigFileContent(string FileName, string Content, long Size, DateTime ModifiedAt);
public sealed record AgentConfigFileSaveResult(string FileName, long Size, DateTime ModifiedAt);
public interface IAgentConfigService
{
IReadOnlyList<AgentConfigFileInfo> GetConfigFiles(string agentId);
Task<AgentConfigFileContent?> GetConfigFileAsync(string agentId, string fileName, CancellationToken ct = default);
Task<AgentConfigFileSaveResult?> SaveConfigFileAsync(string agentId, string fileName, string content, CancellationToken ct = default);
}
+9
View File
@@ -0,0 +1,9 @@
using Nexus.Api.DTOs;
namespace Nexus.Api.Services;
public interface ICalendarService
{
Task<IReadOnlyList<CronJobEntry>> GetCronJobsAsync(CancellationToken ct = default);
Task<IReadOnlyList<UpcomingCronEntry>> GetUpcomingCronJobsAsync(CancellationToken ct = default);
}
+25
View File
@@ -0,0 +1,25 @@
using Nexus.Api.Models;
namespace Nexus.Api.Services;
public enum QueueDeleteOutcome { Deleted, NotFound, GatewayError, TaskNotFound, InvalidTaskId, Ignored }
public enum QueuePriorityOutcome { Updated, Ignored, TaskNotFound, InvalidTaskId }
public sealed record QueueDeleteResult(QueueDeleteOutcome Outcome);
public sealed record QueuePriorityResult(QueuePriorityOutcome Outcome, string? NewPriority = null);
public interface IDashboardService
{
Task<DashboardStatus> GetStatusAsync();
Task<List<DashboardAgentInfo>> GetAgentsAsync();
Task<List<FeedEntry>> GetOperationsAsync(int limit, string? agentFilter);
Task<ChatResponse> SendChatAsync(string agentId, string message);
Task<List<MessageEntry>> GetMessagesAsync(string? sessionKey, int limit, int offset);
Task<List<QueueItem>> GetQueueAsync(CancellationToken ct);
Task<QueueDeleteResult> DeleteQueueItemAsync(string id, string? source, CancellationToken ct);
Task<QueuePriorityResult> CycleQueuePriorityAsync(string id, CancellationToken ct);
Task<AgentModelInfo?> GetAgentModelAsync(string agentId);
Task<bool> SetAgentModelAsync(string agentId, string model);
Task<List<AgentActivityEntry>> GetAgentActivityAsync(string agentId, int limit);
List<ModelOption> GetAvailableModels();
}
+22
View File
@@ -0,0 +1,22 @@
namespace Nexus.Api.Services;
public sealed record DocFileInfo(
string Name,
string Path,
string Category,
string Type,
long Size,
DateTime ModifiedAt);
public sealed record DocFileContent(
string Name,
string Path,
string Content,
long Size,
DateTime ModifiedAt);
public interface IDocService
{
IReadOnlyList<DocFileInfo> GetAll();
Task<DocFileContent?> GetFileAsync(string path);
}
+22
View File
@@ -0,0 +1,22 @@
namespace Nexus.Api.Services;
public sealed record IncidentSummary(
string Name,
string Title,
string? Date,
string Severity,
string Excerpt,
long Size);
public sealed record IncidentDetail(
string Name,
string Title,
string? Date,
string Content,
long Size);
public interface IIncidentService
{
Task<IReadOnlyList<IncidentSummary>> GetAllAsync();
Task<IncidentDetail?> GetByNameAsync(string name);
}
+14
View File
@@ -0,0 +1,14 @@
namespace Nexus.Api.Services;
public sealed record MemoryFileInfo(string Name, string Path, long Size, DateTime ModifiedAt);
public sealed record MemoryFileContent(string Name, string Path, string Content, long Size, DateTime ModifiedAt);
public sealed record MemorySearchResult(string Name, string Path, string Excerpt, long Size);
public interface IMemoryService
{
Task<IReadOnlyList<MemoryFileInfo>> GetAllAsync();
Task<IReadOnlyList<MemorySearchResult>> SearchAsync(string query);
Task<MemoryFileContent?> GetFileAsync(string name);
}
+13
View File
@@ -0,0 +1,13 @@
using Nexus.Api.Data;
using Nexus.Api.Models;
namespace Nexus.Api.Services;
public interface INotificationService
{
Task<Notification> CreateAsync(string type, string title, string? message, string forUser, Guid? taskId = null, CancellationToken ct = default);
Task<IReadOnlyList<Notification>> GetForUserAsync(string forUser, int limit = 50, bool unreadOnly = false, CancellationToken ct = default);
Task<bool> MarkAsReadAsync(Guid id, CancellationToken ct = default);
Task<int> MarkAllAsReadAsync(string forUser, CancellationToken ct = default);
Task<int> GetUnreadCountAsync(string forUser, CancellationToken ct = default);
}
@@ -0,0 +1,20 @@
using System.Text.Json.Nodes;
using Nexus.Api.Models;
namespace Nexus.Api.Services;
public interface IOpenClawGatewayClient
{
Task<JsonNode?> InvokeToolAsync(string tool, object? args = null);
Task<DashboardStatus> GetStatusAsync();
Task<List<DashboardAgentInfo>> GetAgentsAsync();
Task<List<MessageEntry>> GetSessionHistoryAsync(string sessionKey, int limit = 50, int offset = 0);
Task<List<FeedEntry>> GetAllAgentOperationsAsync(int limit = 30);
Task<ChatResponse> SendChatMessageAsync(string agentId, string message);
Task<List<QueueItem>> GetQueueAsync();
Task<bool> DeleteCronJobAsync(string id);
Task<AgentModelInfo?> GetAgentModelAsync(string agentId);
Task<bool> SetAgentModelAsync(string agentId, string model);
Task<List<AgentActivityEntry>> GetAgentActivityAsync(string agentId, int limit = 5);
List<ModelOption> GetAvailableModels();
}
+6
View File
@@ -0,0 +1,6 @@
namespace Nexus.Api.Services;
public interface IOperationsService
{
Task<object> GetSnapshotAsync(CancellationToken ct = default);
}
+17
View File
@@ -0,0 +1,17 @@
using Nexus.Api.Data;
using Nexus.Api.DTOs;
namespace Nexus.Api.Services;
public enum ProjectDeleteOutcome { NotFound, Deleted, Archived }
public sealed record ProjectDeleteResult(ProjectDeleteOutcome Outcome, Project? Project = null);
public interface IProjectService
{
Task<IReadOnlyList<Project>> GetAllAsync(CancellationToken ct = default);
Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task<Project> CreateAsync(CreateProjectRequest request, CancellationToken ct = default);
Task<Project?> UpdateAsync(Guid id, UpdateProjectRequest request, CancellationToken ct = default);
Task<ProjectDeleteResult> DeleteAsync(Guid id, CancellationToken ct = default);
}
+44
View File
@@ -0,0 +1,44 @@
using Nexus.Api.Data;
using Nexus.Api.DTOs;
using Nexus.Api.Models;
namespace Nexus.Api.Services;
public enum TaskOperationOutcome { Success, NotFound, InvalidState }
public sealed record TaskOperationResult(TaskOperationOutcome Outcome, WorkTask? Task = null);
public interface ITaskService
{
Task<IReadOnlyList<WorkTask>> GetAllAsync(CancellationToken ct = default);
Task<WorkTask?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task<IReadOnlyList<WorkTask>> GetPendingApprovalAsync(CancellationToken ct = default);
Task<WorkTask> CreateAsync(CreateTaskRequest request, CancellationToken ct = default);
Task<TaskOperationResult> ApproveAsync(Guid id, CancellationToken ct = default);
Task<TaskOperationResult> RejectAsync(Guid id, CancellationToken ct = default);
Task<TaskOperationResult> UpdateStateAsync(Guid id, string state, CancellationToken ct = default);
Task<TaskOperationResult> UpdateAsync(Guid id, UpdateTaskRequest request, CancellationToken ct = default);
Task<TaskOperationResult> DeleteAsync(Guid id, CancellationToken ct = default);
// Dashboard-facing task operations
Task<IReadOnlyList<WorkTask>> GetOpenAsync(CancellationToken ct = default);
Task<WorkTask> CreateDashboardTaskAsync(string title, string? detail, string? source, string? priority, string? assignedTo, Guid? parentTaskId = null, CancellationToken ct = default);
Task<WorkTask> CreateAgentTaskAsync(string title, string? detail, string? source, string? priority, string? assignedTo, string? expectedFrom, Guid? parentTaskId = null, CancellationToken ct = default);
Task<TaskOperationResult> UpdateDashboardTaskAsync(Guid id, string? title, string? detail, string? source, string? priority, string? assignedTo, DateTimeOffset? dueDate = null, CancellationToken ct = default);
Task<TaskOperationResult> UpdateStatusAsync(Guid id, string status, CancellationToken ct = default);
Task<TaskOperationResult> CompleteViaQueueAsync(Guid id, CancellationToken ct = default);
Task<TaskOperationResult> CyclePriorityAsync(Guid id, CancellationToken ct = default);
// Task Board
Task<BoardResponse> GetBoardAsync(CancellationToken ct = default);
Task<TaskOperationResult> MoveTaskAsync(Guid id, string newState, CancellationToken ct = default);
Task<int> ResetStaleAsync(int staleHours, CancellationToken ct = default);
Task<int> ResetStaleInProgressTasksAsync(TimeSpan staleThreshold, CancellationToken ct = default);
Task<IReadOnlyList<WorkTask>> GetChildTasksAsync(Guid parentId, CancellationToken ct = default);
Task<List<ActivityEvent>> GetTaskActivityAsync(Guid taskId, CancellationToken ct = default);
Task<DashboardTaskDto?> GetDashboardTaskByIdAsync(Guid id, CancellationToken ct = default);
// Agent Workflow Overview
Task<IReadOnlyList<WorkTask>> GetWaitingTasksAsync(CancellationToken ct = default);
Task<AgentWorkflowOverview> GetAgentWorkflowOverviewAsync(TimeSpan staleThreshold, CancellationToken ct = default);
}
+19
View File
@@ -0,0 +1,19 @@
using Nexus.Api.Data;
namespace Nexus.Api.Services;
public sealed record TeamMember(
string Id,
string Name,
string Role,
string Model,
OperationalStatus Status,
DateTimeOffset? LastSeen,
string? Workspace,
string? Description,
string Identity);
public interface ITeamService
{
Task<IReadOnlyList<TeamMember>> GetTeamAsync(CancellationToken ct = default);
}
+89
View File
@@ -0,0 +1,89 @@
using Nexus.Api.Helpers;
using System.Text.RegularExpressions;
namespace Nexus.Api.Services;
public sealed partial class IncidentService : IIncidentService
{
private const string BasePath = "/mnt/workspace-iris/memory/incidents";
public async Task<IReadOnlyList<IncidentSummary>> GetAllAsync()
{
if (!Directory.Exists(BasePath))
return Array.Empty<IncidentSummary>();
var incidents = new List<IncidentSummary>();
foreach (var file in Directory.GetFiles(BasePath, "*.md").OrderByDescending(f => f).Take(50))
{
var fi = new FileInfo(file);
if (fi.Length > 1_000_000) continue;
var name = Path.GetFileNameWithoutExtension(file);
var content = await File.ReadAllTextAsync(file);
var title = ExtractTitle(name, content);
var date = ExtractDate(name);
var severity = ExtractSeverity(content);
var excerpt = ExtractExcerpt(content);
incidents.Add(new IncidentSummary(Path.GetFileName(file), title, date, severity, excerpt, fi.Length));
}
return incidents;
}
public async Task<IncidentDetail?> GetByNameAsync(string name)
{
if (!PathSecurityHelper.TryResolveSafePath(BasePath, name, out var filePath))
return null;
if (!File.Exists(filePath!))
{
if (!name.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
filePath = Path.Combine(BasePath, name + ".md");
if (!File.Exists(filePath!))
return null;
}
var content = await File.ReadAllTextAsync(filePath!);
var fi = new FileInfo(filePath!);
var fileName = Path.GetFileName(filePath!);
var title = ExtractTitle(Path.GetFileNameWithoutExtension(filePath!), content);
var date = ExtractDate(fileName);
return new IncidentDetail(fileName, title, date, content, fi.Length);
}
private static string ExtractTitle(string name, string content)
{
var match = TitleRegex().Match(content);
return match.Success ? match.Groups[1].Value.Trim() : name;
}
private static string? ExtractDate(string fileName)
{
var match = DateRegex().Match(fileName);
return match.Success ? match.Groups[1].Value : null;
}
private static string ExtractSeverity(string content)
{
var match = SeverityRegex().Match(content);
return match.Success ? match.Groups[1].Value.Trim() : "unknown";
}
private static string ExtractExcerpt(string content)
{
var excerptEnd = content.IndexOf("\n## ", StringComparison.Ordinal);
var excerpt = excerptEnd > 0 ? content[..excerptEnd].Trim() : content[..Math.Min(300, content.Length)].Trim();
return excerpt.Length > 200 ? excerpt[..200] + "…" : excerpt;
}
[GeneratedRegex(@"^#\s+(.+)$", RegexOptions.Multiline)]
private static partial Regex TitleRegex();
[GeneratedRegex(@"^(\d{4}-\d{2}-\d{2})")]
private static partial Regex DateRegex();
[GeneratedRegex(@"\*\*Severity:\*\*\s*(.+)$", RegexOptions.Multiline)]
private static partial Regex SeverityRegex();
}
+100
View File
@@ -0,0 +1,100 @@
using Nexus.Api.Helpers;
namespace Nexus.Api.Services;
public sealed class MemoryService : IMemoryService
{
private const string BasePath = "/mnt/workspace-iris/memory";
private const string LongTermPath = "/mnt/workspace-iris/MEMORY.md";
private const int MaxFileSize = 1_000_000;
private const int MaxFiles = 50;
public Task<IReadOnlyList<MemoryFileInfo>> GetAllAsync()
{
var files = new List<MemoryFileInfo>();
if (File.Exists(LongTermPath))
{
var fi = new FileInfo(LongTermPath);
files.Add(new MemoryFileInfo("MEMORY.md", "MEMORY.md", fi.Length, fi.LastWriteTimeUtc));
}
if (Directory.Exists(BasePath))
{
var memFiles = Directory.GetFiles(BasePath, "*.md")
.Select(f => new FileInfo(f))
.OrderByDescending(f => f.Name)
.Select(f => new MemoryFileInfo(
f.Name,
f.FullName.Replace(BasePath, "").TrimStart('/'),
f.Length,
f.LastWriteTimeUtc));
files.AddRange(memFiles);
}
return Task.FromResult<IReadOnlyList<MemoryFileInfo>>(files);
}
public async Task<IReadOnlyList<MemorySearchResult>> SearchAsync(string query)
{
var results = new List<MemorySearchResult>();
async Task SearchDir(string dir)
{
if (!Directory.Exists(dir)) return;
foreach (var file in Directory.GetFiles(dir, "*.md").Take(MaxFiles))
{
var fi = new FileInfo(file);
if (fi.Length > MaxFileSize) continue;
var content = await File.ReadAllTextAsync(file);
if (!content.Contains(query, StringComparison.OrdinalIgnoreCase)) continue;
var idx = content.IndexOf(query, StringComparison.OrdinalIgnoreCase);
var start = Math.Max(0, idx - 60);
var excerpt = (start > 0 ? "…" : "") + content.Substring(start, Math.Min(200, content.Length - start)) + "…";
results.Add(new MemorySearchResult(
Path.GetFileName(file),
file.Replace(BasePath, "").TrimStart('/'),
excerpt,
fi.Length));
}
}
await SearchDir(BasePath);
if (File.Exists(LongTermPath))
{
var content = await File.ReadAllTextAsync(LongTermPath);
if (content.Contains(query, StringComparison.OrdinalIgnoreCase))
{
var idx = content.IndexOf(query, StringComparison.OrdinalIgnoreCase);
var start = Math.Max(0, idx - 60);
var excerpt = (start > 0 ? "…" : "") + content.Substring(start, Math.Min(200, content.Length - start)) + "…";
results.Insert(0, new MemorySearchResult("MEMORY.md", "MEMORY.md", excerpt, content.Length));
}
}
return results;
}
public async Task<MemoryFileContent?> GetFileAsync(string name)
{
string? filePath;
if (name.Equals("MEMORY.md", StringComparison.OrdinalIgnoreCase))
{
filePath = LongTermPath;
}
else
{
if (!PathSecurityHelper.TryResolveSafePath(BasePath, name, out filePath))
return null;
}
if (!File.Exists(filePath!))
return null;
var content = await File.ReadAllTextAsync(filePath!);
return new MemoryFileContent(name, name, content, content.Length, File.GetLastWriteTimeUtc(filePath!));
}
}
+61
View File
@@ -0,0 +1,61 @@
using Microsoft.EntityFrameworkCore;
using Nexus.Api.Data;
using Nexus.Api.Models;
namespace Nexus.Api.Services;
public sealed class NotificationService(NexusDbContext db) : INotificationService
{
public async Task<Notification> CreateAsync(string type, string title, string? message, string forUser, Guid? taskId = null, CancellationToken ct = default)
{
var notification = new Notification
{
Type = type,
Title = title,
Message = message,
ForUser = forUser.ToLowerInvariant(),
TaskId = taskId
};
db.Notifications.Add(notification);
await db.SaveChangesAsync(ct);
return notification;
}
public async Task<IReadOnlyList<Notification>> GetForUserAsync(string forUser, int limit = 50, bool unreadOnly = false, CancellationToken ct = default)
{
var query = db.Notifications
.Where(n => n.ForUser == forUser.ToLowerInvariant());
if (unreadOnly)
query = query.Where(n => !n.IsRead);
return await query
.OrderByDescending(n => n.CreatedAt)
.Take(limit)
.ToListAsync(ct);
}
public async Task<bool> MarkAsReadAsync(Guid id, CancellationToken ct = default)
{
var notification = await db.Notifications.FindAsync([id], ct);
if (notification is null) return false;
notification.IsRead = true;
await db.SaveChangesAsync(ct);
return true;
}
public async Task<int> MarkAllAsReadAsync(string forUser, CancellationToken ct = default)
{
var count = await db.Notifications
.Where(n => n.ForUser == forUser.ToLowerInvariant() && !n.IsRead)
.ExecuteUpdateAsync(s => s.SetProperty(n => n.IsRead, true), ct);
return count;
}
public async Task<int> GetUnreadCountAsync(string forUser, CancellationToken ct = default)
{
return await db.Notifications
.CountAsync(n => n.ForUser == forUser.ToLowerInvariant() && !n.IsRead, ct);
}
}
+811 -61
View File
@@ -6,7 +6,7 @@ using Nexus.Api.Models;
namespace Nexus.Api.Services; namespace Nexus.Api.Services;
public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration configuration) public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration configuration) : IOpenClawGatewayClient
{ {
private static readonly JsonSerializerOptions JsonOptions = new() private static readonly JsonSerializerOptions JsonOptions = new()
{ {
@@ -61,84 +61,351 @@ public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration
} }
} }
public async Task<List<DashboardAgentInfo>> GetAgentsAsync() /// <summary>
{ /// Reads the agent session status from the Gateway via session_status tool.
var agentDefs = new[] /// Returns fields like model, provider, status, lastActivity, isActive, currentTask.
{ /// Returns null if the session is unreachable.
new { Id = "iris", Name = "Chief of Staff", Model = "deepseek/deepseek-v4-flash", /// </summary>
Description = "Zentrale operative Führungsinstanz. Strukturiert Aufgaben, bewertet Risiken, steuert spezialisierte Agenten und eskaliert kritische Entscheidungen.", private async Task<JsonNode?> TryGetAgentStatusAsync(string agentId)
Tags = new[] { "Orchestration", "Delegation", "Approval", "Risk Management" } },
new { Id = "programmer", Name = "Full-Stack Developer", Model = "deepseek/deepseek-v4-flash",
Description = "Primärer Entwicklungsagent. Implementiert Features, behebt Bugs und schreibt Code im gesamten Stack — autonom im Rahmen seines Scopes.",
Tags = new[] { "Full-Stack", "TypeScript", "C#", "Vue", ".NET", "Builds" } },
new { Id = "reviewer", Name = "Code Quality Assurance", Model = "deepseek/deepseek-v4-pro",
Description = "Code-Qualitätskontrolle. Prüft Diffs auf Bugs, Regressionen, Sicherheitslücken und Wartbarkeit. Berichtet Findings strukturiert und knapp.",
Tags = new[] { "Code Review", "Testing", "Security", "Quality" } },
new { Id = "architekt", Name = "Infrastructure Architect", Model = "deepseek/deepseek-v4-pro",
Description = "Verwaltet die gesamte Server-Infrastruktur. Deployt Services, konfiguriert Docker, Nginx und Firewall. Stellt sicher, dass die Produktivumgebung stabil und sicher läuft.",
Tags = new[] { "Docker", "Nginx", "CI/CD", "Firewall", "VPS" } },
new { Id = "executor", Name = "Host Executor", Model = "deepseek/deepseek-v4-flash",
Description = "Einziger Agent mit Host-Exec-Rechten. Führt Docker- und Shell-Befehle auf dem VPS aus — ausschließlich im Auftrag von Iris. Handelt niemals eigeninitiativ.",
Tags = new[] { "Docker", "Shell", "Host", "Deployment" } },
new { Id = "researcher", Name = "Research & Analysis", Model = "deepseek/deepseek-v4-pro",
Description = "Spezialisierter Recherche-Agent. Sucht online, prüft Quellen, analysiert Inhalte (inkl. YouTube-Videos) und übergibt strukturierte Erkenntnisse. Ausschließlich Lese- und Analyse-Rechte.",
Tags = new[] { "Research", "Quellenprüfung", "Analyse", "Docs" } },
};
var agents = new List<DashboardAgentInfo>();
foreach (var def in agentDefs)
{
var isActive = false;
string? currentTask = null;
try
{
var memDir = "/mnt/workspace-" + def.Id + "/memory";
if (Directory.Exists(memDir))
{
var latestFile = Directory.GetFiles(memDir, "*", SearchOption.AllDirectories)
.Select(f => new FileInfo(f))
.OrderByDescending(f => f.LastWriteTimeUtc)
.FirstOrDefault();
if (latestFile is not null)
{
var age = DateTime.UtcNow - latestFile.LastWriteTimeUtc;
isActive = age.TotalMinutes < 15;
if (isActive)
{ {
try try
{ {
var firstLine = File.ReadLines(latestFile.FullName).FirstOrDefault()?.Trim(); return await InvokeToolAsync("session_status", new { sessionKey = "agent:" + agentId + ":main" });
if (!string.IsNullOrWhiteSpace(firstLine) && firstLine.Length > 60)
currentTask = firstLine[..60];
else if (!string.IsNullOrWhiteSpace(firstLine))
currentTask = firstLine;
else
currentTask = "Working...";
} }
catch catch
{ {
currentTask = "Working..."; return null;
} }
} }
public async Task<List<DashboardAgentInfo>> GetAgentsAsync()
{
// Fallback hardcoded descriptions and tags known for each agent
var knownInfo = new Dictionary<string, (string Name, string Description, string[] Tags)>
{
["iris"] = (
"Iris",
"Zentrale operative Führungsinstanz. Strukturiert Aufgaben, bewertet Risiken, steuert spezialisierte Agenten und eskaliert kritische Entscheidungen.",
new[] { "Orchestration", "Delegation", "Approval", "Risk Management" }
),
["programmer"] = (
"Full-Stack Developer",
"Primärer Entwicklungsagent. Implementiert Features, behebt Bugs und schreibt Code im gesamten Stack — autonom im Rahmen seines Scopes.",
new[] { "Full-Stack", "TypeScript", "C#", "Vue", ".NET", "Builds" }
),
["reviewer"] = (
"Code Quality Assurance",
"Code-Qualitätskontrolle. Prüft Diffs auf Bugs, Regressionen, Sicherheitslücken und Wartbarkeit. Berichtet Findings strukturiert und knapp.",
new[] { "Code Review", "Testing", "Security", "Quality" }
),
["architekt"] = (
"Infrastructure Architect",
"Verwaltet die gesamte Server-Infrastruktur. Deployt Services, konfiguriert Docker, Nginx und Firewall. Stellt sicher, dass die Produktivumgebung stabil und sicher läuft.",
new[] { "Docker", "Nginx", "CI/CD", "Firewall", "VPS" }
),
["executor"] = (
"Host Executor",
"Einziger Agent mit Host-Exec-Rechten. Führt Docker- und Shell-Befehle auf dem VPS aus — ausschließlich im Auftrag von Iris. Handelt niemals eigeninitiativ.",
new[] { "Docker", "Shell", "Host", "Deployment" }
),
["researcher"] = (
"Research & Analysis",
"Spezialisierter Recherche-Agent. Sucht online, prüft Quellen, analysiert Inhalte (inkl. YouTube-Videos) und übergibt strukturierte Erkenntnisse. Ausschließlich Lese- und Analyse-Rechte.",
new[] { "Research", "Quellenprüfung", "Analyse", "Docs" }
)
};
// Load agent IDs from openclaw.json config
var agentIds = LoadAgentIdsFromConfig();
var agents = new List<DashboardAgentInfo>();
// Read queue once for workload calculation
var queueItems = new List<QueueItem>();
try { queueItems = await GetQueueAsync(); } catch { }
foreach (var id in agentIds)
{
// Skip the "main" agent (it's the default assistant, not a sub-agent)
if (string.Equals(id, "main", StringComparison.OrdinalIgnoreCase))
continue;
// 1. Try to get dynamic session status from Gateway
var status = await TryGetAgentStatusAsync(id);
// 2. Extract model from session_status (dynamic)
var model = status?["model"]?.GetValue<string>();
// 3. Extract activity from session_status
var isActive = false;
string? currentTask = null;
if (status is not null)
{
// Check explicit isActive field
var activeVal = status["isActive"];
if (activeVal is not null && activeVal.GetValueKind() == JsonValueKind.True)
isActive = true;
else if (activeVal is not null && activeVal.GetValueKind() == JsonValueKind.String)
isActive = string.Equals(activeVal.GetValue<string>(), "true", StringComparison.OrdinalIgnoreCase);
// Fall back to status text
var statusText = status["status"]?.GetValue<string>();
if (!isActive && statusText is not null)
isActive = string.Equals(statusText, "active", StringComparison.OrdinalIgnoreCase)
|| string.Equals(statusText, "running", StringComparison.OrdinalIgnoreCase);
currentTask = status["currentTask"]?.GetValue<string>()
?? status["task"]?.GetValue<string>()
?? (isActive ? "Working..." : null);
} }
// 4. Try to read workspace metadata for richer info
var (name, description, tags) = await ReadAgentMetadataAsync(id);
// 5. Fallback to known info if workspace metadata not available
if (string.IsNullOrWhiteSpace(name) && knownInfo.TryGetValue(id, out var kn))
{
name = kn.Name;
if (string.IsNullOrWhiteSpace(description))
description = kn.Description;
if (tags.Length == 0)
tags = kn.Tags;
} }
if (string.IsNullOrWhiteSpace(model))
{
model = id.ToLowerInvariant() switch
{
"iris" or "programmer" or "executor" => "deepseek/deepseek-v4-flash",
"reviewer" or "architekt" or "researcher" => "deepseek/deepseek-v4-pro",
_ => "deepseek/deepseek-v4-flash"
};
} }
catch { }
// 6. Read goal from workspace files
var goal = await ReadAgentGoalAsync(id);
// 7. Calculate progress dynamically
var progress = CalculateAgentProgress(id, isActive, status);
// 8. Calculate workload from queue items
var workload = CalculateAgentWorkload(id, queueItems);
agents.Add(new DashboardAgentInfo( agents.Add(new DashboardAgentInfo(
Id: def.Id, Id: id,
Name: def.Name, Name: string.IsNullOrWhiteSpace(name) ? DeriveRole(id) : name,
Role: DeriveRole(def.Id), Role: DeriveRole(id),
Model: def.Model, Model: model,
IsActive: isActive, IsActive: isActive,
CurrentTask: currentTask, CurrentTask: currentTask,
Description: def.Description, Description: description,
Tags: def.Tags Tags: tags,
Progress: progress,
Workload: workload,
Goal: goal,
RoleBadge: DeriveRoleBadge(id),
StatusLabel: DeriveStatusLabel(isActive, status),
Elapsed: FormatElapsed(status),
Think: null,
Next: DeriveNext(isActive, currentTask)
)); ));
} }
return agents; return agents;
} }
/// <summary>
/// Loads agent IDs from the OpenClaw config file (openclaw.json).
/// Falls back to the known list if the config file is unavailable.
/// </summary>
private List<string> LoadAgentIdsFromConfig()
{
try
{
var configPath = configuration.GetValue<string>("AgentConfigPath")
?? "/home/node/.openclaw/openclaw.json";
if (!System.IO.File.Exists(configPath))
return GetDefaultAgentIds();
var json = System.IO.File.ReadAllText(configPath);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (!root.TryGetProperty("agents", out var agentsEl))
return GetDefaultAgentIds();
if (!agentsEl.TryGetProperty("list", out var listEl))
return GetDefaultAgentIds();
var ids = new List<string>();
foreach (var agentEl in listEl.EnumerateArray())
{
if (agentEl.TryGetProperty("id", out var idEl))
{
var id = idEl.GetString();
if (!string.IsNullOrWhiteSpace(id))
ids.Add(id);
}
}
return ids.Count > 0 ? ids : GetDefaultAgentIds();
}
catch
{
return GetDefaultAgentIds();
}
}
private static List<string> GetDefaultAgentIds()
=> new() { "iris", "programmer", "reviewer", "architekt", "executor", "researcher" };
/// <summary>
/// Reads agent metadata from workspace files (IDENTITY.md, SOUL.md).
/// Returns (Name, Description, Tags) — empty strings/arrays if unavailable.
/// Tags are not read from files (kept as empty for dynamic agents).
/// </summary>
private async Task<(string Name, string Description, string[] Tags)> ReadAgentMetadataAsync(string agentId)
{
var name = string.Empty;
var description = string.Empty;
var tags = Array.Empty<string>();
try
{
// Try the host-mounted workspace path (used by the API container)
var workspacePath = "/mnt/workspace-" + agentId;
var identityPath = Path.Combine(workspacePath, "IDENTITY.md");
if (System.IO.File.Exists(identityPath))
{
var content = await System.IO.File.ReadAllTextAsync(identityPath);
ParseIdentityContent(content, out name, out description);
}
else
{
// Fallback: try the OpenClaw workspace path inside the gateway container
var altPath = "/home/node/.openclaw/workspace-" + agentId + "/IDENTITY.md";
if (System.IO.File.Exists(altPath))
{
var content = await System.IO.File.ReadAllTextAsync(altPath);
ParseIdentityContent(content, out name, out description);
}
}
// If description is still empty, try SOUL.md
if (string.IsNullOrWhiteSpace(description))
{
var soulPath = Path.Combine(workspacePath, "SOUL.md");
string? soulContent = null;
if (System.IO.File.Exists(soulPath))
{
soulContent = await System.IO.File.ReadAllTextAsync(soulPath);
}
else
{
var altSoulPath = "/home/node/.openclaw/workspace-" + agentId + "/SOUL.md";
if (System.IO.File.Exists(altSoulPath))
{
soulContent = await System.IO.File.ReadAllTextAsync(altSoulPath);
}
}
if (soulContent is not null)
{
description = ExtractDescriptionFromSoul(soulContent);
}
}
}
catch
{
// Fallback to hardcoded values will handle this
}
return (name, description, tags);
}
/// <summary>
/// Parses an IDENTITY.md file to extract Name and a short description (role/creature).
/// Looks for markdown list items like "- **Name:** ...", "- **Rolle:** ...", etc.
/// </summary>
private static void ParseIdentityContent(string content, out string name, out string description)
{
name = string.Empty;
description = string.Empty;
using var reader = new StringReader(content);
string? line;
while ((line = reader.ReadLine()) is not null)
{
// Extract name from "- **Name:** ..."
if (string.IsNullOrWhiteSpace(name))
{
var nameMarker = "- **Name:**";
var idx = line.IndexOf(nameMarker, StringComparison.OrdinalIgnoreCase);
if (idx >= 0)
{
name = line[(idx + nameMarker.Length)..].Trim();
continue;
}
}
// Extract role/theme from "- **Rolle:** ..." or "- **Role:** ..." or "- **Creature:** ..."
if (string.IsNullOrWhiteSpace(description))
{
var descMarkers = new[] { "- **Rolle:**", "- **Role:**", "- **Creature:**" };
foreach (var marker in descMarkers)
{
var idx = line.IndexOf(marker, StringComparison.OrdinalIgnoreCase);
if (idx >= 0)
{
description = line[(idx + marker.Length)..].Trim();
break;
}
}
}
}
}
/// <summary>
/// Extracts a short description from SOUL.md (first heading or first paragraph after the "Rolle" section).
/// Returns the first ~200 characters of meaningful content.
/// </summary>
private static string ExtractDescriptionFromSoul(string content)
{
// Look for "## Rolle" section and take the first paragraph after it
using var reader = new StringReader(content);
string? line;
var inRoleSection = false;
var paragraphs = new List<string>();
while ((line = reader.ReadLine()) is not null)
{
var trimmed = line.Trim();
if (trimmed.StartsWith("## ", StringComparison.OrdinalIgnoreCase))
{
if (inRoleSection)
break; // We've moved past the "Rolle" section
if (trimmed.IndexOf("Rolle", StringComparison.OrdinalIgnoreCase) >= 0
|| trimmed.IndexOf("Role", StringComparison.OrdinalIgnoreCase) >= 0)
{
inRoleSection = true;
}
continue;
}
if (inRoleSection && !string.IsNullOrWhiteSpace(trimmed))
{
paragraphs.Add(trimmed);
if (paragraphs.Count >= 3)
break;
}
}
var summary = string.Join(" ", paragraphs);
return summary.Length > 200 ? summary[..200] + "…" : summary;
}
public async Task<List<MessageEntry>> GetSessionHistoryAsync( public async Task<List<MessageEntry>> GetSessionHistoryAsync(
string sessionKey, int limit = 50, int offset = 0) string sessionKey, int limit = 50, int offset = 0)
{ {
@@ -153,7 +420,7 @@ public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration
if (toolResult is null) if (toolResult is null)
return result; return result;
var json = toolResult.ToJsonString(); result.Add(new MessageEntry("diag", "JSON[" + json.Substring(0, Math.Min(200, json.Length)) + "]", DateTimeOffset.UtcNow.ToString("o"))); var json = toolResult.ToJsonString();
using var doc = JsonDocument.Parse(json); using var doc = JsonDocument.Parse(json);
var root = doc.RootElement; var root = doc.RootElement;
@@ -214,6 +481,138 @@ public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration
return result; return result;
} }
/// <summary>
/// Collects assistant messages from ALL agent sessions (multi-agent operations feed).
/// Merges, sorts by timestamp descending, and limits the result.
/// Falls back to an empty list if any agent session is unreachable.
/// </summary>
public async Task<List<FeedEntry>> GetAllAgentOperationsAsync(int limit = 30)
{
var allEntries = new List<FeedEntry>();
var agentIds = LoadAgentIdsFromConfig();
foreach (var agentId in agentIds)
{
try
{
var sessionKey = $"agent:{agentId}:main";
var messages = await GetSessionHistoryAsync(sessionKey, Math.Min(limit * 2, 50));
foreach (var msg in messages)
{
if (!string.Equals(msg.Role, "assistant", StringComparison.OrdinalIgnoreCase))
continue;
if (string.IsNullOrWhiteSpace(msg.Content))
continue;
// Parse timestamp
var ts = ParseTimestamp(msg.Timestamp);
var timeAgo = FormatTimeAgo(ts);
// Extract a short agent indicator and action from content
var (agent, action) = ExtractAgentAction(msg.Content);
// Determine event type based on content heuristics
var eventType = DetectEventType(msg.Content);
allEntries.Add(new FeedEntry(
agent,
action,
msg.Timestamp,
timeAgo,
AgentId: agentId,
Type: eventType
));
}
}
catch
{
// Agent session unreachable — skip; we still have data from other agents
}
}
// Sort descending by timestamp, then limit
return allEntries
.OrderByDescending(e => ParseTimestamp(e.Timestamp))
.Take(Math.Clamp(limit, 1, 100))
.ToList();
}
private static DateTimeOffset ParseTimestamp(string timestamp)
{
if (DateTimeOffset.TryParse(timestamp, null, System.Globalization.DateTimeStyles.None, out var dt))
return dt;
return DateTimeOffset.UtcNow;
}
private static string FormatTimeAgo(DateTimeOffset ts)
{
var diff = DateTimeOffset.UtcNow - ts;
if (diff.TotalMinutes < 1) return "just now";
if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m ago";
if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h ago";
if (diff.TotalDays < 7) return $"{(int)diff.TotalDays}d ago";
return ts.ToString("MMM dd");
}
/// <summary>
/// Determines a FeedEntry event type from message content heuristics.
/// </summary>
private static string DetectEventType(string content)
{
if (content.Contains("Subagent Task") || content.Contains("subagent"))
{
if (content.Contains("complete") || content.Contains("done") || content.Contains("finished"))
return "task_complete";
return "task_start";
}
if (content.Contains("Deploy") || content.Contains("deploy") || content.Contains("publish"))
return "deploy";
if (content.Contains("System") || content.Contains("system") || content.Contains("health"))
return "system";
if (content.Contains("Gestartet") || content.Contains("started") || content.Contains("Session"))
return "session_start";
return "chat";
}
/// <summary>
/// Extracts a human-readable agent name and action summary from message content.
/// </summary>
private static (string Agent, string Action) ExtractAgentAction(string content)
{
// Take first line or first ~80 chars as the action summary
var firstLine = content.Split('\n', 2)[0].Trim();
var summary = firstLine.Length > 80 ? firstLine[..80] + "\u2026" : firstLine;
// Try to identify which agent this came from
var agent = "Iris";
foreach (var marker in new[] { "**Agent:**", "**Agent:** ", "*Agent:* ", "Agent:" })
{
var idx = content.IndexOf(marker, StringComparison.OrdinalIgnoreCase);
if (idx >= 0)
{
var after = content[(idx + marker.Length)..].TrimStart();
var end = after.IndexOfAny(['\n', '\r', ',', '.']);
var found = end > 0 ? after[..end].Trim() : after.Split('\n', 2)[0].Trim();
if (!string.IsNullOrWhiteSpace(found) && found.Length < 30)
{
agent = found;
break;
}
}
}
// Try to find agent name at the start in brackets like [Agent: Iris]
if (agent == "Iris")
{
var bracketMatch = System.Text.RegularExpressions.Regex.Match(content, @"\[Agent:\s*([^\]]+)\]");
if (bracketMatch.Success)
agent = bracketMatch.Groups[1].Value.Trim();
}
return (agent, summary);
}
public async Task<ChatResponse> SendChatMessageAsync(string agentId, string message) public async Task<ChatResponse> SendChatMessageAsync(string agentId, string message)
{ {
try try
@@ -262,7 +661,28 @@ public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration
var status = j["state"]?["lastStatus"]?.GetValue<string>() var status = j["state"]?["lastStatus"]?.GetValue<string>()
?? j["status"]?.GetValue<string>() ?? j["status"]?.GetValue<string>()
?? "unknown"; ?? "unknown";
items.Add(new QueueItem(id, name, status));
// Calculate waitTime from nextRun if available
var waitTime = "--";
var nextRunStr = j["nextRun"]?.GetValue<string>()
?? j["next_run"]?.GetValue<string>()
?? j["scheduledAt"]?.GetValue<string>();
if (nextRunStr is not null && DateTimeOffset.TryParse(nextRunStr, out var nextRun))
{
var diff = nextRun - DateTimeOffset.UtcNow;
if (diff.TotalMinutes < 0)
waitTime = "now";
else if (diff.TotalMinutes < 1)
waitTime = "<1m";
else if (diff.TotalMinutes < 60)
waitTime = $"{(int)diff.TotalMinutes}m";
else if (diff.TotalHours < 24)
waitTime = $"{(int)diff.TotalHours}h";
else
waitTime = $"{(int)diff.TotalDays}d";
}
items.Add(new QueueItem(id, name, status, "medium", "cron", waitTime));
} }
return items; return items;
} }
@@ -272,6 +692,19 @@ public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration
} }
} }
public async Task<bool> DeleteCronJobAsync(string id)
{
try
{
var result = await InvokeToolAsync("cron", new { action = "delete", id });
return result is not null;
}
catch
{
return false;
}
}
public async Task<DashboardStatus> GetStatusAsync() public async Task<DashboardStatus> GetStatusAsync()
{ {
var gatewayOk = false; var gatewayOk = false;
@@ -359,6 +792,323 @@ public sealed class OpenClawGatewayClient(HttpClient httpClient, IConfiguration
} }
} }
/// <summary>
/// Reads the agent's goal from workspace files (goals.md preferred, then AGENTS.md, SOUL.md).
/// Returns the first meaningful line or null.
/// </summary>
private async Task<string?> ReadAgentGoalAsync(string agentId)
{
try
{
var workspacePath = "/home/node/.openclaw/workspace-" + agentId;
// 1. Try goals.md first
var goalsPath = Path.Combine(workspacePath, "goals.md");
if (System.IO.File.Exists(goalsPath))
{
var content = await System.IO.File.ReadAllTextAsync(goalsPath);
foreach (var line in content.Split('\n'))
{
var trimmed = line.Trim();
if (!string.IsNullOrWhiteSpace(trimmed) && !trimmed.StartsWith('#') && !trimmed.StartsWith('-'))
return trimmed.Length > 120 ? trimmed[..117] + "..." : trimmed;
}
}
// 2. Try SOUL.md "## Rolle" section
var soulPath = Path.Combine(workspacePath, "SOUL.md");
if (System.IO.File.Exists(soulPath))
{
var soul = await System.IO.File.ReadAllTextAsync(soulPath);
using var reader = new StringReader(soul);
string? line;
var inRoleSection = false;
while ((line = reader.ReadLine()) is not null)
{
var trimmed = line.Trim();
if (trimmed.StartsWith("## ", StringComparison.OrdinalIgnoreCase))
{
if (inRoleSection) break;
if (trimmed.IndexOf("Rolle", StringComparison.OrdinalIgnoreCase) >= 0
|| trimmed.IndexOf("Role", StringComparison.OrdinalIgnoreCase) >= 0
|| trimmed.IndexOf("Oberstes", StringComparison.OrdinalIgnoreCase) >= 0)
{
inRoleSection = true;
}
continue;
}
if (inRoleSection && !string.IsNullOrWhiteSpace(trimmed) && !trimmed.StartsWith('-'))
{
return trimmed.Length > 120 ? trimmed[..117] + "..." : trimmed;
}
}
// 3. Look for "## Oberstes Prinzip" as second choice
inRoleSection = false;
using var reader2 = new StringReader(soul);
while ((line = reader2.ReadLine()) is not null)
{
var trimmed = line.Trim();
if (trimmed.StartsWith("## ") && trimmed.IndexOf("Prinzip", StringComparison.OrdinalIgnoreCase) >= 0)
{
inRoleSection = true;
continue;
}
if (inRoleSection && !string.IsNullOrWhiteSpace(trimmed) && !trimmed.StartsWith('-') && !trimmed.StartsWith('#'))
{
return trimmed.Length > 120 ? trimmed[..117] + "..." : trimmed;
}
}
}
// 4. Try AGENTS.md first heading
var agentsPath = Path.Combine(workspacePath, "AGENTS.md");
if (System.IO.File.Exists(agentsPath))
{
var agentsContent = await System.IO.File.ReadAllTextAsync(agentsPath);
foreach (var line in agentsContent.Split('\n'))
{
var trimmed = line.Trim();
if (trimmed.StartsWith("# "))
return trimmed[2..].Trim();
}
}
}
catch
{
// Fallback to hardcoded
}
// Fallback: known goals
return agentId.ToLowerInvariant() switch
{
"iris" => "Mission Control — maximale Autonomie bei kontrolliertem Risiko",
"programmer" => "Nexus Dashboard & Dungeon System",
"reviewer" => "Zero critical findings before merge",
"architekt" => "Stabile Zero-Downtime-Deployments",
"executor" => "Sichere Host-Execution im Allowlist-Rahmen",
"researcher" => "Verifizierte, strukturierte Recherche-Ergebnisse",
_ => null
};
}
/// <summary>
/// Calculates agent progress (0-100) based on session activity.
/// Active agents with recent activity get higher scores.
/// Idle agents or inactive sessions get lower scores.
/// </summary>
private static int CalculateAgentProgress(string agentId, bool isActive, JsonNode? status)
{
if (!isActive)
return 0;
// Base progress from active status
var progress = 50;
// Boost for agents that have a current task
var hasTask = status?["currentTask"]?.GetValue<string>() is not null
|| status?["task"]?.GetValue<string>() is not null;
if (hasTask)
progress += 20;
// Check for last activity timestamp — more recent = higher progress
var lastActivity = status?["lastActivity"]?.GetValue<string>()
?? status?["lastMessage"]?.GetValue<string>();
if (lastActivity is not null && DateTimeOffset.TryParse(lastActivity, out var lastTs))
{
var minutesSinceActivity = (DateTimeOffset.UtcNow - lastTs).TotalMinutes;
if (minutesSinceActivity < 1)
progress += 25; // actively working
else if (minutesSinceActivity < 5)
progress += 15;
else if (minutesSinceActivity < 15)
progress += 10;
else
progress -= 10; // stale
}
else if (hasTask)
{
// Has task but no timestamp — assume actively working
progress += 15;
}
return Math.Clamp(progress, 0, 100);
}
/// <summary>
/// Calculates agent workload (0-100) based on queue items and active status.
/// More queued tasks or active sessions = higher workload.
/// </summary>
private static int CalculateAgentWorkload(string agentId, List<QueueItem> queueItems)
{
if (queueItems.Count == 0)
return 0;
// Calculate workload based on queue density per agent
var agentQueued = queueItems.Count(q =>
q.Name.Contains(agentId, StringComparison.OrdinalIgnoreCase)
|| q.Id.Contains(agentId, StringComparison.OrdinalIgnoreCase));
// Base workload from total queue pressure
var totalQueuePressure = Math.Min(queueItems.Count * 10, 60);
// Agent-specific queue items add extra weight
var agentPressure = agentQueued * 25;
return Math.Clamp(totalQueuePressure + agentPressure, 0, 100);
}
/// <summary>
/// Fetches the most recent assistant activity (last N messages) for a specific agent.
/// Returns entries with timestamp and truncated content text.
/// Falls back to an empty list if the session is unreachable.
/// </summary>
public async Task<List<AgentActivityEntry>> GetAgentActivityAsync(string agentId, int limit = 5)
{
var entries = new List<AgentActivityEntry>();
try
{
var sessionKey = $"agent:{agentId}:main";
var messages = await GetSessionHistoryAsync(sessionKey, Math.Clamp(limit * 2, 1, 100));
foreach (var msg in messages)
{
if (!string.Equals(msg.Role, "assistant", StringComparison.OrdinalIgnoreCase))
continue;
if (string.IsNullOrWhiteSpace(msg.Content))
continue;
if (msg.Content == "REPLY_SKIP" || msg.Content == "ANNOUNCE_SKIP")
continue;
// Truncate content to first 200 chars for compact display
var text = msg.Content.Length > 200
? msg.Content[..200] + "…"
: msg.Content;
var ts = ParseTimestamp(msg.Timestamp);
var timeAgo = FormatTimeAgo(ts);
entries.Add(new AgentActivityEntry(timeAgo, text));
}
}
catch
{
// Return empty list if gateway is unreachable
}
return entries.Take(Math.Clamp(limit, 1, 20)).ToList();
}
/// <summary>
/// Returns the list of available models by reading from the OpenClaw config,
/// with fallback to hardcoded list.
/// </summary>
public List<ModelOption> GetAvailableModels()
{
try
{
var configPath = configuration.GetValue<string>("AgentConfigPath")
?? "/home/node/.openclaw/openclaw.json";
if (!System.IO.File.Exists(configPath))
return GetDefaultModels();
var json = System.IO.File.ReadAllText(configPath);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
// Read models from agents.defaults.models
if (!root.TryGetProperty("agents", out var agentsEl))
return GetDefaultModels();
if (!agentsEl.TryGetProperty("defaults", out var defaultsEl))
return GetDefaultModels();
if (!defaultsEl.TryGetProperty("models", out var modelsEl))
return GetDefaultModels();
var models = new List<ModelOption>();
foreach (var modelProp in modelsEl.EnumerateObject())
{
var modelId = modelProp.Name;
var modelObj = modelProp.Value;
var name = modelId; // fallback: use model ID as name
var provider = ExtractProvider(modelId);
// Check for alias in the model object
if (modelObj.TryGetProperty("alias", out var aliasEl))
{
var alias = aliasEl.GetString();
if (!string.IsNullOrWhiteSpace(alias))
name = alias;
}
models.Add(new ModelOption(modelId, name, provider));
}
return models.Count > 0 ? models : GetDefaultModels();
}
catch
{
return GetDefaultModels();
}
}
private static List<ModelOption> GetDefaultModels()
=> new()
{
new ModelOption("openai/gpt-5.4", "GPT-5.4", "openai"),
new ModelOption("openai/gpt-5.5", "GPT-5.5", "openai"),
new ModelOption("deepseek/deepseek-v4-flash", "DeepSeek V4 Flash", "deepseek"),
new ModelOption("deepseek/deepseek-v4-pro", "DeepSeek V4 Pro", "deepseek")
};
private static string ExtractProvider(string modelId)
{
var slash = modelId.IndexOf('/');
return slash > 0 ? modelId[..slash] : "unknown";
}
private static string DeriveRoleBadge(string agentId) => agentId.ToLowerInvariant() switch
{
"iris" => "badge-purple",
"programmer" or "developer" => "badge-blue",
"reviewer" => "badge-amber",
"architekt" => "badge-cyan",
"executor" => "badge-rose",
"researcher" => "badge-green",
_ => "badge-slate"
};
private static string DeriveStatusLabel(bool isActive, JsonNode? status)
{
if (!isActive) return "Bereit";
var statusText = status?["status"]?.GetValue<string>()?.ToLowerInvariant();
return statusText switch
{
"thinking" or "think" => "Plant",
"blocked" or "block" => "Blockiert",
_ => "Arbeitet"
};
}
private static string? FormatElapsed(JsonNode? status)
{
var lastActivity = status?["lastActivity"]?.GetValue<string>()
?? status?["lastMessage"]?.GetValue<string>();
if (lastActivity is null) return null;
if (!DateTimeOffset.TryParse(lastActivity, out var ts)) return null;
var diff = DateTimeOffset.UtcNow - ts;
if (diff.TotalSeconds < 60) return $"{(int)diff.TotalSeconds}s";
if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m";
if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h";
return $"{(int)diff.TotalDays}d";
}
private static string DeriveNext(bool isActive, string? currentTask)
{
if (!isActive) return "Standby";
if (!string.IsNullOrWhiteSpace(currentTask) && currentTask != "Working...")
return currentTask.Length > 60 ? currentTask[..60] + "…" : currentTask;
return "Aufgabe ausführen";
}
private static string DeriveRole(string agentId) => agentId.ToLowerInvariant() switch private static string DeriveRole(string agentId) => agentId.ToLowerInvariant() switch
{ {
"iris" => "Chief of Staff", "iris" => "Chief of Staff",
+59
View File
@@ -0,0 +1,59 @@
using Nexus.Api.Data;
using Nexus.Api.Integrations;
using Nexus.Api.Repositories;
namespace Nexus.Api.Services;
public sealed class OperationsService(
IAgentRuntime runtime,
IAgentService agentService,
IProjectRepository projectRepo,
ITaskRepository taskRepo,
IActivityRepository activityRepo) : IOperationsService
{
public async Task<object> GetSnapshotAsync(CancellationToken ct = default)
{
var runtimeTask = runtime.GetStatusAsync(ct);
var agentsTask = agentService.GetAgentsAsync(ct);
// Repository calls share the scoped EF Core DbContext and must stay serialized.
var projects = await projectRepo.GetAllAsync(ct);
var tasks = await taskRepo.GetAllAsync(ct);
var activity = await activityRepo.GetRecentAsync(20, ct);
var agents = await agentsTask;
var completedTasks = tasks.Count(x => x.State == TaskStateHelper.ToStateString(TaskState.Done));
var runtimeStatus = await runtimeTask;
var lastIncident = tasks
.Where(x => x.State == TaskStateHelper.ToStateString(TaskState.Blocked))
.OrderByDescending(x => x.UpdatedAt)
.Select(x => new { TaskId = (Guid?)x.Id, Title = (string?)x.Title, Since = (DateTimeOffset?)x.UpdatedAt })
.FirstOrDefault();
return new
{
generatedAt = DateTimeOffset.UtcNow,
runtime = runtimeStatus,
models = Array.Empty<object>(),
runtimeHealthy = runtimeStatus.Status == OperationalStatus.Online,
metrics = new
{
activeAgents = agents.Count,
queuedTasks = tasks.Count - completedTasks,
successRate = tasks.Count == 0 ? 100 : Math.Round(completedTasks * 100d / tasks.Count, 1),
incidents = tasks.Count(x => x.State == TaskStateHelper.ToStateString(TaskState.Blocked))
},
lastIncident,
projectHealth = new
{
Online = projects.Count(x => x.Status == OperationalStatus.Online),
Offline = projects.Count(x => x.Status == OperationalStatus.Offline),
Degraded = projects.Count(x => x.Status == OperationalStatus.Degraded),
Unknown = projects.Count(x => x.Status == OperationalStatus.Unknown)
},
agents = agents.Select(x => new { x.Id, x.Name, x.Role, x.Status, x.Model }),
projects = projects.Select(x => new { x.Id, x.Name, x.Status, x.Progress, x.UpdatedAt }),
tasks = tasks.Select(x => new { x.Id, x.Title, x.State, x.Priority, x.ProjectId, x.UpdatedAt }),
activity = activity.Select(x => new { x.Id, x.Type, x.Message, at = x.CreatedAt })
};
}
}
+64
View File
@@ -0,0 +1,64 @@
using Nexus.Api.Data;
using Nexus.Api.DTOs;
using Nexus.Api.Repositories;
namespace Nexus.Api.Services;
public sealed class ProjectService(
IProjectRepository projectRepo,
IActivityRepository activityRepo) : IProjectService
{
public async Task<IReadOnlyList<Project>> GetAllAsync(CancellationToken ct = default)
=> await projectRepo.GetAllAsync(ct);
public async Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default)
=> await projectRepo.GetByIdAsync(id, ct);
public async Task<Project> CreateAsync(CreateProjectRequest request, CancellationToken ct = default)
{
var project = new Project
{
Name = request.Name.Trim(),
Description = request.Description?.Trim() ?? string.Empty,
Status = OperationalStatus.Online
};
await projectRepo.AddAsync(project, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} created" }, ct);
return project;
}
public async Task<Project?> UpdateAsync(Guid id, UpdateProjectRequest request, CancellationToken ct = default)
{
var project = await projectRepo.GetByIdAsync(id, ct);
if (project is null) return null;
if (!string.IsNullOrWhiteSpace(request.Name))
project.Name = request.Name.Trim();
if (request.Description is not null)
project.Description = request.Description.Trim();
if (!string.IsNullOrWhiteSpace(request.Status) && Enum.TryParse<OperationalStatus>(request.Status, true, out var parsedStatus))
project.Status = parsedStatus;
await projectRepo.UpdateAsync(project, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} updated" }, ct);
return project;
}
public async Task<ProjectDeleteResult> DeleteAsync(Guid id, CancellationToken ct = default)
{
var project = await projectRepo.GetByIdAsync(id, ct);
if (project is null) return new ProjectDeleteResult(ProjectDeleteOutcome.NotFound);
if (await projectRepo.HasTasksAsync(id, ct))
{
project.Status = OperationalStatus.Offline;
await projectRepo.UpdateAsync(project, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} archived" }, ct);
return new ProjectDeleteResult(ProjectDeleteOutcome.Archived, project);
}
await activityRepo.AddAsync(new ActivityEvent { Type = "project", Message = $"Project {project.Name} deleted" }, ct);
await projectRepo.DeleteAsync(project, ct);
return new ProjectDeleteResult(ProjectDeleteOutcome.Deleted);
}
}
+642
View File
@@ -0,0 +1,642 @@
using Nexus.Api.Data;
using Nexus.Api.DTOs;
using Nexus.Api.Models;
using Nexus.Api.Repositories;
namespace Nexus.Api.Services;
public sealed class TaskService(
ITaskRepository taskRepo,
IActivityRepository activityRepo,
INotificationService notificationService,
IHttpContextAccessor httpContextAccessor) : ITaskService
{
private static readonly HashSet<string> ValidAssignees =
["bao", "iris", "programmer", "reviewer", "architekt", "researcher", "executor"];
public async Task<IReadOnlyList<WorkTask>> GetAllAsync(CancellationToken ct = default)
=> await taskRepo.GetAllAsync(ct);
public async Task<WorkTask?> GetByIdAsync(Guid id, CancellationToken ct = default)
=> await taskRepo.GetByIdAsync(id, ct);
public async Task<DashboardTaskDto?> GetDashboardTaskByIdAsync(Guid id, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return null;
var activity = await activityRepo.GetRecentForTasksAsync([task.Id], ct);
return MapToDtoWithActivity(task, activity);
}
public async Task<IReadOnlyList<WorkTask>> GetPendingApprovalAsync(CancellationToken ct = default)
=> await taskRepo.GetPendingApprovalAsync(ct);
public async Task<WorkTask> CreateAsync(CreateTaskRequest request, CancellationToken ct = default)
{
var task = new WorkTask
{
Title = request.Title.Trim(),
Priority = string.IsNullOrWhiteSpace(request.Priority) ? "Normal" : request.Priority.Trim(),
ProjectId = request.ProjectId
};
await taskRepo.AddAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} created", TaskId = task.Id }, ct);
return task;
}
public async Task<TaskOperationResult> ApproveAsync(Guid id, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
if (!TaskStateHelper.IsInProgressOrBlocked(task.State))
return new TaskOperationResult(TaskOperationOutcome.InvalidState, task);
task.State = TaskStateHelper.ToStateString(TaskState.Done);
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} approved", TaskId = task.Id }, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> RejectAsync(Guid id, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
if (!TaskStateHelper.IsInProgressOrBlocked(task.State))
return new TaskOperationResult(TaskOperationOutcome.InvalidState, task);
task.State = TaskStateHelper.ToStateString(TaskState.Backlog);
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} rejected, returned to backlog", TaskId = task.Id }, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> UpdateStateAsync(Guid id, string state, CancellationToken ct = default)
{
var canonical = TaskStateHelper.AllStates.FirstOrDefault(s => s.Equals(state, StringComparison.OrdinalIgnoreCase));
if (canonical is null) return new TaskOperationResult(TaskOperationOutcome.InvalidState);
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
// Enforce workflow rules
var caller = ResolveCaller();
if (!TaskStateHelper.CanChangeState(caller, task))
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
task.State = canonical;
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} moved to {task.State}", TaskId = task.Id }, ct);
await CreateStatusChangeNotificationsAsync(task, canonical, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> UpdateAsync(Guid id, UpdateTaskRequest request, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
var changes = new List<string>();
if (!string.IsNullOrWhiteSpace(request.Title) && !string.Equals(task.Title, request.Title.Trim(), StringComparison.Ordinal))
{
changes.Add($"Titel: \"{task.Title}\" → \"{request.Title.Trim()}\"");
task.Title = request.Title.Trim();
}
if (!string.IsNullOrWhiteSpace(request.Priority) && !string.Equals(task.Priority, request.Priority.Trim(), StringComparison.OrdinalIgnoreCase))
{
changes.Add($"Priorität: {task.Priority} → {request.Priority.Trim()}");
task.Priority = request.Priority.Trim();
}
if (request.ProjectId.HasValue)
{
changes.Add($"Projekt-ID geändert");
task.ProjectId = request.ProjectId.Value == Guid.Empty ? null : request.ProjectId;
}
await taskRepo.UpdateAsync(task, ct);
var changeSummary = changes.Count > 0 ? string.Join("; ", changes) : "keine sichtbaren Änderungen";
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" aktualisiert: {changeSummary}", TaskId = task.Id }, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> DeleteAsync(Guid id, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
if (!TaskStateHelper.IsDoneOrBacklog(task.State))
return new TaskOperationResult(TaskOperationOutcome.InvalidState, task);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task {task.Title} deleted", TaskId = task.Id }, ct);
await taskRepo.DeleteAsync(task, ct);
return new TaskOperationResult(TaskOperationOutcome.Success);
}
// ── Dashboard-facing operations ──
public async Task<IReadOnlyList<WorkTask>> GetOpenAsync(CancellationToken ct = default)
{
var all = await taskRepo.GetAllAsync(ct);
return all.Where(t => !string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase))
.OrderByDescending(t => t.CreatedAt)
.ToList();
}
/// <summary>
/// Returns agent-tasks that are still open and where an agent is expected to respond.
/// Iris Dashboard uses this to see who she is waiting for.
/// </summary>
public async Task<IReadOnlyList<WorkTask>> GetWaitingTasksAsync(CancellationToken ct = default)
{
var all = await taskRepo.GetAllAsync(ct);
return all
.Where(t => t.IsAgentTask && !string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase))
.OrderBy(t => t.ExpectedFrom != null ? 0 : 1)
.ThenByDescending(t => t.UpdatedAt)
.ToList();
}
/// <summary>
/// Returns agent-tasks grouped by which agent is expected to respond,
/// with stale-detection: tasks in InProgress/Delegated that haven't been
/// updated within the stale threshold.
/// </summary>
public async Task<AgentWorkflowOverview> GetAgentWorkflowOverviewAsync(TimeSpan staleThreshold, CancellationToken ct = default)
{
var all = await taskRepo.GetAllAsync(ct);
var threshold = DateTimeOffset.UtcNow - staleThreshold;
var agentTasks = all.Where(t => t.IsAgentTask).ToList();
var activity = await activityRepo.GetRecentForTasksAsync(agentTasks.Select(t => t.Id), ct);
List<DashboardTaskDto> map(IEnumerable<WorkTask> tasks)
=> tasks.Select(task => MapToDtoWithActivity(task, activity)).ToList();
var waitingForBao = map(agentTasks
.Where(t => string.Equals(t.ExpectedFrom, "bao", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase)));
var waitingForIris = map(agentTasks
.Where(t => string.Equals(t.ExpectedFrom, "iris", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase)));
var waitingForOthers = map(agentTasks
.Where(t =>
{
var expected = (t.ExpectedFrom ?? "").ToLowerInvariant();
return expected != "bao" && expected != "iris" && !string.IsNullOrWhiteSpace(expected) &&
!string.Equals(t.State, "Done", StringComparison.OrdinalIgnoreCase);
}));
var staleTasks = map(agentTasks
.Where(t =>
(string.Equals(t.State, "In progress", StringComparison.OrdinalIgnoreCase) ||
string.Equals(t.State, "Delegated", StringComparison.OrdinalIgnoreCase)) &&
t.UpdatedAt < threshold));
return new AgentWorkflowOverview(waitingForBao, waitingForIris, waitingForOthers,
staleTasks, staleThreshold);
}
public async Task<WorkTask> CreateDashboardTaskAsync(
string title, string? detail, string? source, string? priority,
string? assignedTo, Guid? parentTaskId = null, CancellationToken ct = default)
{
// Validate parent task exists if specified
if (parentTaskId.HasValue)
{
var parent = await taskRepo.GetByIdAsync(parentTaskId.Value, ct);
if (parent is null)
throw new ArgumentException($"Parent task {parentTaskId} not found.", nameof(parentTaskId));
}
var task = new WorkTask
{
Title = title.Trim(),
Detail = detail?.Trim(),
Source = string.IsNullOrWhiteSpace(source) ? "bao" : source.Trim(),
Priority = string.IsNullOrWhiteSpace(priority) ? "Normal" : priority.Trim(),
AssignedTo = ValidateAssignedTo(assignedTo),
ParentTaskId = parentTaskId
};
await taskRepo.AddAsync(task, ct);
var message = $"Task \"{task.Title}\" created ({task.Source})";
if (parentTaskId.HasValue)
message += $" [child of {parentTaskId.Value}]";
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = message, TaskId = task.Id }, ct);
// Auto-notify: if assigned to bao, create a task_assigned notification
if (string.Equals(assignedTo, "bao", StringComparison.OrdinalIgnoreCase))
{
await notificationService.CreateAsync(
"task_assigned",
$"Neue Aufgabe: {task.Title}",
detail,
"bao",
task.Id,
ct);
}
return task;
}
public async Task<WorkTask> CreateAgentTaskAsync(
string title, string? detail, string? source, string? priority,
string? assignedTo, string? expectedFrom, Guid? parentTaskId = null, CancellationToken ct = default)
{
var task = await CreateDashboardTaskAsync(title, detail, source, priority, assignedTo, parentTaskId, ct);
task.IsAgentTask = true;
task.ExpectedFrom = string.IsNullOrWhiteSpace(expectedFrom) ? null : expectedFrom.Trim().ToLowerInvariant();
// Persist the agent-task-specific fields
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent
{
Type = "agent_task",
Message = $"Agent-Task created: \"{task.Title}\" (Source: {task.Source}, Expected: {task.ExpectedFrom ?? "none"})",
TaskId = task.Id
}, ct);
// Notify iris about new agent-task
await notificationService.CreateAsync(
"agent_task_created",
$"Neuer Agent-Task: {task.Title}",
detail,
"iris",
task.Id,
ct);
return task;
}
public async Task<TaskOperationResult> UpdateDashboardTaskAsync(
Guid id, string? title, string? detail, string? source,
string? priority, string? assignedTo, DateTimeOffset? dueDate = null, CancellationToken ct = default)
{
var caller = ResolveCaller();
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
var changes = new List<string>();
if (!string.IsNullOrWhiteSpace(title) && !string.Equals(task.Title, title.Trim(), StringComparison.Ordinal))
{
changes.Add($"Titel: \"{task.Title}\" → \"{title.Trim()}\"");
task.Title = title.Trim();
}
if (detail is not null)
{
var newDetail = string.IsNullOrWhiteSpace(detail) ? null : detail.Trim();
if (!string.Equals(task.Detail ?? "", newDetail ?? "", StringComparison.Ordinal))
{
changes.Add("Beschreibung aktualisiert");
task.Detail = newDetail;
}
}
if (!string.IsNullOrWhiteSpace(source))
task.Source = source.Trim();
if (!string.IsNullOrWhiteSpace(priority) && !string.Equals(task.Priority, priority.Trim(), StringComparison.OrdinalIgnoreCase))
{
changes.Add($"Priorität: {task.Priority} → {priority.Trim()}");
task.Priority = priority.Trim();
}
if (assignedTo is not null)
{
var validated = ValidateAssignedTo(assignedTo);
if (!string.Equals(task.AssignedTo ?? "", validated ?? "", StringComparison.OrdinalIgnoreCase))
{
changes.Add($"Zuständig: {task.AssignedTo ?? "niemand"} → {validated ?? "niemand"}");
task.AssignedTo = validated;
}
}
if (dueDate.HasValue)
{
if (task.DueDate?.Date != dueDate.Value.Date)
{
changes.Add($"Fällig: {task.DueDate?.ToString("yyyy-MM-dd") ?? "kein Datum"} → {dueDate.Value:yyyy-MM-dd}");
task.DueDate = dueDate;
}
}
await taskRepo.UpdateAsync(task, ct);
var changeSummary = changes.Count > 0 ? string.Join("; ", changes) : "keine sichtbaren Änderungen";
await activityRepo.AddAsync(new ActivityEvent
{
Type = "task",
Message = $"Task \"{task.Title}\" aktualisiert von {caller}: {changeSummary}",
TaskId = task.Id
}, ct);
// Notification: wenn Bao die Task geändert hat, Iris benachrichtigen
if (changes.Count > 0 && caller == "bao")
{
await notificationService.CreateAsync(
"task_content_changed",
$"Bao hat \"{task.Title}\" geändert",
$"{changeSummary}",
"iris",
task.Id,
ct);
}
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> UpdateStatusAsync(Guid id, string status, CancellationToken ct = default)
{
if (!TaskStateHelper.IsValidState(status))
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
// Enforce workflow rules
var caller = ResolveCaller();
if (!TaskStateHelper.CanChangeState(caller, task))
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
var canonical = TaskStateHelper.AllStates.First(s => s.Equals(status, StringComparison.OrdinalIgnoreCase));
task.State = canonical;
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" → {canonical}", TaskId = task.Id }, ct);
await CreateStatusChangeNotificationsAsync(task, canonical, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> CompleteViaQueueAsync(Guid id, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
task.State = "Done";
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" completed via queue", TaskId = task.Id }, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public async Task<TaskOperationResult> CyclePriorityAsync(Guid id, CancellationToken ct = default)
{
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
task.Priority = task.Priority.ToLowerInvariant() switch
{
"high" => "Medium",
"medium" => "Low",
"low" => "High",
_ => "Medium"
};
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" priority → {task.Priority}", TaskId = task.Id }, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
// ── Board operations ──
public async Task<BoardResponse> GetBoardAsync(CancellationToken ct = default)
{
var all = await taskRepo.GetAllAsync(ct);
var offen = new List<DashboardTaskDto>();
var inProgress = new List<DashboardTaskDto>();
var delegated = new List<DashboardTaskDto>();
var review = new List<DashboardTaskDto>();
var blocked = new List<DashboardTaskDto>();
var done = new List<DashboardTaskDto>();
foreach (var task in all)
{
var dto = MapToDto(task);
switch (task.State.ToLowerInvariant())
{
case "backlog":
offen.Add(dto); break;
case "in progress":
inProgress.Add(dto); break;
case "delegated":
delegated.Add(dto); break;
case "review":
review.Add(dto); break;
case "blocked":
blocked.Add(dto); break;
case "done":
done.Add(dto); break;
default:
offen.Add(dto); break;
}
}
offen.Sort(SortByPriorityThenCreatedAt);
inProgress.Sort(SortByPriorityThenCreatedAt);
delegated.Sort(SortByPriorityThenCreatedAt);
review.Sort(SortByPriorityThenCreatedAt);
blocked.Sort(SortByPriorityThenCreatedAt);
done.Sort(SortByPriorityThenCreatedAt);
return new BoardResponse(offen, inProgress, delegated, review, blocked, done);
}
private static int SortByPriorityThenCreatedAt(DashboardTaskDto a, DashboardTaskDto b)
{
var priorityCompare = PriorityScore(b.Priority).CompareTo(PriorityScore(a.Priority));
return priorityCompare != 0 ? priorityCompare : a.CreatedAt.CompareTo(b.CreatedAt);
}
private static int PriorityScore(string priority) => priority.ToLowerInvariant() switch
{
"high" => 3,
"medium" => 2,
"normal" => 2,
"low" => 1,
_ => 2
};
public async Task<TaskOperationResult> MoveTaskAsync(Guid id, string newState, CancellationToken ct = default)
{
// Resolve canonical state: accept board group keys or canonical strings
var canonical = TaskStateHelper.AllStates
.FirstOrDefault(s => s.Equals(newState, StringComparison.OrdinalIgnoreCase));
if (canonical is null)
{
// Try mapping from board group key
canonical = TaskStateHelper.BoardGroupToState(newState);
}
if (canonical is null)
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
var task = await taskRepo.GetByIdAsync(id, ct);
if (task is null) return new TaskOperationResult(TaskOperationOutcome.NotFound);
// Enforce workflow rules
var caller = ResolveCaller();
if (!TaskStateHelper.CanChangeState(caller, task))
return new TaskOperationResult(TaskOperationOutcome.InvalidState);
task.State = canonical;
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent { Type = "task", Message = $"Task \"{task.Title}\" moved to {canonical}", TaskId = task.Id }, ct);
await CreateStatusChangeNotificationsAsync(task, canonical, ct);
return new TaskOperationResult(TaskOperationOutcome.Success, task);
}
public Task<int> ResetStaleAsync(int staleHours, CancellationToken ct = default)
{
var normalizedHours = Math.Max(1, staleHours);
return ResetStaleInProgressTasksAsync(TimeSpan.FromHours(normalizedHours), ct);
}
public async Task<int> ResetStaleInProgressTasksAsync(TimeSpan staleThreshold, CancellationToken ct = default)
{
var all = await taskRepo.GetAllAsync(ct);
var threshold = DateTimeOffset.UtcNow - staleThreshold;
var staleTasks = all.Where(t =>
(string.Equals(t.State, "In progress", StringComparison.OrdinalIgnoreCase) ||
string.Equals(t.State, "Delegated", StringComparison.OrdinalIgnoreCase)) &&
t.UpdatedAt < threshold).ToList();
foreach (var task in staleTasks)
{
var prevState = task.State;
task.State = "Backlog";
await taskRepo.UpdateAsync(task, ct);
await activityRepo.AddAsync(new ActivityEvent
{
Type = "task",
Message = $"Task \"{task.Title}\" reset from {prevState} to Backlog (stale)",
TaskId = task.Id
}, ct);
}
return staleTasks.Count;
}
public async Task<IReadOnlyList<WorkTask>> GetChildTasksAsync(Guid parentId, CancellationToken ct = default)
{
var all = await taskRepo.GetAllAsync(ct);
return all.Where(t => t.ParentTaskId == parentId)
.OrderByDescending(t => t.CreatedAt)
.ToList();
}
public async Task<List<ActivityEvent>> GetTaskActivityAsync(Guid taskId, CancellationToken ct = default)
{
var all = await activityRepo.GetRecentAsync(100, ct);
return all.Where(e => e.TaskId == taskId).ToList();
}
private static DashboardTaskDto MapToDto(WorkTask t) => new(
t.Id, t.Title, t.Detail, t.Source, t.State, t.Priority, t.AssignedTo,
t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt,
t.IsAgentTask, t.ExpectedFrom);
private static DashboardTaskDto MapToDtoWithActivity(WorkTask t, IEnumerable<ActivityEvent> activity)
{
var last = activity
.Where(e => e.TaskId == t.Id)
.OrderByDescending(e => e.CreatedAt)
.FirstOrDefault();
return new DashboardTaskDto(
t.Id, t.Title, t.Detail, t.Source, t.State, t.Priority, t.AssignedTo,
t.ParentTaskId, t.DueDate, t.CreatedAt, t.UpdatedAt,
t.IsAgentTask, t.ExpectedFrom,
last?.Message,
last?.CreatedAt);
}
/// <summary>
/// Validates AssignedTo — only recognized agent values are accepted.
/// Returns null for invalid values.
/// </summary>
private static string? ValidateAssignedTo(string? assignedTo)
{
if (string.IsNullOrWhiteSpace(assignedTo)) return null;
var lower = assignedTo.Trim().ToLowerInvariant();
return ValidAssignees.Contains(lower) ? lower : null;
}
/// <summary>
/// Resolves the caller identity from the HTTP context.
/// Reads the X-Agent-Id header for agent calls, falls back to JWT name.
/// Outside HTTP context → "nexus-system" (allowed for internal Cron/ResetStale ops).
/// </summary>
private string ResolveCaller()
{
var httpContext = httpContextAccessor.HttpContext;
if (httpContext is null) return "nexus-system"; // internal system ops allowed
var agentHeader = httpContext.Request.Headers["X-Agent-Id"].FirstOrDefault();
if (!string.IsNullOrWhiteSpace(agentHeader))
return agentHeader.Trim().ToLowerInvariant();
var user = httpContext.User;
var nameClaim = user?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
return nameClaim?.ToLowerInvariant() ?? "";
}
/// <summary>
/// Creates status-change notifications when a task moves to a new state.
/// - Wenn Bao ändert → Iris benachrichtigen
/// - Wenn Iris ändert → Bao benachrichtigen
/// - Review/Blocked bekommen spezifische Töne
/// </summary>
private async Task CreateStatusChangeNotificationsAsync(WorkTask task, string canonical, CancellationToken ct)
{
var caller = ResolveCaller();
if (string.Equals(canonical, "Review", StringComparison.OrdinalIgnoreCase))
{
await notificationService.CreateAsync(
"task_review",
$"Task zur Überprüfung: {task.Title}",
$"Status auf Review geändert von {caller}",
"bao",
task.Id,
ct);
}
else if (string.Equals(canonical, "Blocked", StringComparison.OrdinalIgnoreCase))
{
await notificationService.CreateAsync(
"task_blocked",
$"Aufgabe blockiert: {task.Title}",
$"Die Task wurde von {caller} auf Blockiert gesetzt.",
"iris",
task.Id,
ct);
}
else
{
// Allgemeine Statusänderung: Gegenüber benachrichtigen
if (caller == "bao")
{
await notificationService.CreateAsync(
"task_status_changed",
$"Bao hat Status geändert: {task.Title}",
$"Status → {canonical}",
"iris",
task.Id,
ct);
}
else if (caller == "iris")
{
await notificationService.CreateAsync(
"task_status_changed",
$"Iris hat Status geändert: {task.Title}",
$"Status → {canonical}",
"bao",
task.Id,
ct);
}
}
}
}
+34
View File
@@ -0,0 +1,34 @@
namespace Nexus.Api.Services;
public sealed class TeamService(IAgentService agentService) : ITeamService
{
public async Task<IReadOnlyList<TeamMember>> GetTeamAsync(CancellationToken ct = default)
{
var agents = await agentService.GetAgentsAsync(ct);
var team = new List<TeamMember>(agents.Count);
foreach (var agent in agents)
{
var identity = await ReadIdentityAsync(agent.Workspace, ct);
team.Add(new TeamMember(
agent.Id, agent.Name, agent.Role, agent.Model,
agent.Status, agent.LastSeen, agent.Workspace, agent.Description,
identity));
}
return team;
}
private static async Task<string> ReadIdentityAsync(string? workspace, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(workspace) || !Directory.Exists(workspace))
return string.Empty;
var identityFile = Path.Combine(workspace, "IDENTITY.md");
if (!File.Exists(identityFile))
return string.Empty;
var content = await File.ReadAllTextAsync(identityFile, ct);
return string.Join("\n", content.Split('\n').Where(l => l.StartsWith("- **")).Take(8));
}
}
+85 -9
View File
@@ -4,7 +4,14 @@ services:
postgres: postgres:
image: postgres:17-alpine image: postgres:17-alpine
restart: unless-stopped restart: unless-stopped
deploy:
resources:
limits:
memory: 384M
reservations:
memory: 96M
environment: environment:
POSTGRES_INITDB_ARGS: --data-checksums
POSTGRES_DB: ${POSTGRES_DB:-nexus} POSTGRES_DB: ${POSTGRES_DB:-nexus}
POSTGRES_USER: ${POSTGRES_USER:-nexus} POSTGRES_USER: ${POSTGRES_USER:-nexus}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
@@ -15,12 +22,29 @@ services:
interval: 10s interval: 10s
timeout: 5s timeout: 5s
retries: 5 retries: 5
start_period: 30s
networks: [nexus] networks: [nexus]
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
api: api:
build: build:
context: ./backend context: ./backend
restart: unless-stopped restart: unless-stopped
deploy:
resources:
limits:
memory: 512M
reservations:
memory: 128M
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 120s
environment: environment:
ASPNETCORE_ENVIRONMENT: Production ASPNETCORE_ENVIRONMENT: Production
ASPNETCORE_URLS: http://+:8080 ASPNETCORE_URLS: http://+:8080
@@ -29,41 +53,93 @@ services:
Jwt__Issuer: ${JWT_ISSUER:-nexus} Jwt__Issuer: ${JWT_ISSUER:-nexus}
Jwt__Audience: ${JWT_AUDIENCE:-nexus-web} Jwt__Audience: ${JWT_AUDIENCE:-nexus-web}
Owner__Email: ${OWNER_EMAIL:?Set OWNER_EMAIL in .env} Owner__Email: ${OWNER_EMAIL:?Set OWNER_EMAIL in .env}
# OWNER_PASSWORD is only used during initial seed (first deploy).
# After that the DB is the single source of truth, enforced by SeedAudit.
# Default: empty (seed uses a random password if unset on first run).
Owner__Password: ${OWNER_PASSWORD:-} Owner__Password: ${OWNER_PASSWORD:-}
Owner__DisplayName: ${OWNER_DISPLAY_NAME:-Owner} Owner__DisplayName: ${OWNER_DISPLAY_NAME:-Owner}
Integrations__OpenClaw__BaseUrl: ${OPENCLAW_BASE_URL:-http://host.docker.internal:18789} Integrations__OpenClaw__BaseUrl: ${OPENCLAW_BASE_URL:-http://host.docker.internal:18789}
Integrations__OpenClaw__Token: ${OPENCLAW_GATEWAY_TOKEN:-} Integrations__OpenClaw__Token: ${OPENCLAW_GATEWAY_TOKEN:-}
Integrations__OpenClaw__Password: ${OPENCLAW_GATEWAY_PASSWORD:-} Integrations__OpenClaw__Password: ${OPENCLAW_GATEWAY_PASSWORD:-}
Admin__ResetToken: ${Admin__ResetToken:-} Admin__ResetToken: ${Admin__ResetToken:-}
NexusApiKey: ${NEXUS_API_KEY:-}
extra_hosts: extra_hosts:
- host.docker.internal:host-gateway - host.docker.internal:host-gateway
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_started
restart: true
healthcheck:
test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:8080/health/live || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 15s
volumes: volumes:
- /opt/openclaw/data/openclaw/workspace-iris:/mnt/workspace-iris - /home/projekte_bao/openclaw/data/openclaw/openclaw.json:/home/node/.openclaw/openclaw.json:ro
- /opt/openclaw/data/openclaw/workspace-programmer:/mnt/workspace-programmer - /home/projekte_bao/openclaw/data/openclaw/workspace-iris:/mnt/workspace-iris
- /opt/openclaw/data/openclaw/workspace-reviewer:/mnt/workspace-reviewer - /home/projekte_bao/openclaw/data/openclaw/workspace-programmer:/mnt/workspace-programmer
- /opt/openclaw/data/openclaw/workspace-architekt:/mnt/workspace-architekt - /home/projekte_bao/openclaw/data/openclaw/workspace-reviewer:/mnt/workspace-reviewer
- /opt/openclaw/data/openclaw/workspace-researcher:/mnt/workspace-researcher - /home/projekte_bao/openclaw/data/openclaw/workspace-architekt:/mnt/workspace-architekt
- /opt/openclaw/data/openclaw/workspace-executor:/mnt/workspace-executor - /home/projekte_bao/openclaw/data/openclaw/workspace-researcher:/mnt/workspace-researcher
- /home/projekte_bao/openclaw/data/openclaw/workspace-executor:/mnt/workspace-executor
networks: networks:
- nexus - nexus
- openclaw_default - openclaw_default
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
web: web:
build: build:
context: ./frontend context: ./frontend
restart: unless-stopped restart: unless-stopped
deploy:
resources:
limits:
memory: 128M
reservations:
memory: 32M
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
window: 120s
labels:
- "traefik.enable=true"
- "traefik.http.routers.nexus.rule=Host(`nexus.noveria.net`)"
- "traefik.http.routers.nexus.tls=true"
- "traefik.http.routers.nexus.tls.certresolver=letsencrypt"
- "traefik.http.services.nexus.loadbalancer.server.port=80"
ports: ports:
- "127.0.0.1:18880:80" - "127.0.0.1:18880:80"
depends_on: [api] depends_on:
networks: [nexus] api:
condition: service_started
restart: true
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:80/ || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
networks:
- nexus
- proxy
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
networks: networks:
nexus: nexus:
openclaw_default: openclaw_default:
external: true external: true
proxy:
external: true
volumes: volumes:
nexus-postgres: nexus-postgres:
@@ -0,0 +1 @@
{"locator":{"name":"pnpm","reference":"10.12.1"},"bin":{"pnpm":"./bin/pnpm.cjs","pnpx":"./bin/pnpx.cjs"},"hash":"sha512.f0dda8580f0ee9481c5c79a1d927b9164f2c478e90992ad268bbb2465a736984391d6333d2c327913578b2804af33474ca554ba29c04a8b13060a717675ae3ac"}
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015-2016 Rico Sta. Cruz and other contributors
Copyright (c) 2016-2025 Zoltan Kochan and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,212 @@
[简体中文](https://pnpm.io/zh/) |
[日本語](https://pnpm.io/ja/) |
[한국어](https://pnpm.io/ko/) |
[Italiano](https://pnpm.io/it/) |
[Português Brasileiro](https://pnpm.io/pt/)
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://i.imgur.com/qlW1eEG.png">
<source media="(prefers-color-scheme: dark)" srcset="https://i.imgur.com/qlW1eEG.png">
<img src="https://i.imgur.com/qlW1eEG.png" alt="pnpm">
</picture>
Fast, disk space efficient package manager:
* **Fast.** Up to 2x faster than the alternatives (see [benchmark](#benchmark)).
* **Efficient.** Files inside `node_modules` are linked from a single content-addressable storage.
* **[Great for monorepos](https://pnpm.io/workspaces).**
* **Strict.** A package can access only dependencies that are specified in its `package.json`.
* **Deterministic.** Has a lockfile called `pnpm-lock.yaml`.
* **Works as a Node.js version manager.** See [pnpm env use](https://pnpm.io/cli/env).
* **Works everywhere.** Supports Windows, Linux, and macOS.
* **Battle-tested.** Used in production by teams of [all sizes](https://pnpm.io/users) since 2016.
* [See the full feature comparison with npm and Yarn](https://pnpm.io/feature-comparison).
To quote the [Rush](https://rushjs.io/) team:
> Microsoft uses pnpm in Rush repos with hundreds of projects and hundreds of PRs per day, and weve found it to be very fast and reliable.
[![npm version](https://img.shields.io/npm/v/pnpm.svg?label=latest)](https://github.com/pnpm/pnpm/releases/latest)
[![Join the chat at Discord](https://img.shields.io/discord/731599538665553971.svg)](https://r.pnpm.io/chat)
[![OpenCollective](https://opencollective.com/pnpm/backers/badge.svg)](https://opencollective.com/pnpm)
[![OpenCollective](https://opencollective.com/pnpm/sponsors/badge.svg)](https://opencollective.com/pnpm)
[![X Follow](https://img.shields.io/twitter/follow/pnpmjs.svg?style=social&label=Follow)](https://x.com/intent/follow?screen_name=pnpmjs&region=follow_link)
[![Stand With Ukraine](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/badges/StandWithUkraine.svg)](https://stand-with-ukraine.pp.ua)
## Platinum Sponsors
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://bit.dev/?utm_source=pnpm&utm_medium=readme" target="_blank"><img src="https://pnpm.io/img/users/bit.svg" width="80" alt="Bit"></a>
</td>
<td align="center" valign="middle">
<a href="https://sanity.io/?utm_source=pnpm&utm_medium=readme" target="_blank"><img src="https://pnpm.io/img/users/sanity.svg" width="180" alt="Bit"></a>
</td>
</tr>
</tbody>
</table>
## Gold Sponsors
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://discord.com/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/discord.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/discord_light.svg" />
<img src="https://pnpm.io/img/users/discord.svg" width="220" alt="Discord" />
</picture>
</a>
</td>
<td align="center" valign="middle">
<a href="https://coderabbit.ai/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/coderabbit.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/coderabbit_light.svg" />
<img src="https://pnpm.io/img/users/coderabbit.svg" width="220" alt="CodeRabbit" />
</picture>
</a>
</td>
<td align="center" valign="middle">
<a href="https://workleap.com/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/workleap.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/workleap_light.svg" />
<img src="https://pnpm.io/img/users/workleap.svg" width="190" alt="Workleap" />
</picture>
</a>
</td>
</tr>
<tr>
<td align="center" valign="middle">
<a href="https://stackblitz.com/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/stackblitz.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/stackblitz_light.svg" />
<img src="https://pnpm.io/img/users/stackblitz.svg" width="190" alt="Stackblitz" />
</picture>
</a>
</td>
<td align="center" valign="middle">
<a href="https://vite.dev/?utm_source=pnpm&utm_medium=readme" target="_blank">
<img src="https://pnpm.io/img/users/vitejs.svg" width="42" alt="Vite">
</a>
</td>
</tr>
</tbody>
</table>
## Silver Sponsors
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="https://uscreen.de/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/uscreen.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/uscreen_light.svg" />
<img src="https://pnpm.io/img/users/uscreen.svg" width="180" alt="u|screen" />
</picture>
</a>
</td>
<td align="center" valign="middle">
<a href="https://leniolabs.com/?utm_source=pnpm&utm_medium=readme" target="_blank">
<img src="https://pnpm.io/img/users/leniolabs.jpg" width="40" alt="Leniolabs_">
</a>
</td>
<td align="center" valign="middle">
<a href="https://depot.dev/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/depot.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/depot_light.svg" />
<img src="https://pnpm.io/img/users/depot.svg" width="100" alt="Depot" />
</picture>
</a>
</td>
</tr>
<tr>
<td align="center" valign="middle">
<a href="https://devowl.io/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/devowlio.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/devowlio.svg" />
<img src="https://pnpm.io/img/users/devowlio.svg" width="100" alt="devowl.io" />
</picture>
</a>
</td>
<td align="center" valign="middle">
<a href="https://cerbos.dev/?utm_source=pnpm&utm_medium=readme" target="_blank">
<picture>
<source media="(prefers-color-scheme: light)" srcset="https://pnpm.io/img/users/cerbos.svg" />
<source media="(prefers-color-scheme: dark)" srcset="https://pnpm.io/img/users/cerbos_light.svg" />
<img src="https://pnpm.io/img/users/cerbos.svg" width="90" alt="Cerbos" />
</picture>
</a>
</td>
<td align="center" valign="middle">
<a href="https://opensource.mercedes-benz.com/?utm_source=pnpm&utm_medium=readme" target="_blank">
<img src="https://pnpm.io/img/users/mercedes.svg" width="32" alt="Vite">
</a>
</td>
</tr>
</tbody>
</table>
Support this project by [becoming a sponsor](https://opencollective.com/pnpm#sponsor).
## Background
pnpm uses a content-addressable filesystem to store all files from all module directories on a disk.
When using npm, if you have 100 projects using lodash, you will have 100 copies of lodash on disk.
With pnpm, lodash will be stored in a content-addressable storage, so:
1. If you depend on different versions of lodash, only the files that differ are added to the store.
If lodash has 100 files, and a new version has a change only in one of those files,
`pnpm update` will only add 1 new file to the storage.
1. All the files are saved in a single place on the disk. When packages are installed, their files are linked
from that single place consuming no additional disk space. Linking is performed using either hard-links or reflinks (copy-on-write).
As a result, you save gigabytes of space on your disk and you have a lot faster installations!
If you'd like more details about the unique `node_modules` structure that pnpm creates and
why it works fine with the Node.js ecosystem, read this small article: [Flat node_modules is not the only way](https://pnpm.io/blog/2020/05/27/flat-node-modules-is-not-the-only-way).
💖 Like this project? Let people know with a [tweet](https://r.pnpm.io/tweet)
## Installation
For installation options [visit our website](https://pnpm.io/installation).
## Usage
Just use pnpm in place of npm/Yarn. E.g., install dependencies via:
```
pnpm install
```
For more advanced usage, read [pnpm CLI](https://pnpm.io/pnpm-cli) on our website, or run `pnpm help`.
## Benchmark
pnpm is up to 2x faster than npm and Yarn classic. See all benchmarks [here](https://r.pnpm.io/benchmarks).
Benchmarks on an app with lots of dependencies:
![](https://pnpm.io/img/benchmarks/alotta-files.svg)
## Support
- [Frequently Asked Questions](https://pnpm.io/faq)
- [Chat](https://r.pnpm.io/chat)
- [X](https://x.com/pnpmjs)
- [Bluesky](https://bsky.app/profile/pnpm.io)
## License
[MIT](https://github.com/pnpm/pnpm/blob/main/LICENSE)
@@ -0,0 +1,189 @@
{
"name": "pnpm",
"version": "10.12.1",
"description": "Fast, disk space efficient package manager",
"keywords": [
"pnpm",
"pnpm10",
"dependencies",
"dependency manager",
"efficient",
"fast",
"hardlinks",
"install",
"installer",
"link",
"lockfile",
"modules",
"monorepo",
"multi-package",
"npm",
"package manager",
"package.json",
"packages",
"prune",
"rapid",
"remove",
"shrinkwrap",
"symlinks",
"uninstall",
"workspace"
],
"license": "MIT",
"funding": "https://opencollective.com/pnpm",
"repository": {
"type": "git",
"url": "git+https://github.com/pnpm/pnpm.git",
"directory": "pnpm"
},
"homepage": "https://pnpm.io",
"bugs": {
"url": "https://github.com/pnpm/pnpm/issues"
},
"main": "bin/pnpm.cjs",
"exports": {
".": "./package.json"
},
"files": [
"dist",
"bin"
],
"bin": {
"pnpm": "bin/pnpm.cjs",
"pnpx": "bin/pnpx.cjs"
},
"directories": {
"test": "test"
},
"unpkg": "dist/pnpm.cjs",
"__dependencies": {
"v8-compile-cache": "2.4.0"
},
"__optionalDependencies": {
"node-gyp": "^11.1.0"
},
"__devDependencies": {
"@pnpm/assert-project": "workspace:*",
"@pnpm/byline": "catalog:",
"@pnpm/cache.commands": "workspace:*",
"@pnpm/cli-meta": "workspace:*",
"@pnpm/cli-utils": "workspace:*",
"@pnpm/client": "workspace:*",
"@pnpm/command": "workspace:*",
"@pnpm/common-cli-options-help": "workspace:*",
"@pnpm/config": "workspace:*",
"@pnpm/constants": "workspace:*",
"@pnpm/core-loggers": "workspace:*",
"@pnpm/crypto.hash": "workspace:*",
"@pnpm/default-reporter": "workspace:*",
"@pnpm/dependency-path": "workspace:*",
"@pnpm/env.path": "workspace:*",
"@pnpm/error": "workspace:*",
"@pnpm/exec.build-commands": "workspace:*",
"@pnpm/filter-workspace-packages": "workspace:*",
"@pnpm/find-workspace-dir": "workspace:*",
"@pnpm/lockfile.types": "workspace:*",
"@pnpm/logger": "workspace:*",
"@pnpm/modules-yaml": "workspace:*",
"@pnpm/nopt": "catalog:",
"@pnpm/parse-cli-args": "workspace:*",
"@pnpm/plugin-commands-audit": "workspace:*",
"@pnpm/plugin-commands-completion": "workspace:*",
"@pnpm/plugin-commands-config": "workspace:*",
"@pnpm/plugin-commands-deploy": "workspace:*",
"@pnpm/plugin-commands-doctor": "workspace:*",
"@pnpm/plugin-commands-env": "workspace:*",
"@pnpm/plugin-commands-init": "workspace:*",
"@pnpm/plugin-commands-installation": "workspace:*",
"@pnpm/plugin-commands-licenses": "workspace:*",
"@pnpm/plugin-commands-listing": "workspace:*",
"@pnpm/plugin-commands-outdated": "workspace:*",
"@pnpm/plugin-commands-patching": "workspace:*",
"@pnpm/plugin-commands-publishing": "workspace:*",
"@pnpm/plugin-commands-rebuild": "workspace:*",
"@pnpm/plugin-commands-script-runners": "workspace:*",
"@pnpm/plugin-commands-server": "workspace:*",
"@pnpm/plugin-commands-setup": "workspace:*",
"@pnpm/plugin-commands-store": "workspace:*",
"@pnpm/plugin-commands-store-inspecting": "workspace:*",
"@pnpm/prepare": "workspace:*",
"@pnpm/read-package-json": "workspace:*",
"@pnpm/read-project-manifest": "workspace:*",
"@pnpm/registry-mock": "catalog:",
"@pnpm/run-npm": "workspace:*",
"@pnpm/store.cafs": "workspace:*",
"@pnpm/tabtab": "catalog:",
"@pnpm/test-fixtures": "workspace:*",
"@pnpm/test-ipc-server": "workspace:*",
"@pnpm/tools.path": "workspace:*",
"@pnpm/tools.plugin-commands-self-updater": "workspace:*",
"@pnpm/types": "workspace:*",
"@pnpm/worker": "workspace:*",
"@pnpm/workspace.find-packages": "workspace:*",
"@pnpm/workspace.pkgs-graph": "workspace:*",
"@pnpm/workspace.read-manifest": "workspace:*",
"@pnpm/workspace.state": "workspace:*",
"@pnpm/write-project-manifest": "workspace:*",
"@types/cross-spawn": "catalog:",
"@types/is-windows": "catalog:",
"@types/pnpm__byline": "catalog:",
"@types/ramda": "catalog:",
"@types/semver": "catalog:",
"@zkochan/retry": "catalog:",
"@zkochan/rimraf": "catalog:",
"chalk": "catalog:",
"ci-info": "catalog:",
"cross-spawn": "catalog:",
"deep-require-cwd": "catalog:",
"delay": "catalog:",
"dir-is-case-sensitive": "catalog:",
"esbuild": "catalog:",
"execa": "catalog:",
"exists-link": "catalog:",
"is-windows": "catalog:",
"load-json-file": "catalog:",
"loud-rejection": "catalog:",
"normalize-newline": "catalog:",
"p-any": "catalog:",
"p-defer": "catalog:",
"path-name": "catalog:",
"pidtree": "catalog:",
"ps-list": "catalog:",
"ramda": "catalog:",
"read-yaml-file": "catalog:",
"render-help": "catalog:",
"semver": "catalog:",
"split-cmd": "catalog:",
"symlink-dir": "catalog:",
"tempy": "catalog:",
"tree-kill": "catalog:",
"write-json-file": "catalog:",
"write-pkg": "catalog:",
"write-yaml-file": "catalog:"
},
"engines": {
"node": ">=18.12"
},
"jest": {
"preset": "@pnpm/jest-config/with-registry"
},
"preferGlobal": true,
"publishConfig": {
"tag": "next-10",
"executableFiles": [
"./dist/node-gyp-bin/node-gyp",
"./dist/node-gyp-bin/node-gyp.cmd",
"./dist/node_modules/node-gyp/bin/node-gyp.js"
]
},
"scripts": {
"bundle": "ts-node bundle.ts",
"start": "tsc --watch",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
"pretest:e2e": "rimraf node_modules/.bin/pnpm",
"_test": "jest",
"test": "pnpm run compile && pnpm run _test",
"_compile": "tsc --build",
"compile": "tsc --build && pnpm run lint --fix && rimraf dist bin/nodes && pnpm run bundle && shx cp -r node-gyp-bin dist/node-gyp-bin && shx cp -r node_modules/@pnpm/tabtab/lib/templates dist/templates && shx cp -r node_modules/ps-list/vendor dist/vendor && shx cp pnpmrc dist/pnpmrc"
}
}
+3
View File
@@ -5,6 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#080a0f" /> <meta name="theme-color" content="#080a0f" />
<title>Nexus | Noveria Operations</title> <title>Nexus | Noveria Operations</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Manrope:wght@400;500;600;700;800&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+3 -3
View File
@@ -23,7 +23,7 @@ const activeView = computed(() => {
const routePaths: Record<string, string> = { const routePaths: Record<string, string> = {
Dashboard: '/dashboard', Memory: '/memory', Docs: '/docs', Security: '/security', Dashboard: '/dashboard', Memory: '/memory', Docs: '/docs', Security: '/security',
Projects: '/projects', 'Task Board': '/tasks', Incidents: '/incidents', Calendar: '/calendar', Projects: '/projects', 'Task Board': '/tasks', Incidents: '/incidents', Calendar: '/calendar',
Agents: '/agents', Models: '/models', Activity: '/activity', 'Mobile Chat': '/chat', Settings: '/settings', Agents: '/agents', Models: '/models', Activity: '/activity', 'Mobile Chat': '/chat', Notifications: '/notifications', Settings: '/settings',
} }
const navigate = (label: string) => { const navigate = (label: string) => {
@@ -32,7 +32,7 @@ const navigate = (label: string) => {
} }
const mobileNavOpen = ref(false) const mobileNavOpen = ref(false)
const standaloneViews = computed(() => ['Dashboard', 'Settings', 'ProjectDetail', 'Memory', 'Docs', 'Security', 'Incidents', 'Calendar', 'AgentDetail', 'Agents'].includes(activeView.value)) const standaloneViews = computed(() => ['Dashboard', 'Settings', 'ProjectDetail', 'Memory', 'Docs', 'Security', 'Incidents', 'Calendar', 'AgentDetail', 'Agents', 'Task Board', 'TaskDetail', 'Notifications'].includes(activeView.value))
onMounted(() => { onMounted(() => {
if (auth.isAuthenticated) store.refresh() if (auth.isAuthenticated) store.refresh()
@@ -40,7 +40,7 @@ onMounted(() => {
</script> </script>
<template> <template>
<RouterView v-if="route.name === 'Login'" /> <RouterView v-if="route.name === 'Login' || route.name === 'Dashboard'" />
<div v-else class="shell"> <div v-else class="shell">
<AppSidebar <AppSidebar
:active-view="activeView" :active-view="activeView"
+47 -1
View File
@@ -4,6 +4,52 @@
@custom-variant dark (&:is(.dark *)); @custom-variant dark (&:is(.dark *));
/* ── Nexus V2 Theme (Tailwind v4 @theme directive) ── */
@theme {
/* Font families */
--font-sans: 'Manrope', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--font-display: 'Space Grotesk', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
/* Space surfaces */
--color-space-0: #050410;
--color-space-1: #0a0818;
--color-space-2: #0e0c20;
--color-space-3: #141130;
--color-space-4: #1b1742;
/* Glass */
--color-glass: rgba(20, 17, 48, 0.55);
--color-glass-2: rgba(28, 24, 64, 0.55);
/* Lines */
--color-line: rgba(150, 140, 255, 0.10);
--color-line-2: rgba(150, 140, 255, 0.18);
--color-line-3: rgba(150, 140, 255, 0.30);
/* Text */
--color-tx: #ece9ff;
--color-tx-2: #a8a3d6;
--color-tx-3: #6f6aa0;
/* Accent */
--color-a-blue: #4f7cff;
--color-a-purple: #b557f6;
--color-a-mid: #7c6cff;
/* Status */
--color-st-work: #3ddc97;
--color-st-think: #34d6f5;
--color-st-queue: #fbbf24;
--color-st-block: #fb7185;
--color-st-idle: #6b6796;
/* Border radius */
--radius-r: 14px;
--radius-r-sm: 10px;
--radius-r-lg: 20px;
}
:root { :root {
--background: 222.2 84% 4.9%; --background: 222.2 84% 4.9%;
--foreground: 210 40% 98%; --foreground: 210 40% 98%;
@@ -39,7 +85,7 @@
body { body {
background: hsl(var(--background)); background: hsl(var(--background));
color: hsl(var(--foreground)); color: hsl(var(--foreground));
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, font-family: 'Manrope', ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
'Segoe UI', sans-serif; 'Segoe UI', sans-serif;
margin: 0; margin: 0;
min-width: 320px; min-width: 320px;
+110
View File
@@ -0,0 +1,110 @@
/* ================================================================
nexus-tokens.css — Nexus Mission Control V2 Design Tokens
Geladen NACH main.css, überschreibt shadcn/v1-Standards.
================================================================ */
:root {
/* ── Surfaces ─────────────────────────────────────── */
--space-0: #050410;
--space-1: #0a0818;
--space-2: #0e0c20;
--space-3: #141130;
--space-4: #1b1742;
--glass: rgba(20, 17, 48, 0.55);
--glass-2: rgba(28, 24, 64, 0.55);
/* ── Lines ────────────────────────────────────────── */
--line: rgba(150, 140, 255, 0.10);
--line-2: rgba(150, 140, 255, 0.18);
--line-3: rgba(150, 140, 255, 0.30);
/* ── Text ─────────────────────────────────────────── */
--tx: #ece9ff;
--tx-2: #a8a3d6;
--tx-3: #6f6aa0;
/* ── Accent Gradient ──────────────────────────────── */
--a-blue: #4f7cff;
--a-purple: #b557f6;
--a-mid: #7c6cff;
--grad: linear-gradient(120deg, var(--a-blue), var(--a-purple));
--grad-soft: linear-gradient(120deg, rgba(79,124,255,.18), rgba(181,87,246,.18));
/* ── Status ───────────────────────────────────────── */
--st-work: #3ddc97;
--st-think: #34d6f5;
--st-queue: #fbbf24;
--st-block: #fb7185;
--st-idle: #6b6796;
/* ── Glows ────────────────────────────────────────── */
--glow: 0 0 0 1px rgba(124,108,255,.20), 0 0 28px -4px rgba(124,108,255,.55);
--glow-blue: 0 0 24px -2px rgba(79,124,255,.65);
--glow-purple: 0 0 24px -2px rgba(181,87,246,.60);
--glow-work: 0 0 16px -1px rgba(61,220,151,.70);
--glow-think: 0 0 16px -1px rgba(52,214,245,.65);
/* ── Radius ───────────────────────────────────────── */
--r: 14px;
--r-sm: 10px;
--r-lg: 20px;
/* ── Layout ───────────────────────────────────────── */
--sidebar-w: 248px;
--topbar-h: 62px;
--rail-w: 360px;
}
/* ── Glass card utility ────────────────────────────── */
.glass-panel {
background: var(--glass);
border: 1px solid var(--line);
border-radius: var(--r);
backdrop-filter: blur(12px);
}
/* ── Gradient text ─────────────────────────────────── */
.grad-text {
background: var(--grad);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
/* ── Status dot keyframes ──────────────────────────── */
@keyframes pulse-work {
0% { box-shadow: 0 0 0 0 rgba(61,220,151,.55); }
70% { box-shadow: 0 0 0 7px rgba(61,220,151,0); }
100% { box-shadow: 0 0 0 0 rgba(61,220,151,0); }
}
@keyframes pulse-think {
0% { box-shadow: 0 0 0 0 rgba(52,214,245,.55); }
70% { box-shadow: 0 0 0 7px rgba(52,214,245,0); }
100% { box-shadow: 0 0 0 0 rgba(52,214,245,0); }
}
@keyframes pulse-block {
0% { box-shadow: 0 0 0 0 rgba(251,113,133,.55); }
70% { box-shadow: 0 0 0 7px rgba(251,113,133,0); }
100% { box-shadow: 0 0 0 0 rgba(251,113,133,0); }
}
@keyframes shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(180%); }
}
/* ── V2 Scrollbars ─────────────────────────────────── */
.v2-scroll::-webkit-scrollbar { width: 9px; height: 9px; }
.v2-scroll::-webkit-scrollbar-thumb {
background: rgba(124,108,255,.22);
border-radius: 9px;
border: 2px solid transparent;
background-clip: padding-box;
}
.v2-scroll::-webkit-scrollbar-thumb:hover {
background: rgba(124,108,255,.4);
background-clip: padding-box;
}
.v2-scroll::-webkit-scrollbar-track { background: transparent; }
/* ── Typography helpers ────────────────────────────── */
.font-display { font-family: 'Space Grotesk', sans-serif; }
.font-mono-v2 { font-family: 'JetBrains Mono', monospace; font-variant-numeric: tabular-nums; }
@@ -0,0 +1,249 @@
<script setup lang="ts">
/**
* GalaxyBackground Canvas Starfield + Aurora Blobs
*
* Ported from assets/galaxy.js (design_handoff_nexus_v2).
* Auto-mounts onMounted; cleans up onUnmounted.
* Fixed overlay with z-index:0 and pointer-events:none.
*/
import { onMounted, onUnmounted, ref } from 'vue'
const rootRef = ref<HTMLElement | null>(null)
interface Star {
x: number
y: number
r: number
a: number
tw: number
ph: number
hue: number
dx: number
dy: number
}
interface Shoot {
x: number
y: number
len: number
sp: number
ang: number
life: number
}
let resizeObserver: ResizeObserver | null = null
let animFrameId = 0
let canvas: HTMLCanvasElement | null = null
let ctx: CanvasRenderingContext2D | null = null
function mount(root: HTMLElement) {
canvas = document.createElement('canvas')
root.appendChild(canvas)
ctx = canvas.getContext('2d')
if (!ctx) return
const dpr = Math.min(window.devicePixelRatio || 1, 2)
let stars: Star[] = []
let shoots: Shoot[] = []
let W = 0
let H = 0
let t = 0
function resize() {
const r = root.getBoundingClientRect()
W = r.width
H = r.height
canvas!.width = W * dpr
canvas!.height = H * dpr
ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)
const count = Math.round((W * H) / 5200)
stars = []
for (let i = 0; i < count; i++) {
stars.push({
x: Math.random() * W,
y: Math.random() * H,
r: Math.random() * 1.3 + 0.25,
a: Math.random() * 0.6 + 0.2,
tw: Math.random() * 0.025 + 0.004,
ph: Math.random() * Math.PI * 2,
hue: Math.random() < 0.5 ? 230 : 270,
dx: (Math.random() - 0.5) * 0.04,
dy: (Math.random() - 0.5) * 0.04,
})
}
}
function spawnShoot() {
const fromLeft = Math.random() < 0.6
shoots.push({
x: fromLeft ? -40 : W * (0.4 + Math.random() * 0.5),
y: Math.random() * H * 0.5,
len: 90 + Math.random() * 120,
sp: 6 + Math.random() * 5,
ang: Math.random() * 0.3 + 0.15,
life: 1,
})
}
function frame() {
ctx!.clearRect(0, 0, W, H)
t += 1
// Draw stars
for (let i = 0; i < stars.length; i++) {
const s = stars[i]
s.ph += s.tw
const a = s.a * (0.55 + 0.45 * Math.sin(s.ph))
s.x += s.dx
s.y += s.dy
if (s.x < 0) s.x = W
if (s.x > W) s.x = 0
if (s.y < 0) s.y = H
if (s.y > H) s.y = 0
ctx!.beginPath()
ctx!.fillStyle = `hsla(${s.hue},90%,82%,${a})`
ctx!.arc(s.x, s.y, s.r, 0, Math.PI * 2)
ctx!.fill()
// Glow for larger stars
if (s.r > 1) {
ctx!.beginPath()
ctx!.fillStyle = `hsla(${s.hue},95%,80%,${a * 0.12})`
ctx!.arc(s.x, s.y, s.r * 3.5, 0, Math.PI * 2)
ctx!.fill()
}
}
// Shooting stars
if (Math.random() < 0.004 && shoots.length < 2) spawnShoot()
for (let j = shoots.length - 1; j >= 0; j--) {
const sh = shoots[j]
sh.x += Math.cos(sh.ang) * sh.sp
sh.y += Math.sin(sh.ang) * sh.sp
sh.life -= 0.006
const ex = sh.x - Math.cos(sh.ang) * sh.len
const ey = sh.y - Math.sin(sh.ang) * sh.len
const g = ctx!.createLinearGradient(sh.x, sh.y, ex, ey)
g.addColorStop(0, `rgba(200,210,255,${0.9 * sh.life})`)
g.addColorStop(1, 'rgba(160,120,255,0)')
ctx!.strokeStyle = g
ctx!.lineWidth = 2
ctx!.lineCap = 'round'
ctx!.beginPath()
ctx!.moveTo(sh.x, sh.y)
ctx!.lineTo(ex, ey)
ctx!.stroke()
if (sh.life <= 0 || sh.x > W + 60 || sh.y > H + 60) shoots.splice(j, 1)
}
animFrameId = requestAnimationFrame(frame)
}
resizeObserver = new ResizeObserver(() => resize())
resizeObserver.observe(root)
resize()
frame()
}
function cleanup() {
if (resizeObserver) {
resizeObserver.disconnect()
resizeObserver = null
}
if (animFrameId) {
cancelAnimationFrame(animFrameId)
animFrameId = 0
}
if (canvas && canvas.parentNode) {
canvas.parentNode.removeChild(canvas)
}
canvas = null
ctx = null
}
onMounted(() => {
if (rootRef.value) mount(rootRef.value)
})
onUnmounted(() => {
cleanup()
})
</script>
<template>
<div ref="rootRef" class="galaxy-bg">
<div class="aurora a1"></div>
<div class="aurora a2"></div>
<div class="aurora a3"></div>
</div>
</template>
<style scoped>
.galaxy-bg {
position: fixed;
inset: 0;
z-index: 0;
overflow: hidden;
background:
radial-gradient(1200px 800px at 18% -8%, rgba(79,124,255,.20), transparent 60%),
radial-gradient(1000px 760px at 92% 8%, rgba(181,87,246,.18), transparent 60%),
radial-gradient(900px 700px at 60% 110%, rgba(70,60,180,.20), transparent 60%),
linear-gradient(180deg, #070512, #0a0818 60%, #060410);
pointer-events: none;
}
.galaxy-bg canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
.aurora {
position: absolute;
border-radius: 50%;
filter: blur(70px);
opacity: 0.5;
mix-blend-mode: screen;
will-change: transform;
}
.a1 {
width: 46vw;
height: 46vw;
left: -8vw;
top: -14vw;
background: radial-gradient(circle, rgba(79,124,255,.55), transparent 65%);
animation: drift1 26s ease-in-out infinite;
}
.a2 {
width: 40vw;
height: 40vw;
right: -10vw;
top: 2vw;
background: radial-gradient(circle, rgba(181,87,246,.5), transparent 65%);
animation: drift2 32s ease-in-out infinite;
}
.a3 {
width: 42vw;
height: 42vw;
left: 34vw;
bottom: -18vw;
background: radial-gradient(circle, rgba(95,80,220,.45), transparent 65%);
animation: drift3 30s ease-in-out infinite;
}
@keyframes drift1 {
0%, 100% { transform: translate(0, 0) scale(1); }
50% { transform: translate(8vw, 6vw) scale(1.12); }
}
@keyframes drift2 {
0%, 100% { transform: translate(0, 0) scale(1); }
50% { transform: translate(-7vw, 5vw) scale(1.1); }
}
@keyframes drift3 {
0%, 100% { transform: translate(0, 0) scale(1); }
50% { transform: translate(4vw, -6vw) scale(1.15); }
}
</style>
@@ -1,201 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
import { Clock } from '@lucide/vue'
type InitiativeStatus = 'healthy' | 'attention' | 'blocked' | 'paused' | 'completed'
interface Initiative {
title: string
progress: number
openTasks: number
blockers: number
status: InitiativeStatus
lastActivity: string
}
const initiatives = ref<Initiative[]>([
{ title: 'OpenClaw Companion', progress: 55, openTasks: 7, blockers: 2, status: 'healthy', lastActivity: 'vor 8 Minuten' },
{ title: '2D Idle Game', progress: 42, openTasks: 4, blockers: 0, status: 'healthy', lastActivity: 'vor 2 Stunden' },
{ title: 'Deutsch B2', progress: 73, openTasks: 3, blockers: 0, status: 'attention', lastActivity: 'vor 1 Stunde' },
{ title: 'Nexus Dashboard', progress: 60, openTasks: 3, blockers: 0, status: 'healthy', lastActivity: 'vor 5 Minuten' },
])
const statusMeta: Record<InitiativeStatus, { label: string; color: string; bg: string }> = {
healthy: { label: 'Healthy', color: '#22c55e', bg: 'rgba(34,197,94,0.1)' },
attention: { label: 'Needs Attention', color: '#eab308', bg: 'rgba(234,179,8,0.1)' },
blocked: { label: 'Blocked', color: '#ef4444', bg: 'rgba(239,68,68,0.1)' },
paused: { label: 'Paused', color: '#6b7280', bg: 'rgba(107,114,128,0.1)' },
completed: { label: 'Completed', color: '#3b82f6', bg: 'rgba(59,130,246,0.1)' },
}
function onInitiativeClick(title: string) {
console.log('[Dashboard] Open initiative:', title)
}
</script>
<template>
<div class="initiatives-section">
<h2>Active Initiatives</h2>
<div class="initiatives-grid">
<div
v-for="(init, idx) in initiatives"
:key="idx"
:class="['initiative-card', 'status-' + init.status]"
@click="onInitiativeClick(init.title)"
role="button"
tabindex="0"
@keyup.enter="onInitiativeClick(init.title)"
>
<div class="init-head">
<h3>{{ init.title }}</h3>
<span
class="status-badge"
:style="{
color: statusMeta[init.status].color,
background: statusMeta[init.status].bg,
}"
>
{{ statusMeta[init.status].label }}
</span>
</div>
<div class="progress-bar">
<div
class="progress-fill"
:style="{ width: init.progress + '%' }"
></div>
</div>
<div class="progress-label">{{ init.progress }}%</div>
<div class="init-stats">
<span>{{ init.openTasks }} offene Aufgaben</span>
<span v-if="init.blockers">&middot; {{ init.blockers }} Blocker</span>
</div>
<div class="init-meta">
<Clock :size="11" />
<span>Letzte Aktivität {{ init.lastActivity }}</span>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.initiatives-section {
display: flex;
flex-direction: column;
gap: 10px;
padding: 18px;
background: rgba(22, 27, 34, 0.8);
border: 1px solid rgba(139, 124, 246, 0.12);
border-radius: 16px;
box-shadow: 0 4px 24px rgba(0,0,0,0.3);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
transition: all 0.2s ease;
}
.initiatives-section:hover {
border-color: rgba(139, 124, 246, 0.18);
}
.initiatives-section h2 {
font-size: 14px;
font-weight: 600;
margin: 0;
color: #e8eaf0;
}
.initiatives-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 10px;
}
.initiative-card {
background: rgba(13, 17, 23, 0.5);
border: 1px solid rgba(139, 124, 246, 0.08);
border-radius: 14px;
padding: 14px;
cursor: pointer;
transition: all 0.2s ease;
}
.initiative-card:hover {
transform: scale(1.02);
border-color: rgba(139, 124, 246, 0.2);
box-shadow: 0 8px 24px rgba(0,0,0,0.3);
}
.initiative-card:focus-visible {
outline: 2px solid #a78bfa;
outline-offset: 2px;
}
.init-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
gap: 8px;
}
.init-head h3 {
font-size: 12px;
font-weight: 600;
margin: 0;
color: #e8eaf0;
}
.status-badge {
font-size: 8px;
font-weight: 700;
padding: 2px 7px;
border-radius: 12px;
white-space: nowrap;
flex-shrink: 0;
letter-spacing: 0.02em;
}
.progress-bar {
height: 4px;
background: rgba(139, 124, 246, 0.1);
border-radius: 4px;
margin-bottom: 4px;
overflow: hidden;
}
.progress-fill {
height: 100%;
border-radius: 4px;
background: linear-gradient(90deg, #a78bfa, #8b5cf6);
transition: width 0.5s ease;
}
.initiative-card.status-attention .progress-fill {
background: linear-gradient(90deg, #eab308, #f59e0b);
}
.initiative-card.status-blocked .progress-fill {
background: linear-gradient(90deg, #ef4444, #dc2626);
}
.progress-label {
font-size: 10px;
color: #6b7385;
margin-bottom: 4px;
}
.init-stats {
font-size: 9px;
color: #6b7385;
margin-bottom: 4px;
display: flex;
gap: 4px;
flex-wrap: wrap;
}
.init-meta {
display: flex;
align-items: center;
gap: 4px;
font-size: 9px;
color: #6b7385;
}
.init-meta svg {
flex-shrink: 0;
}
@media (max-width: 900px) {
.initiatives-grid {
grid-template-columns: 1fr 1fr;
}
}
@media (max-width: 600px) {
.initiatives-grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -1,229 +0,0 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { CheckCircle2, Circle, AlertTriangle } from '@lucide/vue'
interface AgendaItem {
text: string
time?: string
done?: boolean
overdue?: boolean
}
const STORAGE_KEY = 'nexus-agenda-done'
const agendaToday = ref<AgendaItem[]>([
{ text: 'Teammeeting', time: '14:00' },
{ text: 'Deutsch lernen', time: '18:00' },
{ text: 'Steuerunterlagen prüfen' },
{ text: 'Dungeon-Balance abschließen' },
])
const agendaTomorrow = ref<AgendaItem[]>([
{ text: 'GitHub Issue #23' },
{ text: 'Backup überprüfen' },
])
const agendaOverdue = ref<AgendaItem[]>([
{ text: 'Hangfire konfigurieren', overdue: true },
])
function loadDoneStates() {
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return
const keys: string[] = JSON.parse(raw)
const set = new Set(keys)
const sections = [
{ items: agendaToday.value, prefix: 'today' },
{ items: agendaTomorrow.value, prefix: 'tomorrow' },
{ items: agendaOverdue.value, prefix: 'overdue' },
]
for (const { items, prefix } of sections) {
items.forEach((item, i) => {
if (set.has(`${prefix}-${i}`)) item.done = true
})
}
} catch { /* ignore malformed storage */ }
}
function saveDoneStates() {
const keys: string[] = []
const sections = [
{ items: agendaToday.value, prefix: 'today' },
{ items: agendaTomorrow.value, prefix: 'tomorrow' },
{ items: agendaOverdue.value, prefix: 'overdue' },
]
for (const { items, prefix } of sections) {
items.forEach((item, i) => {
if (item.done) keys.push(`${prefix}-${i}`)
})
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(keys))
}
function toggleAgendaItem(item: AgendaItem) {
item.done = !item.done
saveDoneStates()
}
onMounted(() => {
loadDoneStates()
})
</script>
<template>
<div class="agenda-panel">
<h2>Agenda</h2>
<div class="agenda-section">
<h3>Heute</h3>
<div
v-for="(item, idx) in agendaToday"
:key="'today-' + idx"
:class="['agenda-item', { done: item.done }]"
@click="toggleAgendaItem(item)"
>
<button class="agenda-check">
<CheckCircle2 v-if="item.done" :size="14" class="checked" />
<Circle v-else :size="14" />
</button>
<span class="agenda-text">{{ item.text }}</span>
<span v-if="item.time" class="agenda-time">{{ item.time }}</span>
</div>
</div>
<div class="agenda-section">
<h3>Morgen</h3>
<div
v-for="(item, idx) in agendaTomorrow"
:key="'tomorrow-' + idx"
:class="['agenda-item', { done: item.done }]"
@click="toggleAgendaItem(item)"
>
<button class="agenda-check">
<CheckCircle2 v-if="item.done" :size="14" class="checked" />
<Circle v-else :size="14" />
</button>
<span class="agenda-text">{{ item.text }}</span>
</div>
</div>
<div class="agenda-section">
<h3 class="overdue-heading">
<AlertTriangle :size="12" />
Überfällig
</h3>
<div
v-for="(item, idx) in agendaOverdue"
:key="'overdue-' + idx"
class="agenda-item overdue"
>
<button class="agenda-check">
<AlertTriangle :size="14" class="overdue-icon" />
</button>
<span class="agenda-text">{{ item.text }}</span>
<span class="agenda-sub">seit 2 Tagen</span>
</div>
</div>
</div>
</template>
<style scoped>
.agenda-panel {
display: flex;
flex-direction: column;
gap: 10px;
padding: 18px;
background: rgba(22, 27, 34, 0.8);
border: 1px solid rgba(139, 124, 246, 0.12);
border-radius: 16px;
box-shadow: 0 4px 24px rgba(0,0,0,0.3);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
transition: all 0.2s ease;
}
.agenda-panel:hover {
border-color: rgba(139, 124, 246, 0.18);
}
.agenda-panel h2 {
font-size: 14px;
font-weight: 600;
margin: 0;
color: #e8eaf0;
}
.agenda-section h3 {
display: flex;
align-items: center;
gap: 5px;
font-size: 10px;
font-weight: 700;
color: #6b7385;
text-transform: uppercase;
letter-spacing: 0.08em;
margin: 0 0 4px;
padding-bottom: 4px;
border-bottom: 1px solid rgba(139, 124, 246, 0.06);
}
.overdue-heading {
color: #ef4444 !important;
border-bottom-color: rgba(239, 68, 68, 0.15) !important;
}
.agenda-item {
display: flex;
align-items: center;
gap: 7px;
padding: 5px 6px;
border-radius: 6px;
cursor: pointer;
transition: all 0.15s;
}
.agenda-item:hover {
background: rgba(139, 124, 246, 0.04);
}
.agenda-item.done {
opacity: 0.5;
}
.agenda-item.done .agenda-text {
text-decoration: line-through;
}
.agenda-check {
display: grid;
place-items: center;
background: none;
border: none;
color: #6b7385;
padding: 0;
cursor: pointer;
flex-shrink: 0;
}
.agenda-check .checked {
color: #22c55e;
}
.overdue .overdue-icon {
color: #ef4444;
}
.agenda-text {
flex: 1;
font-size: 10.5px;
color: #7e8799;
}
.agenda-time {
font-size: 9px;
color: #6b7385;
flex-shrink: 0;
}
.agenda-sub {
font-size: 8px;
color: #ef4444;
flex-shrink: 0;
}
.agenda-item.overdue {
background: rgba(239, 68, 68, 0.06);
}
@media (max-width: 900px) {
.agenda-panel {
order: 3;
}
}
</style>
@@ -1,441 +0,0 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { X, ExternalLink } from '@lucide/vue'
import type { AgentNodeData } from '../../composables/useDashboardData'
import { useToast } from '../../composables/useToast'
import Button from '@/components/ui/button/Button.vue'
import Badge from '@/components/ui/Badge.vue'
import Select from '@/components/ui/Select.vue'
const props = defineProps<{
agent: AgentNodeData
runtime: string
}>()
const emit = defineEmits<{
close: []
}>()
const toast = useToast()
interface ModelOption {
id: string
name: string
provider: string
}
const availableModels = ref<ModelOption[]>([])
const selectedModel = ref('')
const currentModel = ref('')
const saving = ref(false)
async function loadModels() {
try {
const res = await fetch('/api/dashboard/models', { credentials: 'include' })
if (res.ok) {
availableModels.value = await res.json()
}
} catch {
// silent
}
}
async function loadCurrentModel() {
try {
const res = await fetch(`/api/dashboard/agents/${props.agent.id}/model`, { credentials: 'include' })
if (res.ok) {
const data = await res.json()
selectedModel.value = data.model
currentModel.value = data.model
}
} catch {
// silent
}
}
async function saveModel() {
saving.value = true
try {
const res = await fetch(`/api/dashboard/agents/${props.agent.id}/model`, {
method: 'PUT',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: selectedModel.value }),
})
if (res.ok) {
currentModel.value = selectedModel.value
toast.success('Model updated successfully')
} else {
toast.error('Failed to update model')
}
} catch {
toast.error('Connection error')
} finally {
saving.value = false
}
}
onMounted(async () => {
await loadModels()
await loadCurrentModel()
})
</script>
<template>
<Teleport to="body">
<div class="modal-overlay" @click.self="$emit('close')">
<div class="modal-card" :style="{ '--agent-color': agent.color }">
<!-- Header -->
<div class="modal-header">
<div class="modal-title-row">
<div class="modal-avatar" :style="{ background: `${agent.color}18`, color: agent.color }">
<span class="avatar-letter">{{ agent.name.charAt(0) }}</span>
</div>
<div>
<h2>{{ agent.name }}</h2>
<span class="modal-role">{{ agent.role }}</span>
<a :href="`/agents/${agent.id}`" class="agent-link-btn" title="Open agent config">
<ExternalLink :size="12" />
</a>
</div>
</div>
<Button variant="ghost" size="icon" class="h-8 w-8" @click="$emit('close')" aria-label="Close">
<X :size="16" />
</Button>
</div>
<!-- Status -->
<section class="modal-section">
<h3 class="section-label">Status</h3>
<div class="status-row">
<Badge
:variant="agent.active ? 'default' : 'secondary'"
:class="agent.active ? 'bg-[rgba(81,212,154,0.1)] text-[#51d49a] border-[rgba(81,212,154,0.3)]' : 'bg-[rgba(107,115,133,0.08)] text-[#6b7385] border-[rgba(107,115,133,0.2)]'"
>
<span class="status-dot" :class="{ active: agent.active }" />
{{ agent.active ? 'Active' : 'Idle' }}
</Badge>
<span v-if="agent.active" class="footer-badge">Runtime: {{ runtime }}</span>
</div>
</section>
<!-- Description -->
<p class="modal-desc">{{ agent.description }}</p>
<!-- Tags -->
<section class="modal-section">
<h3 class="section-label">Tags</h3>
<div class="modal-tags-row">
<Badge
v-for="tag in agent.tags"
:key="tag"
variant="outline"
:style="{ background: `${agent.color}18`, color: agent.color, borderColor: `${agent.color}30` }"
>
{{ tag }}
</Badge>
</div>
</section>
<!-- Current Task -->
<section class="modal-section">
<h3 class="section-label">Current Task</h3>
<p class="section-value">
{{ agent.currentTask }}
<span v-if="agent.active" class="thinking-dots">
<span class="thinking-dot blue"></span>
<span class="thinking-dot violet"></span>
</span>
</p>
</section>
<!-- Goal + Progress -->
<section class="modal-section">
<h3 class="section-label">Goal</h3>
<p class="section-value">{{ agent.goal }}</p>
<div class="progress-row">
<span class="progress-pct">{{ agent.progress }}%</span>
<div class="progress-track">
<div class="progress-fill" :style="{ width: `${agent.progress}%` }"></div>
</div>
</div>
</section>
<!-- Model -->
<section class="modal-section">
<h3 class="section-label">Model</h3>
<div class="model-select-row">
<Select v-model="selectedModel" class="flex-1 text-xs border-[#a78bfa]">
<option v-for="m in availableModels" :key="m.id" :value="m.id">
{{ m.name }} ({{ m.provider }})
</option>
</Select>
<Button
variant="default"
size="sm"
class="bg-[#a78bfa] hover:bg-[#c4b5fd]"
:disabled="saving || selectedModel === currentModel"
@click="saveModel"
>
{{ saving ? 'Saving...' : 'Save' }}
</Button>
</div>
</section>
<!-- Footer Stats -->
<div class="modal-footer">
<Badge :class="agent.active ? 'bg-[rgba(81,212,154,0.06)] text-[#51d49a] border-[rgba(81,212,154,0.25)]' : 'bg-[rgba(107,115,133,0.04)] text-[#6b7385] border-[rgba(107,115,133,0.15)]'">
{{ agent.active ? '● Active' : '○ Idle' }}
</Badge>
<span v-if="agent.active" class="footer-badge">{{ runtime }}</span>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
.modal-overlay {
position: fixed;
inset: 0;
z-index: 1000;
display: grid;
place-items: center;
padding: 24px;
background: rgba(0, 0, 0, 0.55);
backdrop-filter: blur(4px);
animation: overlay-in 0.2s ease;
}
@keyframes overlay-in {
from { opacity: 0; }
to { opacity: 1; }
}
.modal-card {
width: min(480px, 100%);
max-height: 80vh;
overflow-y: auto;
padding: 24px;
background: rgba(18, 22, 30, 0.96);
border: 1px solid color-mix(in srgb, var(--agent-color) 25%, transparent);
border-radius: 16px;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
animation: card-in 0.25s ease;
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
@keyframes card-in {
from { opacity: 0; transform: translateY(12px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.modal-card::-webkit-scrollbar {
width: 5px;
}
.modal-card::-webkit-scrollbar-track {
background: transparent;
}
.modal-card::-webkit-scrollbar-thumb {
background: rgba(139, 124, 246, 0.2);
border-radius: 3px;
}
.modal-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 16px;
}
.modal-title-row {
display: flex;
align-items: center;
gap: 14px;
}
.modal-avatar {
width: 44px;
height: 44px;
display: grid;
place-items: center;
border-radius: 12px;
flex-shrink: 0;
}
.avatar-letter {
font-size: 18px;
font-weight: 700;
}
.modal-title-row h2 {
margin: 0;
font-size: 18px;
font-weight: 700;
color: #e8eaf0;
}
.modal-role {
font-size: 10px;
color: #6b7385;
font-weight: 500;
}
.agent-link-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
margin-left: 4px;
border: none;
border-radius: 6px;
background: transparent;
color: #6b7385;
opacity: 0.4;
cursor: pointer;
transition: opacity 0.2s;
flex-shrink: 0;
text-decoration: none;
vertical-align: middle;
}
.agent-link-btn:hover {
opacity: 1;
color: var(--agent-color);
}
.modal-desc {
font-size: 11px;
line-height: 1.55;
color: #7e8799;
margin: 0 0 18px;
padding-bottom: 14px;
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
.modal-section {
margin-bottom: 16px;
}
.section-label {
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #6b7385;
margin: 0 0 6px;
}
.section-value {
margin: 0;
font-size: 12px;
color: #e8eaf0;
line-height: 1.4;
display: flex;
align-items: center;
gap: 8px;
}
/* Status */
.status-row {
display: flex;
align-items: center;
gap: 12px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #6b7385;
transition: all 0.3s ease;
}
.status-dot.active {
background: #51d49a;
box-shadow: 0 0 8px rgba(81, 212, 154, 0.6);
animation: pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.6; transform: scale(1.2); }
}
/* Tags */
.modal-tags-row {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
/* Progress */
.progress-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 8px;
}
.progress-pct {
font-size: 11px;
font-weight: 600;
color: #7e8799;
flex-shrink: 0;
font-variant-numeric: tabular-nums;
}
.progress-track {
flex: 1;
height: 4px;
background: rgba(255, 255, 255, 0.06);
border-radius: 4px;
overflow: hidden;
}
.progress-fill {
height: 100%;
border-radius: 4px;
background: var(--agent-color);
transition: width 0.5s ease;
}
/* Thinking Dots */
.thinking-dots {
display: inline-flex;
gap: 6px;
flex-shrink: 0;
}
.thinking-dot {
width: 7px;
height: 7px;
border-radius: 50%;
}
.thinking-dot.blue {
background: #3b82f6;
box-shadow: 0 0 8px #3b82f6;
animation: pulse-dot-blue 1.2s ease-in-out infinite;
}
.thinking-dot.violet {
background: #8b7cf6;
box-shadow: 0 0 8px #8b7cf6;
animation: pulse-dot-violet 1.8s ease-in-out infinite 0.3s;
}
@keyframes pulse-dot-blue {
0%, 100% { opacity: 0.4; transform: scale(0.7); }
50% { opacity: 1; transform: scale(1.3); }
}
@keyframes pulse-dot-violet {
0%, 100% { opacity: 0.3; transform: scale(0.6); }
50% { opacity: 1; transform: scale(1.4); }
}
/* Footer */
.modal-footer {
display: flex;
gap: 10px;
padding-top: 14px;
margin-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.footer-badge {
font-size: 9px;
font-weight: 600;
padding: 4px 10px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid rgba(255, 255, 255, 0.06);
color: #7e8799;
}
/* Model Selector */
.model-select-row {
display: flex;
gap: 8px;
align-items: center;
}
</style>
@@ -1,90 +0,0 @@
<script setup lang="ts">
import { Bot } from '@lucide/vue'
import type { ChatMessage } from '../../composables/useDashboardData'
import { renderMarkdown } from '../../utils/markdown'
defineProps<{
messages: ChatMessage[]
irisBusy: boolean
elapsedSeconds: number
}>()
function formatTime(ts: number): string {
const d = new Date(ts)
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
</script>
<template>
<div class="flex flex-col gap-2.5">
<div
v-for="msg in messages"
:key="msg.id"
:class="['flex gap-2', msg.sender === 'user' ? 'justify-end' : '']"
>
<div v-if="msg.sender === 'iris'" class="flex-shrink-0 self-end w-6 h-6 grid place-items-center rounded-lg bg-[rgba(167,139,250,0.15)] text-[#a78bfa]">
<Bot :size="12" />
</div>
<div
:class="[
'px-3 py-2 rounded-lg text-[10.5px] leading-[1.45] max-w-[85%]',
msg.sender === 'iris'
? 'bg-[rgba(167,139,250,0.08)] border border-[rgba(167,139,250,0.1)] text-[#d4d8e0]'
: 'bg-[rgba(59,130,246,0.12)] border border-[rgba(59,130,246,0.15)] text-[#e8eaf0]',
]"
>
<div v-if="msg.sender === 'iris'" v-html="renderMarkdown(msg.text)" class="msg-md"></div>
<p v-else class="m-0">{{ msg.text }}</p>
<div
:class="[
'text-[8px] mt-1 opacity-50',
msg.sender === 'user' ? 'text-right' : 'text-left',
]"
>
{{ formatTime(msg.timestamp) }}
</div>
</div>
</div>
<!-- Busy Bubble -->
<div v-if="irisBusy" class="flex gap-2 max-w-[75%]">
<div class="flex-shrink-0 self-end w-6 h-6 grid place-items-center rounded-lg bg-[rgba(167,139,250,0.15)] text-[#a78bfa]">
<Bot :size="12" />
</div>
<div class="px-3 py-2 rounded-lg text-[10.5px] bg-[rgba(167,139,250,0.08)] border border-[rgba(167,139,250,0.18)] text-[#c4c8d4]">
<div class="flex items-center gap-2">
<span class="w-[7px] h-[7px] rounded-full bg-[#a78bfa] animate-pulse flex-shrink-0" />
<span>Denkt nach...</span>
</div>
<div class="text-[8px] mt-1 opacity-50">läuft seit {{ elapsedSeconds }}s</div>
</div>
</div>
<div v-if="messages.length === 0" class="flex-1 grid place-items-center text-center py-8">
<p class="text-[10px] text-[#6b7385] max-w-[180px] leading-[1.4] m-0">
No messages yet. Start a conversation with Iris.
</p>
</div>
</div>
</template>
<style scoped>
.msg-md { line-height: 1.55; }
.msg-md :deep(p) { margin: 0 0 6px 0; }
.msg-md :deep(p:last-child) { margin-bottom: 0; }
.msg-md :deep(strong) { color: #e8eaf0; font-weight: 700; }
.msg-md :deep(em) { font-style: italic; color: #c4c8d4; }
.msg-md :deep(code) { background: rgba(0,0,0,0.3); padding: 1px 5px; border-radius: 4px; font-family: 'JetBrains Mono','Fira Code',monospace; font-size: 10px; color: #f472b6; }
.msg-md :deep(pre) { background: rgba(0,0,0,0.35); padding: 8px 10px; border-radius: 8px; overflow-x: auto; margin: 6px 0; border: 1px solid rgba(255,255,255,0.04); }
.msg-md :deep(pre code) { background: none; padding: 0; font-size: 10px; color: #d4d8e0; }
.msg-md :deep(a) { color: #a78bfa; text-decoration: underline; text-underline-offset: 2px; }
.msg-md :deep(a:hover) { color: #c4b5fd; }
.msg-md :deep(ul) { margin: 4px 0; padding-left: 16px; }
.msg-md :deep(li) { margin: 2px 0; }
.msg-md :deep(h1), .msg-md :deep(h2), .msg-md :deep(h3), .msg-md :deep(h4), .msg-md :deep(h5), .msg-md :deep(h6) { margin: 8px 0 4px 0; color: #e8eaf0; font-weight: 700; line-height: 1.3; }
.msg-md :deep(h1) { font-size: 13px; }
.msg-md :deep(h2) { font-size: 12px; }
.msg-md :deep(h3) { font-size: 11px; }
.msg-md :deep(h4), .msg-md :deep(h5), .msg-md :deep(h6) { font-size: 10.5px; }
.msg-md :deep(hr) { border: none; border-top: 1px solid rgba(255,255,255,0.08); margin: 8px 0; }
</style>
@@ -1,291 +0,0 @@
<script setup lang="ts">
import { ref, nextTick, watch, onUnmounted } from 'vue'
import { Bot, Send, Maximize2 } from '@lucide/vue'
import type { ChatMessage } from '../../composables/useDashboardData'
import { useDashboardData } from '../../composables/useDashboardData'
import Button from '@/components/ui/button/Button.vue'
import Textarea from '@/components/ui/Textarea.vue'
import Dialog from '@/components/ui/Dialog.vue'
import DialogHeader from '@/components/ui/DialogHeader.vue'
import DialogTitle from '@/components/ui/DialogTitle.vue'
import ChatMessageList from './ChatMessageList.vue'
const props = defineProps<{
messages: ChatMessage[]
irisBusy: boolean
irisFocus: string
}>()
const { sendChatMessage, busySince } = useDashboardData()
const elapsedSeconds = ref(0)
let elapsedInterval: ReturnType<typeof setInterval> | null = null
function startElapsedTimer(): void {
stopElapsedTimer()
const update = () => {
if (busySince.value > 0) {
elapsedSeconds.value = Math.floor((Date.now() - busySince.value) / 1000)
}
}
update()
elapsedInterval = setInterval(update, 1000)
}
function stopElapsedTimer(): void {
if (elapsedInterval) {
clearInterval(elapsedInterval)
elapsedInterval = null
}
}
watch(() => props.irisBusy, (busy) => {
if (busy) {
startElapsedTimer()
} else {
stopElapsedTimer()
elapsedSeconds.value = 0
}
}, { immediate: true })
onUnmounted(() => {
stopElapsedTimer()
})
const inputText = ref('')
const chatListRef = ref<HTMLElement | null>(null)
const chatModalListRef = ref<HTMLElement | null>(null)
const dialogOpen = ref(false)
function sendMessage(): void {
if (!inputText.value.trim()) return
sendChatMessage(inputText.value)
inputText.value = ''
}
watch(
() => props.messages.length,
async () => {
await nextTick()
const el = dialogOpen.value ? chatModalListRef.value : chatListRef.value
if (el) {
el.scrollTop = el.scrollHeight
}
}
)
</script>
<template>
<!-- Inline Chat Panel -->
<div class="chat-panel">
<div class="chat-header">
<div class="chat-header-left">
<Bot :size="16" class="text-[#a78bfa]" />
<h2>Iris Chat</h2>
</div>
<Button variant="ghost" size="icon" class="h-7 w-7" @click="dialogOpen = true" title="Open larger chat">
<Maximize2 :size="14" />
</Button>
</div>
<!-- Focus Bar -->
<div v-if="irisBusy && irisFocus" class="focus-bar">
<span class="focus-label">Current Focus</span>
<span class="focus-text">{{ irisFocus }}</span>
</div>
<!-- Messages -->
<div ref="chatListRef" class="chat-messages">
<ChatMessageList
:messages="messages"
:iris-busy="irisBusy"
:elapsed-seconds="elapsedSeconds"
/>
</div>
<!-- Input -->
<div class="chat-input-row">
<Textarea
v-model="inputText"
rows="1"
placeholder="Type a message..."
class="min-h-0 h-9 resize-none text-xs bg-black/30 border-[rgba(255,255,255,0.08)] text-[#e8eaf0] placeholder:text-[#6b7385] text-[10px]"
@keyup.enter.exact="sendMessage"
/>
<Button
size="icon"
class="h-8 w-8 bg-[#a78bfa] hover:bg-[#c4b5fd] flex-shrink-0"
:disabled="!inputText.trim()"
@click="sendMessage"
aria-label="Send"
>
<Send :size="14" />
</Button>
</div>
</div>
<!-- Expanded Chat Dialog -->
<Dialog :open="dialogOpen" class="sm:max-w-[820px] sm:h-[78vh] p-0 gap-0" @update:open="dialogOpen = $event">
<template #default>
<DialogHeader class="flex-row items-center justify-between px-5 py-4 border-b border-[rgba(255,255,255,0.06)]">
<div class="flex items-center gap-2">
<Bot :size="18" class="text-[#a78bfa]" />
<DialogTitle>Iris Chat</DialogTitle>
</div>
<Button variant="ghost" size="icon" class="h-7 w-7" @click="dialogOpen = false" aria-label="Close">
<span class="text-lg leading-none">&times;</span>
</Button>
</DialogHeader>
<div v-if="irisBusy && irisFocus" class="focus-bar !px-5">
<span class="focus-label">Current Focus</span>
<span class="focus-text">{{ irisFocus }}</span>
</div>
<div ref="chatModalListRef" class="flex-1 overflow-y-auto px-5 py-4">
<ChatMessageList
:messages="messages"
:iris-busy="irisBusy"
:elapsed-seconds="elapsedSeconds"
/>
</div>
<div class="flex gap-2 px-4 py-3 border-t border-[rgba(255,255,255,0.06)]">
<Textarea
v-model="inputText"
rows="1"
placeholder="Type a message..."
class="min-h-0 h-10 resize-none text-sm bg-black/30 border-[rgba(255,255,255,0.08)] text-[#e8eaf0] placeholder:text-[#6b7385]"
@keyup.enter.exact="sendMessage"
/>
<Button
size="icon"
class="h-10 w-10 bg-[#a78bfa] hover:bg-[#c4b5fd] flex-shrink-0"
:disabled="!inputText.trim()"
@click="sendMessage"
aria-label="Send"
>
<Send :size="18" />
</Button>
</div>
</template>
</Dialog>
</template>
<style scoped>
.chat-panel {
display: flex;
flex-direction: column;
flex: 1;
min-height: 360px;
max-height: 480px;
background: rgba(22, 27, 34, 0.75);
border: 1px solid rgba(139, 124, 246, 0.12);
border-radius: 16px;
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.3);
transition: border-color 0.2s ease;
overflow: hidden;
}
.chat-panel:hover {
border-color: rgba(139, 124, 246, 0.18);
}
.chat-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
.chat-header-left {
display: flex;
align-items: center;
gap: 8px;
}
.chat-header h2 {
margin: 0;
font-size: 13px;
font-weight: 600;
color: #e8eaf0;
}
/* Focus Bar */
.focus-bar {
display: flex;
flex-direction: column;
gap: 3px;
padding: 8px 16px;
background: rgba(234, 179, 8, 0.04);
border-bottom: 1px solid rgba(234, 179, 8, 0.08);
}
.focus-label {
font-size: 8px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
color: #eab308;
}
.focus-text {
font-size: 10px;
color: #7e8799;
line-height: 1.3;
}
/* Messages */
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 12px 16px;
}
.chat-messages::-webkit-scrollbar {
width: 5px;
}
.chat-messages::-webkit-scrollbar-track {
background: transparent;
}
.chat-messages::-webkit-scrollbar-thumb {
background: rgba(139, 124, 246, 0.2);
border-radius: 3px;
}
/* Input */
.chat-input-row {
display: flex;
gap: 6px;
padding: 10px 12px;
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
/* ── Mobile: compact mode ── */
@media (max-width: 768px) {
.chat-panel {
min-height: 280px;
max-height: 360px;
border-radius: 12px;
}
.chat-header {
padding: 10px 12px;
}
.chat-header h2 {
font-size: 11px;
}
.chat-messages {
padding: 8px 12px;
}
.chat-input-row {
padding: 8px 10px;
gap: 4px;
}
.focus-bar {
padding: 6px 12px;
}
.focus-label {
font-size: 7px;
}
.focus-text {
font-size: 9px;
}
}
</style>
@@ -1,260 +0,0 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { ChevronLeft, ChevronRight, X } from '@lucide/vue'
import type { FeedEntry } from '../../composables/useDashboardData'
const props = defineProps<{
entries: FeedEntry[]
modelValue: boolean
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
}>()
const selectedDayOffset = ref(0) // 0 = today, -1 = yesterday, etc.
function close() {
emit('update:modelValue', false)
}
function dayLabel(offset: number): string {
if (offset === 0) return 'Heute'
if (offset === -1) return 'Gestern'
if (offset === -2) return 'Vorgestern'
const d = new Date()
d.setDate(d.getDate() + offset)
return d.toLocaleDateString('de-DE', { weekday: 'long', day: 'numeric', month: 'long' })
}
function navigateDay(dir: -1 | 1) {
const next = selectedDayOffset.value + dir
if (next >= -6 && next <= 0) {
selectedDayOffset.value = next
}
}
const filteredEntries = computed(() => {
const targetDate = new Date()
targetDate.setDate(targetDate.getDate() + selectedDayOffset.value)
const targetStr = targetDate.toISOString().slice(0, 10)
return props.entries.filter(e => e.timestamp.slice(0, 10) === targetStr)
})
</script>
<template>
<Teleport to="body">
<div v-if="modelValue" class="feed-modal-overlay" @click.self="close">
<div class="feed-modal-card">
<div class="feed-modal-header">
<h2 class="feed-modal-title">Operations Log</h2>
<button class="feed-modal-close-btn" @click="close" aria-label="Close">
<X :size="16" />
</button>
</div>
<div class="feed-modal-nav">
<button
class="feed-nav-btn"
:disabled="selectedDayOffset <= -6"
@click="navigateDay(-1)"
aria-label="Previous day"
>
<ChevronLeft :size="14" />
</button>
<span class="feed-nav-label">{{ dayLabel(selectedDayOffset) }}</span>
<button
class="feed-nav-btn"
:disabled="selectedDayOffset >= 0"
@click="navigateDay(1)"
aria-label="Next day"
>
<ChevronRight :size="14" />
</button>
</div>
<div class="feed-modal-entries">
<div v-if="filteredEntries.length === 0" class="feed-modal-empty">
Keine Einträge für diesen Tag.
</div>
<div
v-for="(entry, idx) in filteredEntries"
:key="entry.timestamp + '-' + idx"
class="feed-modal-entry"
>
<span class="feed-time">{{ entry.time }}</span>
<span class="feed-bullet">&middot;</span>
<span class="feed-agent" :class="'agent-' + entry.agent.toLowerCase()">
{{ entry.agent }}
</span>
<span class="feed-action">{{ entry.action }}</span>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
.feed-modal-overlay {
position: fixed;
inset: 0;
z-index: 1000;
display: grid;
place-items: center;
background: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(4px);
padding: 20px;
animation: feed-overlay-in 0.2s ease;
}
@keyframes feed-overlay-in {
from { opacity: 0; }
to { opacity: 1; }
}
.feed-modal-card {
background: #161b22;
border: 1px solid rgba(139, 124, 246, 0.15);
border-radius: 16px;
padding: 24px;
width: 100%;
max-width: 520px;
max-height: 80vh;
display: flex;
flex-direction: column;
gap: 16px;
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.5);
animation: feed-card-in 0.25s ease;
}
@keyframes feed-card-in {
from { opacity: 0; transform: translateY(12px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.feed-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.feed-modal-title {
margin: 0;
font-size: 15px;
font-weight: 600;
color: #e8eaf0;
}
.feed-modal-close-btn {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border: none;
background: rgba(255, 255, 255, 0.05);
border-radius: 6px;
color: #7e8799;
cursor: pointer;
transition: all 0.15s;
}
.feed-modal-close-btn:hover {
background: rgba(255, 255, 255, 0.1);
color: #e8eaf0;
}
.feed-modal-nav {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}
.feed-nav-btn {
display: grid;
place-items: center;
width: 30px;
height: 30px;
border: 1px solid rgba(139, 124, 246, 0.15);
background: rgba(139, 124, 246, 0.08);
border-radius: 8px;
color: #a78bfa;
cursor: pointer;
transition: all 0.15s;
}
.feed-nav-btn:hover:not(:disabled) {
background: rgba(139, 124, 246, 0.16);
border-color: rgba(139, 124, 246, 0.3);
}
.feed-nav-btn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.feed-nav-label {
font-size: 12px;
font-weight: 600;
color: #d1d5db;
min-width: 100px;
text-align: center;
}
.feed-modal-entries {
display: flex;
flex-direction: column;
gap: 4px;
overflow-y: auto;
max-height: 50vh;
padding-right: 4px;
}
.feed-modal-empty {
text-align: center;
padding: 24px 0;
font-size: 11px;
color: #6b7385;
}
.feed-modal-entry {
display: flex;
align-items: center;
gap: 5px;
padding: 5px 6px;
border-radius: 6px;
font-size: 9.5px;
line-height: 1.3;
transition: background 0.15s;
}
.feed-modal-entry:hover {
background: rgba(255, 255, 255, 0.03);
}
.feed-time {
color: #6b7385;
flex-shrink: 0;
font-variant-numeric: tabular-nums;
width: 32px;
}
.feed-bullet {
color: #6b7385;
flex-shrink: 0;
}
.feed-agent {
font-weight: 600;
flex-shrink: 0;
}
.agent-iris {
color: #a78bfa;
}
.agent-developer {
color: #3b82f6;
}
.agent-devops {
color: #eab308;
}
.agent-researcher {
color: #22c55e;
}
.agent-reviewer {
color: #a855f7;
}
.feed-action {
color: #7e8799;
white-space: normal;
word-break: break-word;
}
</style>
@@ -1,323 +0,0 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Bot, Sparkles, MessageSquareText, ListTodo, Zap, FileText, Send, Lightbulb } from '@lucide/vue'
import { useTime } from '../../composables/useTime'
import { useOperationsStore } from '../../stores/operations'
interface Suggestion {
text: string
}
const { greeting } = useTime()
const store = useOperationsStore()
const chatInput = ref('')
const meters = computed(() => {
const tasks = store.snapshot.tasks
return {
openTasks: store.snapshot.metrics.queuedTasks,
blocked: store.snapshot.metrics.incidents,
critical: tasks.filter(t => t.state === 'Blocked').length,
active: tasks.filter(t => t.state === 'In progress').length,
}
})
const suggestions = ref<Suggestion[]>([
{ text: 'Du solltest zuerst das Dungeon-System abschließen.' },
{ text: 'Die Dokumentation wurde seit 3 Tagen nicht aktualisiert.' },
{ text: 'Das Projekt OpenClaw benötigt Aufmerksamkeit.' },
])
function sendChat() {
if (!chatInput.value.trim()) return
console.log('[Iris] Chat received:', chatInput.value)
chatInput.value = ''
}
</script>
<template>
<aside class="iris-panel">
<div class="iris-profile">
<div class="iris-avatar">
<Bot :size="32" />
</div>
<div class="iris-name-block">
<h2>Iris</h2>
<span class="iris-role">Chief of Staff</span>
</div>
</div>
<p class="iris-greeting">{{ greeting }} Bao.</p>
<p class="iris-status">Du hast heute <strong>4 wichtige Punkte.</strong></p>
<div class="meters">
<div class="meter-item">
<span class="meter-value">{{ meters.openTasks }}</span>
<span class="meter-label">Offene Aufgaben</span>
</div>
<div class="meter-item">
<span class="meter-value meter-blocked">{{ meters.blocked }}</span>
<span class="meter-label">Blockiert</span>
</div>
<div class="meter-item">
<span class="meter-value meter-critical">{{ meters.critical }}</span>
<span class="meter-label">Kritisch</span>
</div>
<div class="meter-item">
<span class="meter-value meter-active">{{ meters.active }}</span>
<span class="meter-label">Aktiv</span>
</div>
</div>
<div class="suggestions">
<h3><Sparkles :size="14" /> Vorschläge</h3>
<div
v-for="(s, idx) in suggestions"
:key="idx"
class="suggestion-card"
>
<Lightbulb :size="14" class="bulb" />
<span>{{ s.text }}</span>
</div>
</div>
<div class="quick-actions">
<button class="qa-btn">
<MessageSquareText :size="14" /> Chat öffnen
</button>
<button class="qa-btn">
<ListTodo :size="14" /> Tagesplanung
</button>
<button class="qa-btn">
<Zap :size="14" /> Prioritäten setzen
</button>
<button class="qa-btn">
<FileText :size="14" /> Zusammenfassung
</button>
</div>
<div class="chat-box">
<div class="chat-input-row">
<input
v-model="chatInput"
type="text"
placeholder="Frag Iris etwas..."
@keyup.enter="sendChat"
/>
<button class="chat-send" @click="sendChat">
<Send :size="14" />
</button>
</div>
</div>
</aside>
</template>
<style scoped>
.iris-panel {
display: flex;
flex-direction: column;
gap: 12px;
padding: 18px;
background: rgba(22, 27, 34, 0.8);
border: 1px solid rgba(139, 124, 246, 0.12);
border-radius: 16px;
box-shadow: 0 4px 24px rgba(0,0,0,0.3);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
transition: all 0.2s ease;
}
.iris-panel:hover {
border-color: rgba(139, 124, 246, 0.18);
}
.iris-profile {
display: flex;
align-items: center;
gap: 12px;
}
.iris-avatar {
width: 48px;
height: 48px;
border-radius: 14px;
background: rgba(167, 139, 250, 0.15);
color: #a78bfa;
display: grid;
place-items: center;
flex-shrink: 0;
}
.iris-name-block h2 {
font-size: 18px;
font-weight: 700;
margin: 0;
line-height: 1.2;
color: #e8eaf0;
}
.iris-role {
font-size: 10px;
color: #a78bfa;
font-weight: 600;
letter-spacing: 0.04em;
}
.iris-greeting {
font-size: 15px;
font-weight: 600;
margin: 0;
color: #e8eaf0;
}
.iris-status {
font-size: 11px;
color: #7e8799;
margin: 0;
}
.iris-status strong {
color: #e8eaf0;
}
/* Meters */
.meters {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.meter-item {
background: rgba(139, 124, 246, 0.06);
border: 1px solid rgba(139, 124, 246, 0.08);
border-radius: 10px;
padding: 8px;
text-align: center;
transition: all 0.2s ease;
}
.meter-item:hover {
border-color: rgba(139, 124, 246, 0.18);
background: rgba(139, 124, 246, 0.1);
}
.meter-value {
display: block;
font-size: 20px;
font-weight: 700;
color: #e8eaf0;
}
.meter-blocked { color: #eab308; }
.meter-critical { color: #ef4444; }
.meter-active { color: #3b82f6; }
.meter-label {
display: block;
font-size: 8px;
color: #6b7385;
text-transform: uppercase;
letter-spacing: 0.06em;
margin-top: 2px;
}
/* Suggestions */
.suggestions h3 {
display: flex;
align-items: center;
gap: 5px;
font-size: 10px;
font-weight: 700;
color: #a78bfa;
text-transform: uppercase;
letter-spacing: 0.08em;
margin: 0 0 6px;
}
.suggestion-card {
display: flex;
align-items: flex-start;
gap: 7px;
padding: 7px 8px;
margin-bottom: 3px;
border-radius: 8px;
cursor: default;
transition: all 0.2s ease;
}
.suggestion-card:hover {
background: rgba(139, 124, 246, 0.08);
}
.suggestion-card .bulb {
color: #eab308;
flex-shrink: 0;
margin-top: 1px;
}
.suggestion-card span {
font-size: 10.5px;
line-height: 1.4;
color: #7e8799;
}
/* Quick Actions */
.quick-actions {
display: flex;
flex-direction: column;
gap: 4px;
}
.qa-btn {
display: flex;
align-items: center;
gap: 7px;
width: 100%;
padding: 8px 10px;
border: 1px solid rgba(139, 124, 246, 0.1);
border-radius: 8px;
background: rgba(139, 124, 246, 0.04);
color: #7e8799;
font-size: 10.5px;
cursor: pointer;
transition: all 0.2s ease;
}
.qa-btn:hover {
background: rgba(139, 124, 246, 0.12);
border-color: rgba(139, 124, 246, 0.2);
color: #e8eaf0;
}
/* Chat Box */
.chat-box {
margin-top: auto;
}
.chat-input-row {
display: flex;
gap: 5px;
}
.chat-input-row input {
flex: 1;
padding: 7px 10px;
border: 1px solid rgba(139, 124, 246, 0.12);
border-radius: 8px;
background: rgba(13, 17, 23, 0.6);
color: #e8eaf0;
font-size: 10.5px;
font-family: inherit;
outline: none;
transition: border-color 0.2s;
}
.chat-input-row input:focus {
border-color: #a78bfa;
}
.chat-input-row input::placeholder {
color: #6b7385;
}
.chat-send {
display: grid;
place-items: center;
width: 32px;
height: 32px;
border: none;
border-radius: 8px;
background: #a78bfa;
color: #fff;
cursor: pointer;
flex-shrink: 0;
transition: opacity 0.2s;
}
.chat-send:hover {
opacity: 0.85;
}
@media (max-width: 900px) {
.iris-panel {
order: 1;
}
}
</style>

Some files were not shown because too many files have changed in this diff Show More