Nyk commited on
Commit
75f351a
·
2 Parent(s): ab904500c16cdf

merge: sync virtual office branch with main

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env.example +9 -0
  2. .github/workflows/docker-publish.yml +80 -0
  3. Dockerfile +9 -7
  4. README.md +111 -4
  5. docker-compose.yml +7 -2
  6. next.config.js +2 -0
  7. openapi.json +0 -0
  8. package.json +6 -3
  9. playwright.config.ts +17 -2
  10. playwright.openclaw.gateway.config.ts +26 -0
  11. playwright.openclaw.local.config.ts +26 -0
  12. scripts/e2e-openclaw/bin/clawdbot +20 -0
  13. scripts/e2e-openclaw/bin/openclaw +20 -0
  14. scripts/e2e-openclaw/mock-gateway.mjs +61 -0
  15. scripts/e2e-openclaw/start-e2e-server.mjs +99 -0
  16. src/app/[[...panel]]/page.tsx +16 -4
  17. src/app/api/agents/[id]/attribution/route.ts +356 -0
  18. src/app/api/agents/[id]/diagnostics/route.ts +343 -0
  19. src/app/api/agents/[id]/heartbeat/route.ts +29 -4
  20. src/app/api/agents/[id]/memory/route.ts +2 -2
  21. src/app/api/agents/[id]/route.ts +70 -48
  22. src/app/api/agents/[id]/soul/route.ts +11 -5
  23. src/app/api/agents/route.ts +39 -2
  24. src/app/api/cleanup/route.ts +25 -0
  25. src/app/api/cron/route.ts +3 -3
  26. src/app/api/docs/content/route.ts +39 -0
  27. src/app/api/docs/search/route.ts +29 -0
  28. src/app/api/docs/tree/route.ts +21 -0
  29. src/app/api/gateway-config/route.ts +3 -5
  30. src/app/api/gateways/connect/route.ts +76 -0
  31. src/app/api/gateways/health/route.ts +30 -0
  32. src/app/api/integrations/route.ts +8 -8
  33. src/app/api/memory/route.ts +67 -11
  34. src/app/api/mentions/route.ts +50 -0
  35. src/app/api/projects/[id]/route.ts +177 -0
  36. src/app/api/projects/[id]/tasks/route.ts +55 -0
  37. src/app/api/projects/route.ts +94 -0
  38. src/app/api/settings/route.ts +1 -0
  39. src/app/api/spawn/route.ts +43 -7
  40. src/app/api/status/route.ts +71 -49
  41. src/app/api/tasks/[id]/comments/route.ts +14 -8
  42. src/app/api/tasks/[id]/route.ts +151 -22
  43. src/app/api/tasks/outcomes/route.ts +163 -0
  44. src/app/api/tasks/queue/route.ts +147 -0
  45. src/app/api/tasks/route.ts +168 -45
  46. src/app/api/tokens/route.ts +126 -52
  47. src/app/api/workload/route.ts +319 -0
  48. src/components/ErrorBoundary.tsx +4 -1
  49. src/components/chat/chat-panel.tsx +6 -3
  50. src/components/chat/conversation-list.tsx +4 -1
.env.example CHANGED
@@ -1,3 +1,7 @@
 
 
 
 
1
  # === Authentication ===
2
  # Admin user seeded on first run (only if no users exist in DB)
3
  AUTH_USER=admin
@@ -54,6 +58,9 @@ OPENCLAW_GATEWAY_HOST=127.0.0.1
54
  OPENCLAW_GATEWAY_PORT=18789
55
  # Optional: token used by server-side gateway calls
56
  OPENCLAW_GATEWAY_TOKEN=
 
 
 
57
 
58
  # Frontend env vars (NEXT_PUBLIC_ prefix = available in browser)
59
  NEXT_PUBLIC_GATEWAY_HOST=
@@ -61,6 +68,8 @@ NEXT_PUBLIC_GATEWAY_PORT=18789
61
  NEXT_PUBLIC_GATEWAY_PROTOCOL=
62
  NEXT_PUBLIC_GATEWAY_URL=
63
  # NEXT_PUBLIC_GATEWAY_TOKEN= # Optional, set if gateway requires auth token
 
 
64
 
65
  # === Data Paths (all optional, defaults to .data/ in project root) ===
66
  # MISSION_CONTROL_DATA_DIR=.data
 
1
+ # === Server Port ===
2
+ # Port the Next.js server listens on (dev and production)
3
+ # PORT=3000
4
+
5
  # === Authentication ===
6
  # Admin user seeded on first run (only if no users exist in DB)
7
  AUTH_USER=admin
 
58
  OPENCLAW_GATEWAY_PORT=18789
59
  # Optional: token used by server-side gateway calls
60
  OPENCLAW_GATEWAY_TOKEN=
61
+ # Tools profile used when Mission Control spawns sessions via sessions_spawn.
62
+ # OpenClaw 2026.3.2+ defaults to "messaging" if omitted.
63
+ OPENCLAW_TOOLS_PROFILE=coding
64
 
65
  # Frontend env vars (NEXT_PUBLIC_ prefix = available in browser)
66
  NEXT_PUBLIC_GATEWAY_HOST=
 
68
  NEXT_PUBLIC_GATEWAY_PROTOCOL=
69
  NEXT_PUBLIC_GATEWAY_URL=
70
  # NEXT_PUBLIC_GATEWAY_TOKEN= # Optional, set if gateway requires auth token
71
+ # Gateway client id used in websocket handshake (role=operator UI client).
72
+ NEXT_PUBLIC_GATEWAY_CLIENT_ID=openclaw-control-ui
73
 
74
  # === Data Paths (all optional, defaults to .data/ in project root) ===
75
  # MISSION_CONTROL_DATA_DIR=.data
.github/workflows/docker-publish.yml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Docker Publish
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows: ['Quality Gate']
6
+ branches: [main]
7
+ types: [completed]
8
+ push:
9
+ tags:
10
+ - 'v*.*.*'
11
+ workflow_dispatch:
12
+
13
+ concurrency:
14
+ group: docker-publish-${{ github.ref }}
15
+ cancel-in-progress: false
16
+
17
+ permissions:
18
+ contents: read
19
+ packages: write
20
+ id-token: write
21
+
22
+ env:
23
+ REGISTRY: ghcr.io
24
+ IMAGE_NAME: ${{ github.repository }}
25
+
26
+ jobs:
27
+ publish:
28
+ if: >
29
+ github.event_name == 'workflow_dispatch' ||
30
+ github.event_name == 'push' ||
31
+ (
32
+ github.event_name == 'workflow_run' &&
33
+ github.event.workflow_run.conclusion == 'success'
34
+ )
35
+ runs-on: ubuntu-latest
36
+ steps:
37
+ - name: Checkout
38
+ uses: actions/checkout@v4
39
+ with:
40
+ ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}
41
+
42
+ - name: Set up QEMU
43
+ uses: docker/setup-qemu-action@v3
44
+
45
+ - name: Set up Docker Buildx
46
+ uses: docker/setup-buildx-action@v3
47
+
48
+ - name: Log in to GHCR
49
+ uses: docker/login-action@v3
50
+ with:
51
+ registry: ${{ env.REGISTRY }}
52
+ username: ${{ github.actor }}
53
+ password: ${{ secrets.GITHUB_TOKEN }}
54
+
55
+ - name: Docker metadata
56
+ id: meta
57
+ uses: docker/metadata-action@v5
58
+ with:
59
+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
60
+ tags: |
61
+ type=sha,prefix=sha-
62
+ type=ref,event=branch
63
+ type=ref,event=tag
64
+ type=semver,pattern={{version}}
65
+ type=semver,pattern={{major}}.{{minor}}
66
+ type=raw,value=latest,enable={{is_default_branch}}
67
+
68
+ - name: Build and push image
69
+ uses: docker/build-push-action@v6
70
+ with:
71
+ context: .
72
+ file: ./Dockerfile
73
+ push: true
74
+ platforms: linux/amd64,linux/arm64
75
+ tags: ${{ steps.meta.outputs.tags }}
76
+ labels: ${{ steps.meta.outputs.labels }}
77
+ cache-from: type=gha
78
+ cache-to: type=gha,mode=max
79
+ provenance: true
80
+ sbom: true
Dockerfile CHANGED
@@ -3,19 +3,21 @@ RUN corepack enable && corepack prepare pnpm@latest --activate
3
  WORKDIR /app
4
 
5
  FROM base AS deps
 
6
  COPY package.json ./
7
- COPY . .
8
  # better-sqlite3 requires native compilation tools
9
  RUN apt-get update && apt-get install -y python3 make g++ --no-install-recommends && rm -rf /var/lib/apt/lists/*
10
  RUN if [ -f pnpm-lock.yaml ]; then \
11
  pnpm install --frozen-lockfile; \
12
  else \
13
- echo "WARN: pnpm-lock.yaml not found in build context; running non-frozen install"; \
14
  pnpm install --no-frozen-lockfile; \
15
  fi
16
 
17
  FROM base AS build
18
- COPY --from=deps /app ./
 
19
  RUN pnpm build
20
 
21
  FROM node:20-slim AS runtime
@@ -24,15 +26,15 @@ ENV NODE_ENV=production
24
  RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
25
  COPY --from=build /app/.next/standalone ./
26
  COPY --from=build /app/.next/static ./.next/static
27
- # Copy public directory if it exists (may not exist in all setups)
28
- COPY --from=build /app/public* ./public/
29
  # Create data directory with correct ownership for SQLite
30
  RUN mkdir -p .data && chown nextjs:nodejs .data
31
  RUN apt-get update && apt-get install -y curl --no-install-recommends && rm -rf /var/lib/apt/lists/*
32
  USER nextjs
33
- EXPOSE 3000
34
  ENV PORT=3000
 
35
  ENV HOSTNAME=0.0.0.0
36
  HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
37
- CMD curl -f http://localhost:3000/login || exit 1
38
  CMD ["node", "server.js"]
 
3
  WORKDIR /app
4
 
5
  FROM base AS deps
6
+ # Copy only dependency manifests first for better layer caching
7
  COPY package.json ./
8
+ COPY pnpm-lock.yaml* ./
9
  # better-sqlite3 requires native compilation tools
10
  RUN apt-get update && apt-get install -y python3 make g++ --no-install-recommends && rm -rf /var/lib/apt/lists/*
11
  RUN if [ -f pnpm-lock.yaml ]; then \
12
  pnpm install --frozen-lockfile; \
13
  else \
14
+ echo "WARN: pnpm-lock.yaml not found in build context; running non-frozen install" && \
15
  pnpm install --no-frozen-lockfile; \
16
  fi
17
 
18
  FROM base AS build
19
+ COPY --from=deps /app/node_modules ./node_modules
20
+ COPY . .
21
  RUN pnpm build
22
 
23
  FROM node:20-slim AS runtime
 
26
  RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
27
  COPY --from=build /app/.next/standalone ./
28
  COPY --from=build /app/.next/static ./.next/static
29
+ # Copy schema.sql needed by migration 001_init at runtime
30
+ COPY --from=build /app/src/lib/schema.sql ./src/lib/schema.sql
31
  # Create data directory with correct ownership for SQLite
32
  RUN mkdir -p .data && chown nextjs:nodejs .data
33
  RUN apt-get update && apt-get install -y curl --no-install-recommends && rm -rf /var/lib/apt/lists/*
34
  USER nextjs
 
35
  ENV PORT=3000
36
+ EXPOSE 3000
37
  ENV HOSTNAME=0.0.0.0
38
  HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
39
+ CMD curl -f http://localhost:${PORT:-3000}/login || exit 1
40
  CMD ["node", "server.js"]
README.md CHANGED
@@ -113,6 +113,14 @@ Inter-agent communication via the comms API. Agents can send messages to each ot
113
  ### Integrations
114
  Outbound webhooks with delivery history, configurable alert rules with cooldowns, and multi-gateway connection management. Optional 1Password CLI integration for secret management.
115
 
 
 
 
 
 
 
 
 
116
  ### Update Checker
117
  Automatic GitHub release check notifies you when a new version is available, displayed as a banner in the dashboard.
118
 
@@ -202,12 +210,14 @@ All endpoints require authentication unless noted. Full reference below.
202
  | `GET` | `/api/agents` | viewer | List agents with task stats |
203
  | `POST` | `/api/agents` | operator | Register/update agent |
204
  | `GET` | `/api/agents/[id]` | viewer | Agent details |
 
205
  | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json |
206
  | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) |
207
  | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication |
208
  | `POST` | `/api/agents/message` | operator | Send message to agent |
209
  | `GET` | `/api/tasks` | viewer | List tasks (filter: `?status=`, `?assigned_to=`, `?priority=`) |
210
  | `POST` | `/api/tasks` | operator | Create task |
 
211
  | `GET` | `/api/tasks/[id]` | viewer | Task details |
212
  | `PUT` | `/api/tasks/[id]` | operator | Update task |
213
  | `DELETE` | `/api/tasks/[id]` | admin | Delete task |
@@ -217,6 +227,14 @@ All endpoints require authentication unless noted. Full reference below.
217
 
218
  </details>
219
 
 
 
 
 
 
 
 
 
220
  <details>
221
  <summary><strong>Monitoring</strong></summary>
222
 
@@ -272,11 +290,26 @@ All endpoints require authentication unless noted. Full reference below.
272
  | `GET` | `/api/webhooks/deliveries` | admin | Delivery history |
273
  | `GET/POST/PUT/DELETE` | `/api/alerts` | admin | Alert rules |
274
  | `GET/POST/PUT/DELETE` | `/api/gateways` | admin | Gateway connections |
 
275
  | `GET/PUT/DELETE/POST` | `/api/integrations` | admin | Integration management |
276
  | `POST` | `/api/github` | admin | Trigger GitHub Issues sync |
277
 
278
  </details>
279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  <details>
281
  <summary><strong>Direct CLI</strong></summary>
282
 
@@ -342,20 +375,24 @@ See [`.env.example`](.env.example) for the complete list. Key variables:
342
  | `AUTH_PASS` | No | Initial admin password |
343
  | `AUTH_PASS_B64` | No | Base64-encoded admin password (overrides `AUTH_PASS` if set) |
344
  | `API_KEY` | No | API key for headless access |
345
- | `OPENCLAW_HOME` | Yes* | Path to `.openclaw` directory |
 
 
346
  | `OPENCLAW_GATEWAY_HOST` | No | Gateway host (default: `127.0.0.1`) |
347
  | `OPENCLAW_GATEWAY_PORT` | No | Gateway WebSocket port (default: `18789`) |
348
  | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
 
349
  | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
 
350
  | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
351
  | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
352
  | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |
353
  | `MC_ALLOWED_HOSTS` | No | Host allowlist for production |
354
 
355
- *Memory browser, log viewer, and gateway config require `OPENCLAW_HOME`.
356
 
357
  > **Memory Browser note:** OpenClaw does not store agent memory markdown files under
358
- > `$OPENCLAW_HOME/memory/` — that directory does not exist by default. Agent memory lives
359
  > in each agent's workspace (e.g. `~/clawd-agents/{agent}/memory/`). Set
360
  > `OPENCLAW_MEMORY_DIR` to your agents root directory to make the Memory Browser show
361
  > daily logs, `MEMORY.md`, and other markdown files:
@@ -363,6 +400,32 @@ See [`.env.example`](.env.example) for the complete list. Key variables:
363
  > OPENCLAW_MEMORY_DIR=/home/you/clawd-agents
364
  > ```
365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  ## Deployment
367
 
368
  ```bash
@@ -371,7 +434,7 @@ pnpm install --frozen-lockfile
371
  pnpm build
372
 
373
  # Run
374
- OPENCLAW_HOME=/path/to/.openclaw pnpm start
375
  ```
376
 
377
  Network access is restricted by default in production. Set `MC_ALLOWED_HOSTS` (comma-separated) or `MC_ALLOW_ANY_HOST=1` to control access.
@@ -388,6 +451,50 @@ pnpm test:e2e # Playwright E2E
388
  pnpm quality:gate # All checks
389
  ```
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  ## Roadmap
392
 
393
  See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
 
113
  ### Integrations
114
  Outbound webhooks with delivery history, configurable alert rules with cooldowns, and multi-gateway connection management. Optional 1Password CLI integration for secret management.
115
 
116
+ ### Workspace Management
117
+ Workspaces (tenant instances) are created and managed through the **Super Admin** panel, accessible from the sidebar under **Admin > Super Admin**. From there, admins can:
118
+ - **Create** new client instances (slug, display name, Linux user, gateway port, plan tier)
119
+ - **Monitor** provisioning jobs and their step-by-step progress
120
+ - **Decommission** tenants with optional cleanup of state directories and Linux users
121
+
122
+ Each workspace gets its own isolated environment with a dedicated OpenClaw gateway, state directory, and workspace root. See the [Super Admin API](#api-overview) endpoints under `/api/super/*` for programmatic access.
123
+
124
  ### Update Checker
125
  Automatic GitHub release check notifies you when a new version is available, displayed as a banner in the dashboard.
126
 
 
210
  | `GET` | `/api/agents` | viewer | List agents with task stats |
211
  | `POST` | `/api/agents` | operator | Register/update agent |
212
  | `GET` | `/api/agents/[id]` | viewer | Agent details |
213
+ | `GET` | `/api/agents/[id]/attribution` | viewer | Self-scope attribution/audit/cost report (`?privileged=1` admin override) |
214
  | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json |
215
  | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) |
216
  | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication |
217
  | `POST` | `/api/agents/message` | operator | Send message to agent |
218
  | `GET` | `/api/tasks` | viewer | List tasks (filter: `?status=`, `?assigned_to=`, `?priority=`) |
219
  | `POST` | `/api/tasks` | operator | Create task |
220
+ | `GET` | `/api/tasks/queue` | operator | Poll next task for an agent (`?agent=`, optional `?max_capacity=`) |
221
  | `GET` | `/api/tasks/[id]` | viewer | Task details |
222
  | `PUT` | `/api/tasks/[id]` | operator | Update task |
223
  | `DELETE` | `/api/tasks/[id]` | admin | Delete task |
 
227
 
228
  </details>
229
 
230
+ ### Attribution Contract (`/api/agents/[id]/attribution`)
231
+
232
+ - Self-scope by default: requester identity must match target agent via `x-agent-name` (or matching authenticated username).
233
+ - Admin override requires explicit `?privileged=1`.
234
+ - Query params:
235
+ - `hours`: integer window `1..720` (default `24`)
236
+ - `section`: comma-separated subset of `identity,audit,mutations,cost` (default all)
237
+
238
  <details>
239
  <summary><strong>Monitoring</strong></summary>
240
 
 
290
  | `GET` | `/api/webhooks/deliveries` | admin | Delivery history |
291
  | `GET/POST/PUT/DELETE` | `/api/alerts` | admin | Alert rules |
292
  | `GET/POST/PUT/DELETE` | `/api/gateways` | admin | Gateway connections |
293
+ | `POST` | `/api/gateways/connect` | operator | Resolve websocket URL + token for selected gateway |
294
  | `GET/PUT/DELETE/POST` | `/api/integrations` | admin | Integration management |
295
  | `POST` | `/api/github` | admin | Trigger GitHub Issues sync |
296
 
297
  </details>
298
 
299
+ <details>
300
+ <summary><strong>Super Admin (Workspace/Tenant Management)</strong></summary>
301
+
302
+ | Method | Path | Role | Description |
303
+ |--------|------|------|-------------|
304
+ | `GET` | `/api/super/tenants` | admin | List all tenants with latest provisioning status |
305
+ | `POST` | `/api/super/tenants` | admin | Create tenant and queue bootstrap job |
306
+ | `POST` | `/api/super/tenants/[id]/decommission` | admin | Queue tenant decommission job |
307
+ | `GET` | `/api/super/provision-jobs` | admin | List provisioning jobs (filter: `?tenant_id=`, `?status=`) |
308
+ | `POST` | `/api/super/provision-jobs` | admin | Queue additional job for existing tenant |
309
+ | `POST` | `/api/super/provision-jobs/[id]/action` | admin | Approve, reject, or cancel a provisioning job |
310
+
311
+ </details>
312
+
313
  <details>
314
  <summary><strong>Direct CLI</strong></summary>
315
 
 
375
  | `AUTH_PASS` | No | Initial admin password |
376
  | `AUTH_PASS_B64` | No | Base64-encoded admin password (overrides `AUTH_PASS` if set) |
377
  | `API_KEY` | No | API key for headless access |
378
+ | `OPENCLAW_CONFIG_PATH` | Yes* | Absolute path to `openclaw.json` (preferred) |
379
+ | `OPENCLAW_STATE_DIR` | Yes* | OpenClaw state root (default: `~/.openclaw`) |
380
+ | `OPENCLAW_HOME` | No | Legacy alias for state dir (fallback if `OPENCLAW_STATE_DIR` unset) |
381
  | `OPENCLAW_GATEWAY_HOST` | No | Gateway host (default: `127.0.0.1`) |
382
  | `OPENCLAW_GATEWAY_PORT` | No | Gateway WebSocket port (default: `18789`) |
383
  | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
384
+ | `OPENCLAW_TOOLS_PROFILE` | No | Tools profile for `sessions_spawn` (recommended: `coding`) |
385
  | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
386
+ | `NEXT_PUBLIC_GATEWAY_CLIENT_ID` | No | Gateway UI client ID for websocket handshake (default: `openclaw-control-ui`) |
387
  | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
388
  | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
389
  | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |
390
  | `MC_ALLOWED_HOSTS` | No | Host allowlist for production |
391
 
392
+ *Memory browser, log viewer, and gateway config require OpenClaw config/state resolution (`OPENCLAW_CONFIG_PATH` and/or `OPENCLAW_STATE_DIR`).
393
 
394
  > **Memory Browser note:** OpenClaw does not store agent memory markdown files under
395
+ > `$OPENCLAW_STATE_DIR/memory/` — that directory does not exist by default. Agent memory lives
396
  > in each agent's workspace (e.g. `~/clawd-agents/{agent}/memory/`). Set
397
  > `OPENCLAW_MEMORY_DIR` to your agents root directory to make the Memory Browser show
398
  > daily logs, `MEMORY.md`, and other markdown files:
 
400
  > OPENCLAW_MEMORY_DIR=/home/you/clawd-agents
401
  > ```
402
 
403
+ ### Workspace Creation Flow
404
+
405
+ To add a new workspace/client instance in the UI:
406
+
407
+ 1. Open `Workspaces` from the left navigation.
408
+ 2. Expand `Show Create Client Instance`.
409
+ 3. Fill tenant/workspace fields (`slug`, `display_name`, optional ports/gateway owner).
410
+ 4. Click `Create + Queue`.
411
+ 5. Approve/run the generated provisioning job in the same panel.
412
+
413
+ `Workspaces` and `Super Admin` currently point to the same provisioning control plane.
414
+
415
+ ### Projects and Ticket Prefixes
416
+
417
+ Mission Control supports multi-project task organization per workspace:
418
+
419
+ - Create/manage projects via Task Board → `Projects`.
420
+ - Each project has its own ticket prefix and counter.
421
+ - New tasks receive project-scoped ticket refs like `PA-001`, `PA-002`.
422
+ - Task board supports filtering by project.
423
+
424
+ ### Memory Scope Clarification
425
+
426
+ - **Agent profile → Memory tab**: per-agent working memory stored in Mission Control DB (`working_memory`).
427
+ - **Memory Browser page**: workspace/local filesystem memory tree under `OPENCLAW_MEMORY_DIR`.
428
+
429
  ## Deployment
430
 
431
  ```bash
 
434
  pnpm build
435
 
436
  # Run
437
+ OPENCLAW_CONFIG_PATH=/path/to/.openclaw/openclaw.json OPENCLAW_STATE_DIR=/path/to/.openclaw pnpm start
438
  ```
439
 
440
  Network access is restricted by default in production. Set `MC_ALLOWED_HOSTS` (comma-separated) or `MC_ALLOW_ANY_HOST=1` to control access.
 
451
  pnpm quality:gate # All checks
452
  ```
453
 
454
+ ## Workload Signals Contract
455
+
456
+ `GET /api/workload` returns a workload snapshot and one recommendation:
457
+
458
+ - `normal`: system healthy, submit freely
459
+ - `throttle`: reduce submission rate / defer non-critical work
460
+ - `shed`: submit only critical work
461
+ - `pause`: hold submissions until capacity returns
462
+
463
+ Low-signal behavior:
464
+
465
+ - `capacity.error_rate_5m` is clamped to `[0,1]`
466
+ - `queue.estimated_wait_confidence` is `calculated` or `unknown`
467
+ - queue breakdown maps include stable keys even when counts are zero
468
+
469
+ Runtime-tunable thresholds:
470
+
471
+ - `MC_WORKLOAD_QUEUE_DEPTH_NORMAL`
472
+ - `MC_WORKLOAD_QUEUE_DEPTH_THROTTLE`
473
+ - `MC_WORKLOAD_QUEUE_DEPTH_SHED`
474
+ - `MC_WORKLOAD_BUSY_RATIO_THROTTLE`
475
+ - `MC_WORKLOAD_BUSY_RATIO_SHED`
476
+ - `MC_WORKLOAD_ERROR_RATE_THROTTLE`
477
+ - `MC_WORKLOAD_ERROR_RATE_SHED`
478
+ - `MC_WORKLOAD_RECENT_WINDOW_SECONDS`
479
+
480
+ ## Agent Diagnostics Contract
481
+
482
+ `GET /api/agents/{id}/diagnostics` is self-scoped by default.
483
+
484
+ - Self access:
485
+ - Session user where `username === agent.name`, or
486
+ - API-key request with `x-agent-name` matching `{id}` agent name
487
+ - Cross-agent access:
488
+ - Allowed only with explicit `?privileged=1` and admin auth
489
+ - Query validation:
490
+ - `hours` must be an integer between `1` and `720`
491
+ - `section` must be a comma-separated subset of `summary,tasks,errors,activity,trends,tokens`
492
+
493
+ Trend alerts in the `trends.alerts` response are derived from current-vs-previous window comparisons:
494
+
495
+ - `warning`: error spikes or severe activity drop
496
+ - `info`: throughput drops or potential stall patterns
497
+
498
  ## Roadmap
499
 
500
  See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
docker-compose.yml CHANGED
@@ -1,9 +1,14 @@
1
  services:
2
  mission-control:
3
  build: .
 
4
  ports:
5
- - "3000:3000"
6
- env_file: .env
 
 
 
 
7
  volumes:
8
  - mc-data:/app/.data
9
  restart: unless-stopped
 
1
  services:
2
  mission-control:
3
  build: .
4
+ container_name: mission-control
5
  ports:
6
+ - "${MC_PORT:-3000}:${PORT:-3000}"
7
+ environment:
8
+ - PORT=${PORT:-3000}
9
+ env_file:
10
+ - path: .env
11
+ required: false
12
  volumes:
13
  - mc-data:/app/.data
14
  restart: unless-stopped
next.config.js CHANGED
@@ -2,6 +2,8 @@
2
  const nextConfig = {
3
  output: 'standalone',
4
  turbopack: {},
 
 
5
 
6
  // Security headers
7
  async headers() {
 
2
  const nextConfig = {
3
  output: 'standalone',
4
  turbopack: {},
5
+ // Transpile ESM-only packages so they resolve correctly in all environments
6
+ transpilePackages: ['react-markdown', 'remark-gfm'],
7
 
8
  // Security headers
9
  async headers() {
openapi.json CHANGED
The diff for this file is too large to render. See raw diff
 
package.json CHANGED
@@ -3,15 +3,18 @@
3
  "version": "1.3.0",
4
  "description": "OpenClaw Mission Control — open-source agent orchestration dashboard",
5
  "scripts": {
6
- "dev": "next dev --hostname 127.0.0.1",
7
  "build": "next build",
8
- "start": "next start --hostname 0.0.0.0 --port 3005",
9
  "lint": "eslint .",
10
  "typecheck": "tsc --noEmit",
11
  "test": "vitest run",
12
  "test:watch": "vitest",
13
  "test:ui": "vitest --ui",
14
  "test:e2e": "playwright test",
 
 
 
15
  "test:all": "pnpm lint && pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e",
16
  "quality:gate": "pnpm test:all"
17
  },
@@ -77,4 +80,4 @@
77
  "better-sqlite3"
78
  ]
79
  }
80
- }
 
3
  "version": "1.3.0",
4
  "description": "OpenClaw Mission Control — open-source agent orchestration dashboard",
5
  "scripts": {
6
+ "dev": "next dev --hostname 127.0.0.1 --port ${PORT:-3000}",
7
  "build": "next build",
8
+ "start": "next start --hostname 0.0.0.0 --port ${PORT:-3000}",
9
  "lint": "eslint .",
10
  "typecheck": "tsc --noEmit",
11
  "test": "vitest run",
12
  "test:watch": "vitest",
13
  "test:ui": "vitest --ui",
14
  "test:e2e": "playwright test",
15
+ "test:e2e:openclaw:local": "E2E_GATEWAY_EXPECTED=0 playwright test -c playwright.openclaw.local.config.ts",
16
+ "test:e2e:openclaw:gateway": "E2E_GATEWAY_EXPECTED=1 playwright test -c playwright.openclaw.gateway.config.ts",
17
+ "test:e2e:openclaw": "pnpm test:e2e:openclaw:local && pnpm test:e2e:openclaw:gateway",
18
  "test:all": "pnpm lint && pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e",
19
  "quality:gate": "pnpm test:all"
20
  },
 
80
  "better-sqlite3"
81
  ]
82
  }
83
+ }
playwright.config.ts CHANGED
@@ -2,6 +2,7 @@ import { defineConfig, devices } from '@playwright/test'
2
 
3
  export default defineConfig({
4
  testDir: 'tests',
 
5
  timeout: 60_000,
6
  expect: {
7
  timeout: 10_000
@@ -17,9 +18,23 @@ export default defineConfig({
17
  { name: 'chromium', use: { ...devices['Desktop Chrome'] } }
18
  ],
19
  webServer: {
20
- command: 'pnpm start',
21
  url: 'http://127.0.0.1:3005',
22
  reuseExistingServer: true,
23
- timeout: 30_000,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
  })
 
2
 
3
  export default defineConfig({
4
  testDir: 'tests',
5
+ testIgnore: /openclaw-harness\.spec\.ts/,
6
  timeout: 60_000,
7
  expect: {
8
  timeout: 10_000
 
18
  { name: 'chromium', use: { ...devices['Desktop Chrome'] } }
19
  ],
20
  webServer: {
21
+ command: 'node .next/standalone/server.js',
22
  url: 'http://127.0.0.1:3005',
23
  reuseExistingServer: true,
24
+ timeout: 120_000,
25
+ env: {
26
+ ...process.env,
27
+ HOSTNAME: process.env.HOSTNAME || '127.0.0.1',
28
+ PORT: process.env.PORT || '3005',
29
+ MC_DISABLE_RATE_LIMIT: process.env.MC_DISABLE_RATE_LIMIT || '1',
30
+ MC_WORKLOAD_QUEUE_DEPTH_THROTTLE: process.env.MC_WORKLOAD_QUEUE_DEPTH_THROTTLE || '1000',
31
+ MC_WORKLOAD_QUEUE_DEPTH_SHED: process.env.MC_WORKLOAD_QUEUE_DEPTH_SHED || '2000',
32
+ MC_WORKLOAD_ERROR_RATE_THROTTLE: process.env.MC_WORKLOAD_ERROR_RATE_THROTTLE || '1',
33
+ MC_WORKLOAD_ERROR_RATE_SHED: process.env.MC_WORKLOAD_ERROR_RATE_SHED || '1',
34
+ API_KEY: process.env.API_KEY || 'test-api-key-e2e-12345',
35
+ AUTH_USER: process.env.AUTH_USER || 'testadmin',
36
+ AUTH_PASS: process.env.AUTH_PASS || 'testpass1234!',
37
+ OPENCLAW_MEMORY_DIR: process.env.OPENCLAW_MEMORY_DIR || '.data/e2e-memory',
38
+ },
39
  }
40
  })
playwright.openclaw.gateway.config.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig, devices } from '@playwright/test'
2
+
3
+ export default defineConfig({
4
+ testDir: 'tests',
5
+ testMatch: /openclaw-harness\.spec\.ts/,
6
+ timeout: 60_000,
7
+ expect: {
8
+ timeout: 10_000,
9
+ },
10
+ fullyParallel: false,
11
+ workers: 1,
12
+ reporter: [['list']],
13
+ use: {
14
+ baseURL: 'http://127.0.0.1:3005',
15
+ trace: 'retain-on-failure',
16
+ },
17
+ projects: [
18
+ { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
19
+ ],
20
+ webServer: {
21
+ command: 'node scripts/e2e-openclaw/start-e2e-server.mjs --mode=gateway',
22
+ url: 'http://127.0.0.1:3005',
23
+ reuseExistingServer: false,
24
+ timeout: 120_000,
25
+ },
26
+ })
playwright.openclaw.local.config.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig, devices } from '@playwright/test'
2
+
3
+ export default defineConfig({
4
+ testDir: 'tests',
5
+ testMatch: /openclaw-harness\.spec\.ts/,
6
+ timeout: 60_000,
7
+ expect: {
8
+ timeout: 10_000,
9
+ },
10
+ fullyParallel: false,
11
+ workers: 1,
12
+ reporter: [['list']],
13
+ use: {
14
+ baseURL: 'http://127.0.0.1:3005',
15
+ trace: 'retain-on-failure',
16
+ },
17
+ projects: [
18
+ { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
19
+ ],
20
+ webServer: {
21
+ command: 'node scripts/e2e-openclaw/start-e2e-server.mjs --mode=local',
22
+ url: 'http://127.0.0.1:3005',
23
+ reuseExistingServer: false,
24
+ timeout: 120_000,
25
+ },
26
+ })
scripts/e2e-openclaw/bin/clawdbot ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ if [[ "${1:-}" == "--version" ]]; then
5
+ echo "clawdbot 2026.3.2"
6
+ exit 0
7
+ fi
8
+
9
+ if [[ "${1:-}" == "-c" ]]; then
10
+ cmd="${2:-}"
11
+ if [[ "$cmd" == sessions_spawn* ]]; then
12
+ echo "Session created: mock-clawdbot-session"
13
+ exit 0
14
+ fi
15
+ echo "ok"
16
+ exit 0
17
+ fi
18
+
19
+ echo "clawdbot mock: unsupported args: $*" >&2
20
+ exit 0
scripts/e2e-openclaw/bin/openclaw ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ if [[ "${1:-}" == "--version" ]]; then
5
+ echo "openclaw 2026.3.2"
6
+ exit 0
7
+ fi
8
+
9
+ if [[ "${1:-}" == "-c" ]]; then
10
+ cmd="${2:-}"
11
+ if [[ "$cmd" == sessions_spawn* ]]; then
12
+ echo "Session created: mock-openclaw-session"
13
+ exit 0
14
+ fi
15
+ echo "ok"
16
+ exit 0
17
+ fi
18
+
19
+ echo "openclaw mock: unsupported args: $*" >&2
20
+ exit 0
scripts/e2e-openclaw/mock-gateway.mjs ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ import http from 'node:http'
3
+ import { WebSocketServer } from 'ws'
4
+
5
+ const host = process.env.OPENCLAW_GATEWAY_HOST || '127.0.0.1'
6
+ const port = Number(process.env.OPENCLAW_GATEWAY_PORT || 18789)
7
+
8
+ const server = http.createServer((req, res) => {
9
+ if (!req.url) {
10
+ res.writeHead(404)
11
+ res.end()
12
+ return
13
+ }
14
+
15
+ if (req.url === '/health') {
16
+ res.writeHead(200, { 'content-type': 'application/json' })
17
+ res.end(JSON.stringify({ ok: true, service: 'openclaw-mock-gateway' }))
18
+ return
19
+ }
20
+
21
+ res.writeHead(200, { 'content-type': 'application/json' })
22
+ res.end(JSON.stringify({ ok: true }))
23
+ })
24
+
25
+ const wss = new WebSocketServer({ noServer: true })
26
+
27
+ wss.on('connection', (ws) => {
28
+ ws.send(JSON.stringify({ type: 'status', connected: true, source: 'mock-gateway' }))
29
+ ws.on('message', (raw) => {
30
+ const text = raw.toString()
31
+ if (text.includes('ping')) {
32
+ ws.send(JSON.stringify({ type: 'pong', ts: Date.now() }))
33
+ return
34
+ }
35
+ ws.send(JSON.stringify({ type: 'event', message: 'ack', raw: text }))
36
+ })
37
+ })
38
+
39
+ server.on('upgrade', (req, socket, head) => {
40
+ wss.handleUpgrade(req, socket, head, (ws) => {
41
+ wss.emit('connection', ws, req)
42
+ })
43
+ })
44
+
45
+ server.listen(port, host, () => {
46
+ process.stdout.write(`[openclaw-mock-gateway] listening on ${host}:${port}\n`)
47
+ })
48
+
49
+ function shutdown() {
50
+ wss.clients.forEach((client) => {
51
+ try {
52
+ client.close()
53
+ } catch {
54
+ // noop
55
+ }
56
+ })
57
+ server.close(() => process.exit(0))
58
+ }
59
+
60
+ process.on('SIGINT', shutdown)
61
+ process.on('SIGTERM', shutdown)
scripts/e2e-openclaw/start-e2e-server.mjs ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import process from 'node:process'
6
+
7
+ const modeArg = process.argv.find((arg) => arg.startsWith('--mode='))
8
+ const mode = modeArg ? modeArg.split('=')[1] : 'local'
9
+ if (mode !== 'local' && mode !== 'gateway') {
10
+ process.stderr.write(`Invalid mode: ${mode}\n`)
11
+ process.exit(1)
12
+ }
13
+
14
+ const repoRoot = process.cwd()
15
+ const fixtureSource = path.join(repoRoot, 'tests', 'fixtures', 'openclaw')
16
+ const runtimeRoot = path.join(repoRoot, '.tmp', 'e2e-openclaw', mode)
17
+ const dataDir = path.join(runtimeRoot, 'data')
18
+ const mockBinDir = path.join(repoRoot, 'scripts', 'e2e-openclaw', 'bin')
19
+
20
+ fs.rmSync(runtimeRoot, { recursive: true, force: true })
21
+ fs.mkdirSync(runtimeRoot, { recursive: true })
22
+ fs.mkdirSync(dataDir, { recursive: true })
23
+ fs.cpSync(fixtureSource, runtimeRoot, { recursive: true })
24
+
25
+ const gatewayHost = '127.0.0.1'
26
+ const gatewayPort = '18789'
27
+
28
+ const baseEnv = {
29
+ ...process.env,
30
+ API_KEY: process.env.API_KEY || 'test-api-key-e2e-12345',
31
+ AUTH_USER: process.env.AUTH_USER || 'admin',
32
+ AUTH_PASS: process.env.AUTH_PASS || 'admin',
33
+ MC_DISABLE_RATE_LIMIT: '1',
34
+ MISSION_CONTROL_DATA_DIR: dataDir,
35
+ MISSION_CONTROL_DB_PATH: path.join(dataDir, 'mission-control.db'),
36
+ OPENCLAW_STATE_DIR: runtimeRoot,
37
+ OPENCLAW_CONFIG_PATH: path.join(runtimeRoot, 'openclaw.json'),
38
+ OPENCLAW_GATEWAY_HOST: gatewayHost,
39
+ OPENCLAW_GATEWAY_PORT: gatewayPort,
40
+ OPENCLAW_BIN: path.join(mockBinDir, 'openclaw'),
41
+ CLAWDBOT_BIN: path.join(mockBinDir, 'clawdbot'),
42
+ PATH: `${mockBinDir}:${process.env.PATH || ''}`,
43
+ E2E_GATEWAY_EXPECTED: mode === 'gateway' ? '1' : '0',
44
+ }
45
+
46
+ const children = []
47
+
48
+ if (mode === 'gateway') {
49
+ const gw = spawn('node', ['scripts/e2e-openclaw/mock-gateway.mjs'], {
50
+ cwd: repoRoot,
51
+ env: baseEnv,
52
+ stdio: 'inherit',
53
+ })
54
+ children.push(gw)
55
+ }
56
+
57
+ const standaloneServerPath = path.join(repoRoot, '.next', 'standalone', 'server.js')
58
+ const app = fs.existsSync(standaloneServerPath)
59
+ ? spawn('node', [standaloneServerPath], {
60
+ cwd: repoRoot,
61
+ env: {
62
+ ...baseEnv,
63
+ HOSTNAME: '127.0.0.1',
64
+ PORT: '3005',
65
+ },
66
+ stdio: 'inherit',
67
+ })
68
+ : spawn('pnpm', ['start'], {
69
+ cwd: repoRoot,
70
+ env: baseEnv,
71
+ stdio: 'inherit',
72
+ })
73
+ children.push(app)
74
+
75
+ function shutdown(signal = 'SIGTERM') {
76
+ for (const child of children) {
77
+ if (!child.killed) {
78
+ try {
79
+ child.kill(signal)
80
+ } catch {
81
+ // noop
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ process.on('SIGINT', () => {
88
+ shutdown('SIGINT')
89
+ process.exit(130)
90
+ })
91
+ process.on('SIGTERM', () => {
92
+ shutdown('SIGTERM')
93
+ process.exit(143)
94
+ })
95
+
96
+ app.on('exit', (code) => {
97
+ shutdown('SIGTERM')
98
+ process.exit(code ?? 0)
99
+ })
src/app/[[...panel]]/page.tsx CHANGED
@@ -1,7 +1,7 @@
1
  'use client'
2
 
3
  import { useEffect, useState } from 'react'
4
- import { usePathname } from 'next/navigation'
5
  import { NavRail } from '@/components/layout/nav-rail'
6
  import { HeaderBar } from '@/components/layout/header-bar'
7
  import { LiveFeed } from '@/components/layout/live-feed'
@@ -42,6 +42,7 @@ import { useServerEvents } from '@/lib/use-server-events'
42
  import { useMissionControl } from '@/store'
43
 
44
  export default function Home() {
 
45
  const { connect } = useWebSocket()
46
  const { activeTab, setActiveTab, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable, liveFeedOpen, toggleLiveFeed } = useMissionControl()
47
 
@@ -62,7 +63,13 @@ export default function Home() {
62
 
63
  // Fetch current user
64
  fetch('/api/auth/me')
65
- .then(res => res.ok ? res.json() : null)
 
 
 
 
 
 
66
  .then(data => { if (data?.user) setCurrentUser(data.user) })
67
  .catch(() => {})
68
 
@@ -120,7 +127,7 @@ export default function Home() {
120
  const wsUrl = explicitWsUrl || `${gatewayProto}://${gatewayHost}:${gatewayPort}`
121
  connect(wsUrl, wsToken)
122
  })
123
- }, [connect, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable])
124
 
125
  if (!isClient) {
126
  return (
@@ -140,6 +147,9 @@ export default function Home() {
140
 
141
  return (
142
  <div className="flex h-screen bg-background overflow-hidden">
 
 
 
143
  {/* Left: Icon rail navigation (hidden on mobile, shown as bottom bar instead) */}
144
  <NavRail />
145
 
@@ -149,7 +159,7 @@ export default function Home() {
149
  <LocalModeBanner />
150
  <UpdateBanner />
151
  <PromoBanner />
152
- <main className="flex-1 overflow-auto pb-16 md:pb-0" role="main">
153
  <div aria-live="polite">
154
  <ErrorBoundary key={activeTab}>
155
  <ContentRouter tab={activeTab} />
@@ -258,6 +268,8 @@ function ContentRouter({ tab }: { tab: string }) {
258
  return <OfficePanel />
259
  case 'super-admin':
260
  return <SuperAdminPanel />
 
 
261
  default:
262
  return <Dashboard />
263
  }
 
1
  'use client'
2
 
3
  import { useEffect, useState } from 'react'
4
+ import { usePathname, useRouter } from 'next/navigation'
5
  import { NavRail } from '@/components/layout/nav-rail'
6
  import { HeaderBar } from '@/components/layout/header-bar'
7
  import { LiveFeed } from '@/components/layout/live-feed'
 
42
  import { useMissionControl } from '@/store'
43
 
44
  export default function Home() {
45
+ const router = useRouter()
46
  const { connect } = useWebSocket()
47
  const { activeTab, setActiveTab, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable, liveFeedOpen, toggleLiveFeed } = useMissionControl()
48
 
 
63
 
64
  // Fetch current user
65
  fetch('/api/auth/me')
66
+ .then(async (res) => {
67
+ if (res.ok) return res.json()
68
+ if (res.status === 401) {
69
+ router.replace(`/login?next=${encodeURIComponent(pathname)}`)
70
+ }
71
+ return null
72
+ })
73
  .then(data => { if (data?.user) setCurrentUser(data.user) })
74
  .catch(() => {})
75
 
 
127
  const wsUrl = explicitWsUrl || `${gatewayProto}://${gatewayHost}:${gatewayPort}`
128
  connect(wsUrl, wsToken)
129
  })
130
+ }, [connect, pathname, router, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, setUpdateAvailable])
131
 
132
  if (!isClient) {
133
  return (
 
147
 
148
  return (
149
  <div className="flex h-screen bg-background overflow-hidden">
150
+ <a href="#main-content" className="sr-only focus:not-sr-only focus:absolute focus:z-50 focus:top-2 focus:left-2 focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-md focus:text-sm focus:font-medium">
151
+ Skip to main content
152
+ </a>
153
  {/* Left: Icon rail navigation (hidden on mobile, shown as bottom bar instead) */}
154
  <NavRail />
155
 
 
159
  <LocalModeBanner />
160
  <UpdateBanner />
161
  <PromoBanner />
162
+ <main id="main-content" className="flex-1 overflow-auto pb-16 md:pb-0" role="main">
163
  <div aria-live="polite">
164
  <ErrorBoundary key={activeTab}>
165
  <ContentRouter tab={activeTab} />
 
268
  return <OfficePanel />
269
  case 'super-admin':
270
  return <SuperAdminPanel />
271
+ case 'workspaces':
272
+ return <SuperAdminPanel />
273
  default:
274
  return <Dashboard />
275
  }
src/app/api/agents/[id]/attribution/route.ts ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { getDatabase } from '@/lib/db';
3
+ import { requireRole } from '@/lib/auth';
4
+ import { logger } from '@/lib/logger';
5
+
6
+ const ALLOWED_SECTIONS = new Set(['identity', 'audit', 'mutations', 'cost']);
7
+
8
+ /**
9
+ * GET /api/agents/[id]/attribution - Agent-Level Identity & Attribution
10
+ *
11
+ * Returns a comprehensive audit trail and cost attribution report for
12
+ * a specific agent. Enables per-agent observability, debugging, and
13
+ * cost analysis in multi-agent environments.
14
+ *
15
+ * Query params:
16
+ * hours - Time window (default: 24, max: 720)
17
+ * section - Comma-separated: audit,cost,mutations,identity (default: all)
18
+ *
19
+ * Response:
20
+ * identity - Agent profile, status, and session info
21
+ * audit - Full audit trail of agent actions
22
+ * mutations - Task/memory/soul changes attributed to this agent
23
+ * cost - Token usage and cost breakdown per model
24
+ */
25
+ export async function GET(
26
+ request: NextRequest,
27
+ { params }: { params: Promise<{ id: string }> }
28
+ ) {
29
+ const auth = requireRole(request, 'viewer');
30
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
31
+
32
+ try {
33
+ const db = getDatabase();
34
+ const resolvedParams = await params;
35
+ const agentId = resolvedParams.id;
36
+ const workspaceId = auth.user.workspace_id ?? 1;
37
+
38
+ // Resolve agent
39
+ let agent: any;
40
+ if (/^\d+$/.test(agentId)) {
41
+ agent = db.prepare('SELECT * FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId);
42
+ } else {
43
+ agent = db.prepare('SELECT * FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId);
44
+ }
45
+
46
+ if (!agent) {
47
+ return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
48
+ }
49
+
50
+ const { searchParams } = new URL(request.url);
51
+ const privileged = searchParams.get('privileged') === '1';
52
+ const isSelfByHeader = auth.user.agent_name === agent.name;
53
+ const isSelfByUsername = auth.user.username === agent.name;
54
+ const isSelf = isSelfByHeader || isSelfByUsername;
55
+ const isPrivileged = auth.user.role === 'admin' && privileged;
56
+ if (!isSelf && !isPrivileged) {
57
+ return NextResponse.json(
58
+ { error: 'Forbidden: attribution is self-scope by default. Admin can use ?privileged=1 override.' },
59
+ { status: 403 }
60
+ );
61
+ }
62
+
63
+ const hoursRaw = searchParams.get('hours');
64
+ const hours = parseHours(hoursRaw);
65
+ if (!hours) {
66
+ return NextResponse.json({ error: 'Invalid hours. Expected integer 1..720.' }, { status: 400 });
67
+ }
68
+
69
+ const sections = parseSections(searchParams.get('section'));
70
+ if ('error' in sections) {
71
+ return NextResponse.json({ error: sections.error }, { status: 400 });
72
+ }
73
+
74
+ const now = Math.floor(Date.now() / 1000);
75
+ const since = now - hours * 3600;
76
+
77
+ const result: Record<string, any> = {
78
+ agent_name: agent.name,
79
+ timeframe: { hours, since, until: now },
80
+ access_scope: isSelf ? 'self' : 'privileged',
81
+ };
82
+
83
+ if (sections.sections.has('identity')) {
84
+ result.identity = buildIdentity(db, agent, workspaceId);
85
+ }
86
+
87
+ if (sections.sections.has('audit')) {
88
+ result.audit = buildAuditTrail(db, agent.name, workspaceId, since);
89
+ }
90
+
91
+ if (sections.sections.has('mutations')) {
92
+ result.mutations = buildMutations(db, agent.name, workspaceId, since);
93
+ }
94
+
95
+ if (sections.sections.has('cost')) {
96
+ result.cost = buildCostAttribution(db, agent.name, workspaceId, since);
97
+ }
98
+
99
+ return NextResponse.json(result);
100
+ } catch (error) {
101
+ logger.error({ err: error }, 'GET /api/agents/[id]/attribution error');
102
+ return NextResponse.json({ error: 'Failed to fetch attribution data' }, { status: 500 });
103
+ }
104
+ }
105
+
106
+ /** Agent identity and profile info */
107
+ function buildIdentity(db: any, agent: any, workspaceId: number) {
108
+ const config = safeParseJson(agent.config, {});
109
+
110
+ // Count total tasks ever assigned
111
+ const taskStats = db.prepare(`
112
+ SELECT
113
+ COUNT(*) as total,
114
+ SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed,
115
+ SUM(CASE WHEN status IN ('assigned', 'in_progress') THEN 1 ELSE 0 END) as active
116
+ FROM tasks WHERE assigned_to = ? AND workspace_id = ?
117
+ `).get(agent.name, workspaceId) as any;
118
+
119
+ // Count comments authored
120
+ const commentCount = (db.prepare(
121
+ `SELECT COUNT(*) as c FROM comments WHERE author = ? AND workspace_id = ?`
122
+ ).get(agent.name, workspaceId) as any).c;
123
+
124
+ return {
125
+ id: agent.id,
126
+ name: agent.name,
127
+ role: agent.role,
128
+ status: agent.status,
129
+ last_seen: agent.last_seen,
130
+ last_activity: agent.last_activity,
131
+ created_at: agent.created_at,
132
+ session_key: agent.session_key ? '***' : null, // Masked for security
133
+ has_soul: !!agent.soul_content,
134
+ config_keys: Object.keys(config),
135
+ lifetime_stats: {
136
+ tasks_total: taskStats?.total || 0,
137
+ tasks_completed: taskStats?.completed || 0,
138
+ tasks_active: taskStats?.active || 0,
139
+ comments_authored: commentCount,
140
+ },
141
+ };
142
+ }
143
+
144
+ /** Audit trail — all activities attributed to this agent */
145
+ function buildAuditTrail(db: any, agentName: string, workspaceId: number, since: number) {
146
+ // Activities where this agent is the actor
147
+ const activities = db.prepare(`
148
+ SELECT id, type, entity_type, entity_id, description, data, created_at
149
+ FROM activities
150
+ WHERE actor = ? AND workspace_id = ? AND created_at >= ?
151
+ ORDER BY created_at DESC
152
+ LIMIT 200
153
+ `).all(agentName, workspaceId, since) as any[];
154
+
155
+ // Audit log entries (system-wide, may reference agent)
156
+ let auditEntries: any[] = [];
157
+ try {
158
+ auditEntries = db.prepare(`
159
+ SELECT id, action, actor, detail, created_at
160
+ FROM audit_log
161
+ WHERE (actor = ? OR detail LIKE ?) AND created_at >= ?
162
+ ORDER BY created_at DESC
163
+ LIMIT 100
164
+ `).all(agentName, `%${agentName}%`, since) as any[];
165
+ } catch {
166
+ // audit_log table may not exist
167
+ }
168
+
169
+ // Group activities by type for summary
170
+ const byType: Record<string, number> = {};
171
+ for (const a of activities) {
172
+ byType[a.type] = (byType[a.type] || 0) + 1;
173
+ }
174
+
175
+ return {
176
+ total_activities: activities.length,
177
+ by_type: byType,
178
+ activities: activities.map(a => ({
179
+ ...a,
180
+ data: safeParseJson(a.data, null),
181
+ })),
182
+ audit_log_entries: auditEntries.map(e => ({
183
+ ...e,
184
+ detail: safeParseJson(e.detail, null),
185
+ })),
186
+ };
187
+ }
188
+
189
+ /** Mutations — task changes, comments, status transitions */
190
+ function buildMutations(db: any, agentName: string, workspaceId: number, since: number) {
191
+ // Task mutations (created, updated, status changes)
192
+ const taskMutations = db.prepare(`
193
+ SELECT id, type, entity_type, entity_id, description, data, created_at
194
+ FROM activities
195
+ WHERE actor = ? AND workspace_id = ? AND created_at >= ?
196
+ AND entity_type = 'task'
197
+ AND type IN ('task_created', 'task_updated', 'task_status_change', 'task_assigned')
198
+ ORDER BY created_at DESC
199
+ LIMIT 100
200
+ `).all(agentName, workspaceId, since) as any[];
201
+
202
+ // Comments authored
203
+ const comments = db.prepare(`
204
+ SELECT c.id, c.task_id, c.content, c.created_at, c.mentions, t.title as task_title
205
+ FROM comments c
206
+ LEFT JOIN tasks t ON c.task_id = t.id AND t.workspace_id = ?
207
+ WHERE c.author = ? AND c.workspace_id = ? AND c.created_at >= ?
208
+ ORDER BY c.created_at DESC
209
+ LIMIT 50
210
+ `).all(workspaceId, agentName, workspaceId, since) as any[];
211
+
212
+ // Agent status changes (by heartbeat or others)
213
+ const statusChanges = db.prepare(`
214
+ SELECT id, type, description, data, created_at
215
+ FROM activities
216
+ WHERE entity_type = 'agent' AND workspace_id = ?
217
+ AND created_at >= ?
218
+ AND (actor = ? OR description LIKE ?)
219
+ ORDER BY created_at DESC
220
+ LIMIT 50
221
+ `).all(workspaceId, since, agentName, `%${agentName}%`) as any[];
222
+
223
+ return {
224
+ task_mutations: taskMutations.map(m => ({
225
+ ...m,
226
+ data: safeParseJson(m.data, null),
227
+ })),
228
+ comments: comments.map(c => ({
229
+ ...c,
230
+ mentions: safeParseJson(c.mentions, []),
231
+ content_preview: c.content?.substring(0, 200) || '',
232
+ })),
233
+ status_changes: statusChanges.map(s => ({
234
+ ...s,
235
+ data: safeParseJson(s.data, null),
236
+ })),
237
+ summary: {
238
+ task_mutations_count: taskMutations.length,
239
+ comments_count: comments.length,
240
+ status_changes_count: statusChanges.length,
241
+ },
242
+ };
243
+ }
244
+
245
+ /** Cost attribution — token usage per model */
246
+ function buildCostAttribution(db: any, agentName: string, workspaceId: number, since: number) {
247
+ try {
248
+ const byModel = db.prepare(`
249
+ SELECT model,
250
+ COUNT(*) as request_count,
251
+ SUM(input_tokens) as input_tokens,
252
+ SUM(output_tokens) as output_tokens
253
+ FROM token_usage
254
+ WHERE session_id = ? AND workspace_id = ? AND created_at >= ?
255
+ GROUP BY model
256
+ ORDER BY (input_tokens + output_tokens) DESC
257
+ `).all(agentName, workspaceId, since) as Array<{
258
+ model: string; request_count: number; input_tokens: number; output_tokens: number
259
+ }>;
260
+
261
+ // Also check session IDs that contain the agent name (e.g. "agentname:cli")
262
+ const byModelAlt = db.prepare(`
263
+ SELECT model,
264
+ COUNT(*) as request_count,
265
+ SUM(input_tokens) as input_tokens,
266
+ SUM(output_tokens) as output_tokens
267
+ FROM token_usage
268
+ WHERE session_id LIKE ? AND session_id != ? AND workspace_id = ? AND created_at >= ?
269
+ GROUP BY model
270
+ ORDER BY (input_tokens + output_tokens) DESC
271
+ `).all(`${agentName}:%`, agentName, workspaceId, since) as Array<{
272
+ model: string; request_count: number; input_tokens: number; output_tokens: number
273
+ }>;
274
+
275
+ // Merge results
276
+ const merged = new Map<string, { model: string; request_count: number; input_tokens: number; output_tokens: number }>();
277
+ for (const row of [...byModel, ...byModelAlt]) {
278
+ const existing = merged.get(row.model);
279
+ if (existing) {
280
+ existing.request_count += row.request_count;
281
+ existing.input_tokens += row.input_tokens;
282
+ existing.output_tokens += row.output_tokens;
283
+ } else {
284
+ merged.set(row.model, { ...row });
285
+ }
286
+ }
287
+
288
+ const models = Array.from(merged.values());
289
+ const total = models.reduce((acc, r) => ({
290
+ input_tokens: acc.input_tokens + r.input_tokens,
291
+ output_tokens: acc.output_tokens + r.output_tokens,
292
+ requests: acc.requests + r.request_count,
293
+ }), { input_tokens: 0, output_tokens: 0, requests: 0 });
294
+
295
+ // Daily breakdown for trend
296
+ const daily = db.prepare(`
297
+ SELECT (created_at / 86400) * 86400 as day_bucket,
298
+ SUM(input_tokens) as input_tokens,
299
+ SUM(output_tokens) as output_tokens,
300
+ COUNT(*) as requests
301
+ FROM token_usage
302
+ WHERE (session_id = ? OR session_id LIKE ?) AND workspace_id = ? AND created_at >= ?
303
+ GROUP BY day_bucket
304
+ ORDER BY day_bucket ASC
305
+ `).all(agentName, `${agentName}:%`, workspaceId, since) as any[];
306
+
307
+ return {
308
+ by_model: models,
309
+ total,
310
+ daily_trend: daily.map(d => ({
311
+ date: new Date(d.day_bucket * 1000).toISOString().split('T')[0],
312
+ ...d,
313
+ })),
314
+ };
315
+ } catch {
316
+ return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 }, daily_trend: [] };
317
+ }
318
+ }
319
+
320
+ function parseHours(hoursRaw: string | null): number | null {
321
+ if (!hoursRaw || hoursRaw.trim() === '') return 24;
322
+ if (!/^\d+$/.test(hoursRaw)) return null;
323
+ const hours = Number(hoursRaw);
324
+ if (!Number.isInteger(hours) || hours < 1 || hours > 720) return null;
325
+ return hours;
326
+ }
327
+
328
+ function parseSections(
329
+ sectionRaw: string | null
330
+ ): { sections: Set<string> } | { error: string } {
331
+ const value = (sectionRaw || 'identity,audit,mutations,cost').trim();
332
+ const parsed = value
333
+ .split(',')
334
+ .map((section) => section.trim())
335
+ .filter(Boolean);
336
+
337
+ if (parsed.length === 0) {
338
+ return { error: 'Invalid section. Expected one or more of identity,audit,mutations,cost.' };
339
+ }
340
+
341
+ const invalid = parsed.filter((section) => !ALLOWED_SECTIONS.has(section));
342
+ if (invalid.length > 0) {
343
+ return { error: `Invalid section value(s): ${invalid.join(', ')}` };
344
+ }
345
+
346
+ return { sections: new Set(parsed) };
347
+ }
348
+
349
+ function safeParseJson<T>(raw: string | null | undefined, fallback: T): T {
350
+ if (!raw) return fallback;
351
+ try {
352
+ return JSON.parse(raw) as T;
353
+ } catch {
354
+ return fallback;
355
+ }
356
+ }
src/app/api/agents/[id]/diagnostics/route.ts ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { getDatabase } from '@/lib/db';
3
+ import { requireRole } from '@/lib/auth';
4
+ import { logger } from '@/lib/logger';
5
+
6
+ const ALLOWED_SECTIONS = ['summary', 'tasks', 'errors', 'activity', 'trends', 'tokens'] as const;
7
+ type DiagnosticsSection = (typeof ALLOWED_SECTIONS)[number];
8
+
9
+ function parseHoursParam(raw: string | null): { value?: number; error?: string } {
10
+ if (raw === null) return { value: 24 };
11
+ const parsed = Number(raw);
12
+ if (!Number.isInteger(parsed)) {
13
+ return { error: 'hours must be an integer between 1 and 720' };
14
+ }
15
+ if (parsed < 1 || parsed > 720) {
16
+ return { error: 'hours must be between 1 and 720' };
17
+ }
18
+ return { value: parsed };
19
+ }
20
+
21
+ function parseSectionsParam(raw: string | null): { value?: Set<DiagnosticsSection>; error?: string } {
22
+ if (!raw || raw.trim().length === 0) {
23
+ return { value: new Set(ALLOWED_SECTIONS) };
24
+ }
25
+
26
+ const requested = raw
27
+ .split(',')
28
+ .map((section) => section.trim())
29
+ .filter(Boolean);
30
+
31
+ if (requested.length === 0) {
32
+ return { error: 'section must include at least one valid value' };
33
+ }
34
+
35
+ const invalid = requested.filter((section) => !ALLOWED_SECTIONS.includes(section as DiagnosticsSection));
36
+ if (invalid.length > 0) {
37
+ return { error: `Invalid section value(s): ${invalid.join(', ')}` };
38
+ }
39
+
40
+ return { value: new Set(requested as DiagnosticsSection[]) };
41
+ }
42
+
43
+ /**
44
+ * GET /api/agents/[id]/diagnostics - Agent Self-Diagnostics API
45
+ *
46
+ * Provides an agent with its own performance metrics, error analysis,
47
+ * and trend data so it can self-optimize.
48
+ *
49
+ * Query params:
50
+ * hours - Time window in hours (default: 24, max: 720 = 30 days)
51
+ * section - Comma-separated sections to include (default: all)
52
+ * Options: summary, tasks, errors, activity, trends, tokens
53
+ *
54
+ * Response includes:
55
+ * summary - High-level KPIs (throughput, error rate, activity count)
56
+ * tasks - Task completion breakdown by status and priority
57
+ * errors - Error frequency, types, and recent error details
58
+ * activity - Activity breakdown by type with hourly timeline
59
+ * trends - Multi-period comparison for trend detection
60
+ * tokens - Token usage by model with cost estimates
61
+ */
62
+ export async function GET(
63
+ request: NextRequest,
64
+ { params }: { params: Promise<{ id: string }> }
65
+ ) {
66
+ const auth = requireRole(request, 'viewer');
67
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
68
+
69
+ try {
70
+ const db = getDatabase();
71
+ const resolvedParams = await params;
72
+ const agentId = resolvedParams.id;
73
+ const workspaceId = auth.user.workspace_id ?? 1;
74
+
75
+ // Resolve agent by ID or name
76
+ let agent: any;
77
+ if (/^\d+$/.test(agentId)) {
78
+ agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE id = ? AND workspace_id = ?').get(Number(agentId), workspaceId);
79
+ } else {
80
+ agent = db.prepare('SELECT id, name, role, status, last_seen, created_at FROM agents WHERE name = ? AND workspace_id = ?').get(agentId, workspaceId);
81
+ }
82
+
83
+ if (!agent) {
84
+ return NextResponse.json({ error: 'Agent not found' }, { status: 404 });
85
+ }
86
+
87
+ const { searchParams } = new URL(request.url);
88
+ const requesterAgentName = (request.headers.get('x-agent-name') || '').trim();
89
+ const privileged = searchParams.get('privileged') === '1';
90
+ const isSelfRequest = (requesterAgentName || auth.user.username) === agent.name;
91
+
92
+ // Self-only by default. Cross-agent access requires explicit privileged override.
93
+ if (!isSelfRequest && !(privileged && auth.user.role === 'admin')) {
94
+ return NextResponse.json(
95
+ { error: 'Diagnostics are self-scoped. Use privileged=1 with admin role for cross-agent access.' },
96
+ { status: 403 }
97
+ );
98
+ }
99
+
100
+ const parsedHours = parseHoursParam(searchParams.get('hours'));
101
+ if (parsedHours.error) {
102
+ return NextResponse.json({ error: parsedHours.error }, { status: 400 });
103
+ }
104
+
105
+ const parsedSections = parseSectionsParam(searchParams.get('section'));
106
+ if (parsedSections.error) {
107
+ return NextResponse.json({ error: parsedSections.error }, { status: 400 });
108
+ }
109
+
110
+ const hours = parsedHours.value as number;
111
+ const sections = parsedSections.value as Set<DiagnosticsSection>;
112
+
113
+ const now = Math.floor(Date.now() / 1000);
114
+ const since = now - hours * 3600;
115
+
116
+ const result: Record<string, any> = {
117
+ agent: { id: agent.id, name: agent.name, role: agent.role, status: agent.status },
118
+ timeframe: { hours, since, until: now },
119
+ };
120
+
121
+ if (sections.has('summary')) {
122
+ result.summary = buildSummary(db, agent.name, workspaceId, since);
123
+ }
124
+
125
+ if (sections.has('tasks')) {
126
+ result.tasks = buildTaskMetrics(db, agent.name, workspaceId, since);
127
+ }
128
+
129
+ if (sections.has('errors')) {
130
+ result.errors = buildErrorAnalysis(db, agent.name, workspaceId, since);
131
+ }
132
+
133
+ if (sections.has('activity')) {
134
+ result.activity = buildActivityBreakdown(db, agent.name, workspaceId, since);
135
+ }
136
+
137
+ if (sections.has('trends')) {
138
+ result.trends = buildTrends(db, agent.name, workspaceId, hours);
139
+ }
140
+
141
+ if (sections.has('tokens')) {
142
+ result.tokens = buildTokenMetrics(db, agent.name, workspaceId, since);
143
+ }
144
+
145
+ return NextResponse.json(result);
146
+ } catch (error) {
147
+ logger.error({ err: error }, 'GET /api/agents/[id]/diagnostics error');
148
+ return NextResponse.json({ error: 'Failed to fetch diagnostics' }, { status: 500 });
149
+ }
150
+ }
151
+
152
+ /** High-level KPIs */
153
+ function buildSummary(db: any, agentName: string, workspaceId: number, since: number) {
154
+ const tasksDone = (db.prepare(
155
+ `SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ?`
156
+ ).get(agentName, workspaceId, since) as any).c;
157
+
158
+ const tasksTotal = (db.prepare(
159
+ `SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ?`
160
+ ).get(agentName, workspaceId) as any).c;
161
+
162
+ const activityCount = (db.prepare(
163
+ `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ?`
164
+ ).get(agentName, workspaceId, since) as any).c;
165
+
166
+ const errorCount = (db.prepare(
167
+ `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND type LIKE '%error%'`
168
+ ).get(agentName, workspaceId, since) as any).c;
169
+
170
+ const errorRate = activityCount > 0 ? Math.round((errorCount / activityCount) * 10000) / 100 : 0;
171
+
172
+ return {
173
+ tasks_completed: tasksDone,
174
+ tasks_total: tasksTotal,
175
+ activity_count: activityCount,
176
+ error_count: errorCount,
177
+ error_rate_percent: errorRate,
178
+ };
179
+ }
180
+
181
+ /** Task completion breakdown */
182
+ function buildTaskMetrics(db: any, agentName: string, workspaceId: number, since: number) {
183
+ const byStatus = db.prepare(
184
+ `SELECT status, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY status`
185
+ ).all(agentName, workspaceId) as Array<{ status: string; count: number }>;
186
+
187
+ const byPriority = db.prepare(
188
+ `SELECT priority, COUNT(*) as count FROM tasks WHERE assigned_to = ? AND workspace_id = ? GROUP BY priority`
189
+ ).all(agentName, workspaceId) as Array<{ priority: string; count: number }>;
190
+
191
+ const recentCompleted = db.prepare(
192
+ `SELECT id, title, priority, updated_at FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? ORDER BY updated_at DESC LIMIT 10`
193
+ ).all(agentName, workspaceId, since) as any[];
194
+
195
+ // Estimate throughput: tasks completed per day in the window
196
+ const windowDays = Math.max((Math.floor(Date.now() / 1000) - since) / 86400, 1);
197
+ const completedInWindow = recentCompleted.length;
198
+ const throughputPerDay = Math.round((completedInWindow / windowDays) * 100) / 100;
199
+
200
+ return {
201
+ by_status: Object.fromEntries(byStatus.map(r => [r.status, r.count])),
202
+ by_priority: Object.fromEntries(byPriority.map(r => [r.priority, r.count])),
203
+ recent_completed: recentCompleted,
204
+ throughput_per_day: throughputPerDay,
205
+ };
206
+ }
207
+
208
+ /** Error frequency and analysis */
209
+ function buildErrorAnalysis(db: any, agentName: string, workspaceId: number, since: number) {
210
+ const errorActivities = db.prepare(
211
+ `SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') GROUP BY type ORDER BY count DESC`
212
+ ).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>;
213
+
214
+ const recentErrors = db.prepare(
215
+ `SELECT id, type, description, data, created_at FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%') ORDER BY created_at DESC LIMIT 20`
216
+ ).all(agentName, workspaceId, since) as any[];
217
+
218
+ return {
219
+ by_type: errorActivities,
220
+ total: errorActivities.reduce((sum, e) => sum + e.count, 0),
221
+ recent: recentErrors.map(e => ({
222
+ ...e,
223
+ data: e.data ? JSON.parse(e.data) : null,
224
+ })),
225
+ };
226
+ }
227
+
228
+ /** Activity breakdown with hourly timeline */
229
+ function buildActivityBreakdown(db: any, agentName: string, workspaceId: number, since: number) {
230
+ const byType = db.prepare(
231
+ `SELECT type, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY type ORDER BY count DESC`
232
+ ).all(agentName, workspaceId, since) as Array<{ type: string; count: number }>;
233
+
234
+ const timeline = db.prepare(
235
+ `SELECT (created_at / 3600) * 3600 as hour_bucket, COUNT(*) as count FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? GROUP BY hour_bucket ORDER BY hour_bucket ASC`
236
+ ).all(agentName, workspaceId, since) as Array<{ hour_bucket: number; count: number }>;
237
+
238
+ return {
239
+ by_type: byType,
240
+ timeline: timeline.map(t => ({
241
+ timestamp: t.hour_bucket,
242
+ hour: new Date(t.hour_bucket * 1000).toISOString(),
243
+ count: t.count,
244
+ })),
245
+ };
246
+ }
247
+
248
+ /** Multi-period trend comparison for anomaly/trend detection */
249
+ function buildTrends(db: any, agentName: string, workspaceId: number, hours: number) {
250
+ const now = Math.floor(Date.now() / 1000);
251
+
252
+ // Compare current period vs previous period of same length
253
+ const currentSince = now - hours * 3600;
254
+ const previousSince = currentSince - hours * 3600;
255
+
256
+ const periodMetrics = (since: number, until: number) => {
257
+ const activities = (db.prepare(
258
+ `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ?`
259
+ ).get(agentName, workspaceId, since, until) as any).c;
260
+
261
+ const errors = (db.prepare(
262
+ `SELECT COUNT(*) as c FROM activities WHERE actor = ? AND workspace_id = ? AND created_at >= ? AND created_at < ? AND (type LIKE '%error%' OR type LIKE '%fail%')`
263
+ ).get(agentName, workspaceId, since, until) as any).c;
264
+
265
+ const tasksCompleted = (db.prepare(
266
+ `SELECT COUNT(*) as c FROM tasks WHERE assigned_to = ? AND workspace_id = ? AND status = 'done' AND updated_at >= ? AND updated_at < ?`
267
+ ).get(agentName, workspaceId, since, until) as any).c;
268
+
269
+ return { activities, errors, tasks_completed: tasksCompleted };
270
+ };
271
+
272
+ const current = periodMetrics(currentSince, now);
273
+ const previous = periodMetrics(previousSince, currentSince);
274
+
275
+ const pctChange = (cur: number, prev: number) => {
276
+ if (prev === 0) return cur > 0 ? 100 : 0;
277
+ return Math.round(((cur - prev) / prev) * 10000) / 100;
278
+ };
279
+
280
+ return {
281
+ current_period: { since: currentSince, until: now, ...current },
282
+ previous_period: { since: previousSince, until: currentSince, ...previous },
283
+ change: {
284
+ activities_pct: pctChange(current.activities, previous.activities),
285
+ errors_pct: pctChange(current.errors, previous.errors),
286
+ tasks_completed_pct: pctChange(current.tasks_completed, previous.tasks_completed),
287
+ },
288
+ alerts: buildTrendAlerts(current, previous),
289
+ };
290
+ }
291
+
292
+ /** Generate automatic alerts from trend data */
293
+ function buildTrendAlerts(current: { activities: number; errors: number; tasks_completed: number }, previous: { activities: number; errors: number; tasks_completed: number }) {
294
+ const alerts: Array<{ level: string; message: string }> = [];
295
+
296
+ // Error rate spike
297
+ if (current.errors > 0 && previous.errors > 0) {
298
+ const errorIncrease = (current.errors - previous.errors) / previous.errors;
299
+ if (errorIncrease > 0.5) {
300
+ alerts.push({ level: 'warning', message: `Error count increased ${Math.round(errorIncrease * 100)}% vs previous period` });
301
+ }
302
+ } else if (current.errors > 3 && previous.errors === 0) {
303
+ alerts.push({ level: 'warning', message: `New error pattern: ${current.errors} errors (none in previous period)` });
304
+ }
305
+
306
+ // Throughput drop
307
+ if (previous.tasks_completed > 0 && current.tasks_completed === 0) {
308
+ alerts.push({ level: 'info', message: 'No tasks completed in current period (possible stall)' });
309
+ } else if (previous.tasks_completed > 2 && current.tasks_completed < previous.tasks_completed * 0.5) {
310
+ alerts.push({ level: 'info', message: `Task throughput dropped ${Math.round((1 - current.tasks_completed / previous.tasks_completed) * 100)}%` });
311
+ }
312
+
313
+ // Activity drop (possible offline)
314
+ if (previous.activities > 5 && current.activities < previous.activities * 0.25) {
315
+ alerts.push({ level: 'warning', message: `Activity dropped ${Math.round((1 - current.activities / previous.activities) * 100)}% — agent may be stalled` });
316
+ }
317
+
318
+ return alerts;
319
+ }
320
+
321
+ /** Token usage by model */
322
+ function buildTokenMetrics(db: any, agentName: string, workspaceId: number, since: number) {
323
+ try {
324
+ // session_id on token_usage may store agent name or session key
325
+ const byModel = db.prepare(
326
+ `SELECT model, SUM(input_tokens) as input_tokens, SUM(output_tokens) as output_tokens, COUNT(*) as request_count FROM token_usage WHERE session_id = ? AND workspace_id = ? AND created_at >= ? GROUP BY model ORDER BY (input_tokens + output_tokens) DESC`
327
+ ).all(agentName, workspaceId, since) as Array<{ model: string; input_tokens: number; output_tokens: number; request_count: number }>;
328
+
329
+ const total = byModel.reduce((acc, r) => ({
330
+ input_tokens: acc.input_tokens + r.input_tokens,
331
+ output_tokens: acc.output_tokens + r.output_tokens,
332
+ requests: acc.requests + r.request_count,
333
+ }), { input_tokens: 0, output_tokens: 0, requests: 0 });
334
+
335
+ return {
336
+ by_model: byModel,
337
+ total,
338
+ };
339
+ } catch {
340
+ // token_usage table may not exist
341
+ return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 } };
342
+ }
343
+ }
src/app/api/agents/[id]/heartbeat/route.ts CHANGED
@@ -180,7 +180,7 @@ export async function GET(
180
  * - connection_id: update direct_connections.last_heartbeat
181
  * - status: agent status override
182
  * - last_activity: activity description
183
- * - token_usage: { model, inputTokens, outputTokens } for inline token reporting
184
  */
185
  export async function POST(
186
  request: NextRequest,
@@ -221,10 +221,35 @@ export async function POST(
221
 
222
  if (agent) {
223
  const sessionId = `${agent.name}:cli`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  db.prepare(
225
- `INSERT INTO token_usage (model, session_id, input_tokens, output_tokens, created_at)
226
- VALUES (?, ?, ?, ?, ?)`
227
- ).run(token_usage.model, sessionId, token_usage.inputTokens, token_usage.outputTokens, now);
 
 
 
 
 
 
 
 
228
  tokenRecorded = true;
229
  }
230
  }
 
180
  * - connection_id: update direct_connections.last_heartbeat
181
  * - status: agent status override
182
  * - last_activity: activity description
183
+ * - token_usage: { model, inputTokens, outputTokens, taskId? } for inline token reporting
184
  */
185
  export async function POST(
186
  request: NextRequest,
 
221
 
222
  if (agent) {
223
  const sessionId = `${agent.name}:cli`;
224
+ const parsedTaskId =
225
+ token_usage.taskId != null && Number.isFinite(Number(token_usage.taskId))
226
+ ? Number(token_usage.taskId)
227
+ : null
228
+
229
+ let taskId: number | null = null
230
+ if (parsedTaskId && parsedTaskId > 0) {
231
+ const taskRow = db.prepare(
232
+ 'SELECT id FROM tasks WHERE id = ? AND workspace_id = ?'
233
+ ).get(parsedTaskId, workspaceId) as { id?: number } | undefined
234
+ if (taskRow?.id) {
235
+ taskId = taskRow.id
236
+ } else {
237
+ logger.warn({ taskId: parsedTaskId, workspaceId, agent: agent.name }, 'Ignoring token usage with unknown taskId')
238
+ }
239
+ }
240
+
241
  db.prepare(
242
+ `INSERT INTO token_usage (model, session_id, input_tokens, output_tokens, created_at, workspace_id, task_id)
243
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
244
+ ).run(
245
+ token_usage.model,
246
+ sessionId,
247
+ token_usage.inputTokens,
248
+ token_usage.outputTokens,
249
+ now,
250
+ workspaceId,
251
+ taskId
252
+ );
253
  tokenRecorded = true;
254
  }
255
  }
src/app/api/agents/[id]/memory/route.ts CHANGED
@@ -6,8 +6,8 @@ import { logger } from '@/lib/logger';
6
  /**
7
  * GET /api/agents/[id]/memory - Get agent's working memory
8
  *
9
- * Working memory is stored as WORKING.md content in the database
10
- * Each agent has their own working memory space for temporary notes
11
  */
12
  export async function GET(
13
  request: NextRequest,
 
6
  /**
7
  * GET /api/agents/[id]/memory - Get agent's working memory
8
  *
9
+ * Working memory is stored in the agents.working_memory DB column.
10
+ * This endpoint is per-agent scratchpad memory (not the global Memory Browser filesystem view).
11
  */
12
  export async function GET(
13
  request: NextRequest,
src/app/api/agents/[id]/route.ts CHANGED
@@ -44,12 +44,12 @@ export async function GET(
44
  }
45
 
46
  /**
47
- * PUT /api/agents/[id] - Update agent config with optional gateway write-back
48
  *
49
  * Body: {
50
  * role?: string
51
  * gateway_config?: object - OpenClaw agent config fields to update
52
- * write_to_gateway?: boolean - If true, also write to openclaw.json
53
  * }
54
  */
55
  export async function PUT(
@@ -86,56 +86,78 @@ export async function PUT(
86
  newConfig = { ...existingConfig, ...gateway_config }
87
  }
88
 
89
- // Build update
90
- const fields: string[] = ['updated_at = ?']
91
- const values: any[] = [now]
92
-
93
- if (role !== undefined) {
94
- fields.push('role = ?')
95
- values.push(role)
 
 
 
 
 
 
 
96
  }
97
 
98
- if (gateway_config) {
99
- fields.push('config = ?')
100
- values.push(JSON.stringify(newConfig))
 
 
 
 
 
 
 
101
  }
102
 
103
- values.push(agent.id, workspaceId)
104
- db.prepare(`UPDATE agents SET ${fields.join(', ')} WHERE id = ? AND workspace_id = ?`).run(...values)
 
 
105
 
106
- // Write back to openclaw.json if requested
107
- if (write_to_gateway && gateway_config) {
108
- try {
109
- const openclawId = existingConfig.openclawId || agent.name.toLowerCase().replace(/\s+/g, '-')
110
-
111
- // Build the config to write back (full OpenClaw format)
112
- const writeBack: any = { id: openclawId }
113
- if (gateway_config.model) writeBack.model = gateway_config.model
114
- if (gateway_config.identity) writeBack.identity = gateway_config.identity
115
- if (gateway_config.sandbox) writeBack.sandbox = gateway_config.sandbox
116
- if (gateway_config.tools) writeBack.tools = gateway_config.tools
117
- if (gateway_config.subagents) writeBack.subagents = gateway_config.subagents
118
- if (gateway_config.memorySearch) writeBack.memorySearch = gateway_config.memorySearch
119
-
120
- await writeAgentToConfig(writeBack)
121
-
122
- const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
123
- logAuditEvent({
124
- action: 'agent_config_writeback',
125
- actor: auth.user.username,
126
- actor_id: auth.user.id,
127
- target_type: 'agent',
128
- target_id: agent.id,
129
- detail: { agent_name: agent.name, openclaw_id: openclawId, fields: Object.keys(gateway_config) },
130
- ip_address: ipAddress,
131
- })
132
- } catch (err: any) {
133
- // Config update succeeded in DB but gateway write failed
134
- return NextResponse.json({
135
- warning: `Agent updated in MC but gateway write failed: ${err.message}`,
136
- agent: { ...agent, config: newConfig, role: role || agent.role, updated_at: now },
137
- })
138
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  }
140
 
141
  // Log activity
@@ -144,8 +166,8 @@ export async function PUT(
144
  'agent',
145
  agent.id,
146
  auth.user.username,
147
- `Config updated for agent ${agent.name}${write_to_gateway ? ' (+ gateway)' : ''}`,
148
- { fields: Object.keys(gateway_config || {}), write_to_gateway },
149
  workspaceId
150
  )
151
 
 
44
  }
45
 
46
  /**
47
+ * PUT /api/agents/[id] - Update agent config with unified MC + gateway save
48
  *
49
  * Body: {
50
  * role?: string
51
  * gateway_config?: object - OpenClaw agent config fields to update
52
+ * write_to_gateway?: boolean - Defaults to true when gateway_config exists
53
  * }
54
  */
55
  export async function PUT(
 
86
  newConfig = { ...existingConfig, ...gateway_config }
87
  }
88
 
89
+ const shouldWriteToGateway = Boolean(
90
+ gateway_config &&
91
+ (write_to_gateway === undefined || write_to_gateway === null || write_to_gateway === true)
92
+ )
93
+ const openclawId = existingConfig.openclawId || agent.name.toLowerCase().replace(/\s+/g, '-')
94
+ const getWriteBackPayload = (source: Record<string, any>) => {
95
+ const writeBack: any = { id: openclawId }
96
+ if (source.model) writeBack.model = source.model
97
+ if (source.identity) writeBack.identity = source.identity
98
+ if (source.sandbox) writeBack.sandbox = source.sandbox
99
+ if (source.tools) writeBack.tools = source.tools
100
+ if (source.subagents) writeBack.subagents = source.subagents
101
+ if (source.memorySearch) writeBack.memorySearch = source.memorySearch
102
+ return writeBack
103
  }
104
 
105
+ // Unified save: gateway first, then DB. If DB fails after gateway write, attempt rollback.
106
+ if (shouldWriteToGateway) {
107
+ try {
108
+ await writeAgentToConfig(getWriteBackPayload(gateway_config))
109
+ } catch (err: any) {
110
+ return NextResponse.json(
111
+ { error: `Save failed: unable to update gateway config: ${err.message}` },
112
+ { status: 502 }
113
+ )
114
+ }
115
  }
116
 
117
+ try {
118
+ // Build update
119
+ const fields: string[] = ['updated_at = ?']
120
+ const values: any[] = [now]
121
 
122
+ if (role !== undefined) {
123
+ fields.push('role = ?')
124
+ values.push(role)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  }
126
+
127
+ if (gateway_config) {
128
+ fields.push('config = ?')
129
+ values.push(JSON.stringify(newConfig))
130
+ }
131
+
132
+ values.push(agent.id, workspaceId)
133
+ db.prepare(`UPDATE agents SET ${fields.join(', ')} WHERE id = ? AND workspace_id = ?`).run(...values)
134
+ } catch (err: any) {
135
+ if (shouldWriteToGateway) {
136
+ try {
137
+ // Best-effort rollback to preserve consistency if DB update fails after gateway write.
138
+ await writeAgentToConfig(getWriteBackPayload(existingConfig))
139
+ } catch (rollbackErr: any) {
140
+ logger.error({ err: rollbackErr, agent: agent.name }, 'Failed to rollback gateway config after DB failure')
141
+ return NextResponse.json(
142
+ { error: `Save failed after gateway update and rollback failed: ${err.message}` },
143
+ { status: 500 }
144
+ )
145
+ }
146
+ }
147
+ return NextResponse.json({ error: `Save failed: ${err.message}` }, { status: 500 })
148
+ }
149
+
150
+ if (shouldWriteToGateway) {
151
+ const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
152
+ logAuditEvent({
153
+ action: 'agent_config_writeback',
154
+ actor: auth.user.username,
155
+ actor_id: auth.user.id,
156
+ target_type: 'agent',
157
+ target_id: agent.id,
158
+ detail: { agent_name: agent.name, openclaw_id: openclawId, fields: Object.keys(gateway_config || {}) },
159
+ ip_address: ipAddress,
160
+ })
161
  }
162
 
163
  // Log activity
 
166
  'agent',
167
  agent.id,
168
  auth.user.username,
169
+ `Config updated for agent ${agent.name}${shouldWriteToGateway ? ' (+ gateway)' : ''}`,
170
+ { fields: Object.keys(gateway_config || {}), write_to_gateway: shouldWriteToGateway },
171
  workspaceId
172
  )
173
 
src/app/api/agents/[id]/soul/route.ts CHANGED
@@ -1,12 +1,18 @@
1
  import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, db_helpers } from '@/lib/db';
3
  import { readFileSync, existsSync, readdirSync, writeFileSync, mkdirSync } from 'fs';
4
- import { join, dirname } from 'path';
5
  import { config } from '@/lib/config';
6
  import { resolveWithin } from '@/lib/paths';
7
  import { requireRole } from '@/lib/auth';
8
  import { logger } from '@/lib/logger';
9
 
 
 
 
 
 
 
10
  /**
11
  * GET /api/agents/[id]/soul - Get agent's SOUL content
12
  */
@@ -41,8 +47,8 @@ export async function GET(
41
 
42
  try {
43
  const agentConfig = agent.config ? JSON.parse(agent.config) : {}
44
- if (agentConfig.workspace && config.openclawHome) {
45
- const safeWorkspace = resolveWithin(config.openclawHome, agentConfig.workspace)
46
  const safeSoulPath = resolveWithin(safeWorkspace, 'soul.md')
47
  if (existsSync(safeSoulPath)) {
48
  soulContent = readFileSync(safeSoulPath, 'utf-8')
@@ -157,8 +163,8 @@ export async function PUT(
157
  let savedToWorkspace = false
158
  try {
159
  const agentConfig = agent.config ? JSON.parse(agent.config) : {}
160
- if (agentConfig.workspace && config.openclawHome) {
161
- const safeWorkspace = resolveWithin(config.openclawHome, agentConfig.workspace)
162
  const safeSoulPath = resolveWithin(safeWorkspace, 'soul.md')
163
  mkdirSync(dirname(safeSoulPath), { recursive: true })
164
  writeFileSync(safeSoulPath, newSoulContent || '', 'utf-8')
 
1
  import { NextRequest, NextResponse } from 'next/server';
2
  import { getDatabase, db_helpers } from '@/lib/db';
3
  import { readFileSync, existsSync, readdirSync, writeFileSync, mkdirSync } from 'fs';
4
+ import { join, dirname, isAbsolute, resolve } from 'path';
5
  import { config } from '@/lib/config';
6
  import { resolveWithin } from '@/lib/paths';
7
  import { requireRole } from '@/lib/auth';
8
  import { logger } from '@/lib/logger';
9
 
10
+ function resolveAgentWorkspacePath(workspace: string): string {
11
+ if (isAbsolute(workspace)) return resolve(workspace)
12
+ if (!config.openclawStateDir) throw new Error('OPENCLAW_STATE_DIR not configured')
13
+ return resolveWithin(config.openclawStateDir, workspace)
14
+ }
15
+
16
  /**
17
  * GET /api/agents/[id]/soul - Get agent's SOUL content
18
  */
 
47
 
48
  try {
49
  const agentConfig = agent.config ? JSON.parse(agent.config) : {}
50
+ if (agentConfig.workspace) {
51
+ const safeWorkspace = resolveAgentWorkspacePath(agentConfig.workspace)
52
  const safeSoulPath = resolveWithin(safeWorkspace, 'soul.md')
53
  if (existsSync(safeSoulPath)) {
54
  soulContent = readFileSync(safeSoulPath, 'utf-8')
 
163
  let savedToWorkspace = false
164
  try {
165
  const agentConfig = agent.config ? JSON.parse(agent.config) : {}
166
+ if (agentConfig.workspace) {
167
+ const safeWorkspace = resolveAgentWorkspacePath(agentConfig.workspace)
168
  const safeSoulPath = resolveWithin(safeWorkspace, 'soul.md')
169
  mkdirSync(dirname(safeSoulPath), { recursive: true })
170
  writeFileSync(safeSoulPath, newSoulContent || '', 'utf-8')
src/app/api/agents/route.ts CHANGED
@@ -8,6 +8,10 @@ import { requireRole } from '@/lib/auth';
8
  import { mutationLimiter } from '@/lib/rate-limit';
9
  import { logger } from '@/lib/logger';
10
  import { validateBody, createAgentSchema } from '@/lib/validation';
 
 
 
 
11
 
12
  /**
13
  * GET /api/agents - List all agents with optional filtering
@@ -123,6 +127,7 @@ export async function POST(request: NextRequest) {
123
 
124
  const {
125
  name,
 
126
  role,
127
  session_key,
128
  soul_content,
@@ -130,9 +135,16 @@ export async function POST(request: NextRequest) {
130
  config = {},
131
  template,
132
  gateway_config,
133
- write_to_gateway
 
 
134
  } = body;
135
 
 
 
 
 
 
136
  // Resolve template if specified
137
  let finalRole = role;
138
  let finalConfig: Record<string, any> = { ...config };
@@ -158,6 +170,32 @@ export async function POST(request: NextRequest) {
158
  if (existingAgent) {
159
  return NextResponse.json({ error: 'Agent name already exists' }, { status: 409 });
160
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  const now = Math.floor(Date.now() / 1000);
163
 
@@ -215,7 +253,6 @@ export async function POST(request: NextRequest) {
215
  // Write to gateway config if requested
216
  if (write_to_gateway && finalConfig) {
217
  try {
218
- const openclawId = (name || 'agent').toLowerCase().replace(/\s+/g, '-');
219
  await writeAgentToConfig({
220
  id: openclawId,
221
  name,
 
8
  import { mutationLimiter } from '@/lib/rate-limit';
9
  import { logger } from '@/lib/logger';
10
  import { validateBody, createAgentSchema } from '@/lib/validation';
11
+ import { runOpenClaw } from '@/lib/command';
12
+ import { config as appConfig } from '@/lib/config';
13
+ import { resolveWithin } from '@/lib/paths';
14
+ import path from 'node:path';
15
 
16
  /**
17
  * GET /api/agents - List all agents with optional filtering
 
127
 
128
  const {
129
  name,
130
+ openclaw_id,
131
  role,
132
  session_key,
133
  soul_content,
 
135
  config = {},
136
  template,
137
  gateway_config,
138
+ write_to_gateway,
139
+ provision_openclaw_workspace,
140
+ openclaw_workspace_path
141
  } = body;
142
 
143
+ const openclawId = (openclaw_id || name || 'agent')
144
+ .toLowerCase()
145
+ .replace(/[^a-z0-9]+/g, '-')
146
+ .replace(/^-|-$/g, '');
147
+
148
  // Resolve template if specified
149
  let finalRole = role;
150
  let finalConfig: Record<string, any> = { ...config };
 
170
  if (existingAgent) {
171
  return NextResponse.json({ error: 'Agent name already exists' }, { status: 409 });
172
  }
173
+
174
+ if (provision_openclaw_workspace) {
175
+ if (!appConfig.openclawStateDir) {
176
+ return NextResponse.json(
177
+ { error: 'OPENCLAW_STATE_DIR is not configured; cannot provision OpenClaw workspace' },
178
+ { status: 500 }
179
+ );
180
+ }
181
+
182
+ const workspacePath = openclaw_workspace_path
183
+ ? path.resolve(openclaw_workspace_path)
184
+ : resolveWithin(appConfig.openclawStateDir, path.join('workspaces', openclawId));
185
+
186
+ try {
187
+ await runOpenClaw(
188
+ ['agents', 'add', openclawId, '--name', name, '--workspace', workspacePath, '--non-interactive'],
189
+ { timeoutMs: 20000 }
190
+ );
191
+ } catch (provisionError: any) {
192
+ logger.error({ err: provisionError, openclawId, workspacePath }, 'OpenClaw workspace provisioning failed');
193
+ return NextResponse.json(
194
+ { error: provisionError?.message || 'Failed to provision OpenClaw agent workspace' },
195
+ { status: 502 }
196
+ );
197
+ }
198
+ }
199
 
200
  const now = Math.floor(Date.now() / 1000);
201
 
 
253
  // Write to gateway config if requested
254
  if (write_to_gateway && finalConfig) {
255
  try {
 
256
  await writeAgentToConfig({
257
  id: openclawId,
258
  name,
src/app/api/cleanup/route.ts CHANGED
@@ -3,6 +3,7 @@ import { requireRole } from '@/lib/auth'
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
  import { heavyLimiter } from '@/lib/rate-limit'
 
6
 
7
  interface CleanupResult {
8
  table: string
@@ -59,6 +60,17 @@ export async function GET(request: NextRequest) {
59
  preview.push({ table: 'Token Usage (file)', retention_days: ret.tokenUsage, stale_count: 0, note: 'No token data file' })
60
  }
61
 
 
 
 
 
 
 
 
 
 
 
 
62
  return NextResponse.json({ retention: config.retention, preview })
63
  }
64
 
@@ -137,6 +149,19 @@ export async function POST(request: NextRequest) {
137
  }
138
  }
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  if (!dryRun && totalDeleted > 0) {
141
  const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
142
  logAuditEvent({
 
3
  import { getDatabase, logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
  import { heavyLimiter } from '@/lib/rate-limit'
6
+ import { countStaleGatewaySessions, pruneGatewaySessionsOlderThan } from '@/lib/sessions'
7
 
8
  interface CleanupResult {
9
  table: string
 
60
  preview.push({ table: 'Token Usage (file)', retention_days: ret.tokenUsage, stale_count: 0, note: 'No token data file' })
61
  }
62
 
63
+ if (ret.gatewaySessions > 0) {
64
+ preview.push({
65
+ table: 'Gateway Session Store',
66
+ retention_days: ret.gatewaySessions,
67
+ stale_count: countStaleGatewaySessions(ret.gatewaySessions),
68
+ note: 'Stored under ~/.openclaw/agents/*/sessions/sessions.json',
69
+ })
70
+ } else {
71
+ preview.push({ table: 'Gateway Session Store', retention_days: 0, stale_count: 0, note: 'Retention disabled (keep forever)' })
72
+ }
73
+
74
  return NextResponse.json({ retention: config.retention, preview })
75
  }
76
 
 
149
  }
150
  }
151
 
152
+ if (ret.gatewaySessions > 0) {
153
+ const sessionPrune = dryRun
154
+ ? { deleted: countStaleGatewaySessions(ret.gatewaySessions), filesTouched: 0 }
155
+ : pruneGatewaySessionsOlderThan(ret.gatewaySessions)
156
+ results.push({
157
+ table: 'Gateway Session Store',
158
+ deleted: sessionPrune.deleted,
159
+ cutoff_date: new Date(Date.now() - ret.gatewaySessions * 86400000).toISOString().split('T')[0],
160
+ retention_days: ret.gatewaySessions,
161
+ })
162
+ totalDeleted += sessionPrune.deleted
163
+ }
164
+
165
  if (!dryRun && totalDeleted > 0) {
166
  const ipAddress = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown'
167
  logAuditEvent({
src/app/api/cron/route.ts CHANGED
@@ -67,9 +67,9 @@ interface OpenClawCronFile {
67
  }
68
 
69
  function getCronFilePath(): string {
70
- const openclawHome = config.openclawHome
71
- if (!openclawHome) return ''
72
- return path.join(openclawHome, 'cron', 'jobs.json')
73
  }
74
 
75
  async function loadCronFile(): Promise<OpenClawCronFile | null> {
 
67
  }
68
 
69
  function getCronFilePath(): string {
70
+ const openclawStateDir = config.openclawStateDir
71
+ if (!openclawStateDir) return ''
72
+ return path.join(openclawStateDir, 'cron', 'jobs.json')
73
  }
74
 
75
  async function loadCronFile(): Promise<OpenClawCronFile | null> {
src/app/api/docs/content/route.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { readLimiter } from '@/lib/rate-limit'
4
+ import { logger } from '@/lib/logger'
5
+ import { readDocsContent } from '@/lib/docs-knowledge'
6
+
7
+ export async function GET(request: NextRequest) {
8
+ const auth = requireRole(request, 'viewer')
9
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
10
+
11
+ const rateCheck = readLimiter(request)
12
+ if (rateCheck) return rateCheck
13
+
14
+ try {
15
+ const { searchParams } = new URL(request.url)
16
+ const path = (searchParams.get('path') || '').trim()
17
+
18
+ if (!path) {
19
+ return NextResponse.json({ error: 'Path required' }, { status: 400 })
20
+ }
21
+
22
+ try {
23
+ const doc = await readDocsContent(path)
24
+ return NextResponse.json(doc)
25
+ } catch (error) {
26
+ const message = (error as Error).message || ''
27
+ if (message.includes('Path not allowed')) {
28
+ return NextResponse.json({ error: 'Path not allowed' }, { status: 403 })
29
+ }
30
+ if (message.includes('not configured')) {
31
+ return NextResponse.json({ error: 'Docs directory not configured' }, { status: 500 })
32
+ }
33
+ return NextResponse.json({ error: 'File not found' }, { status: 404 })
34
+ }
35
+ } catch (error) {
36
+ logger.error({ err: error }, 'GET /api/docs/content error')
37
+ return NextResponse.json({ error: 'Failed to load doc content' }, { status: 500 })
38
+ }
39
+ }
src/app/api/docs/search/route.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { readLimiter } from '@/lib/rate-limit'
4
+ import { logger } from '@/lib/logger'
5
+ import { searchDocs } from '@/lib/docs-knowledge'
6
+
7
+ export async function GET(request: NextRequest) {
8
+ const auth = requireRole(request, 'viewer')
9
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
10
+
11
+ const rateCheck = readLimiter(request)
12
+ if (rateCheck) return rateCheck
13
+
14
+ try {
15
+ const { searchParams } = new URL(request.url)
16
+ const query = (searchParams.get('q') || searchParams.get('query') || '').trim()
17
+ const limit = Math.min(parseInt(searchParams.get('limit') || '50', 10), 200)
18
+
19
+ if (!query) {
20
+ return NextResponse.json({ error: 'Query required' }, { status: 400 })
21
+ }
22
+
23
+ const results = await searchDocs(query, limit)
24
+ return NextResponse.json({ query, results, count: results.length })
25
+ } catch (error) {
26
+ logger.error({ err: error }, 'GET /api/docs/search error')
27
+ return NextResponse.json({ error: 'Failed to search docs' }, { status: 500 })
28
+ }
29
+ }
src/app/api/docs/tree/route.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { readLimiter } from '@/lib/rate-limit'
4
+ import { logger } from '@/lib/logger'
5
+ import { getDocsTree, listDocsRoots } from '@/lib/docs-knowledge'
6
+
7
+ export async function GET(request: NextRequest) {
8
+ const auth = requireRole(request, 'viewer')
9
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
10
+
11
+ const rateCheck = readLimiter(request)
12
+ if (rateCheck) return rateCheck
13
+
14
+ try {
15
+ const tree = await getDocsTree()
16
+ return NextResponse.json({ roots: listDocsRoots(), tree })
17
+ } catch (error) {
18
+ logger.error({ err: error }, 'GET /api/docs/tree error')
19
+ return NextResponse.json({ error: 'Failed to load docs tree' }, { status: 500 })
20
+ }
21
+ }
src/app/api/gateway-config/route.ts CHANGED
@@ -2,13 +2,11 @@ import { NextRequest, NextResponse } from 'next/server'
2
  import { requireRole } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
5
- import { join } from 'path'
6
  import { validateBody, gatewayConfigUpdateSchema } from '@/lib/validation'
7
  import { mutationLimiter } from '@/lib/rate-limit'
8
 
9
  function getConfigPath(): string | null {
10
- if (!config.openclawHome) return null
11
- return join(config.openclawHome, 'openclaw.json')
12
  }
13
 
14
  /**
@@ -20,7 +18,7 @@ export async function GET(request: NextRequest) {
20
 
21
  const configPath = getConfigPath()
22
  if (!configPath) {
23
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
24
  }
25
 
26
  try {
@@ -60,7 +58,7 @@ export async function PUT(request: NextRequest) {
60
 
61
  const configPath = getConfigPath()
62
  if (!configPath) {
63
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
64
  }
65
 
66
  const result = await validateBody(request, gatewayConfigUpdateSchema)
 
2
  import { requireRole } from '@/lib/auth'
3
  import { logAuditEvent } from '@/lib/db'
4
  import { config } from '@/lib/config'
 
5
  import { validateBody, gatewayConfigUpdateSchema } from '@/lib/validation'
6
  import { mutationLimiter } from '@/lib/rate-limit'
7
 
8
  function getConfigPath(): string | null {
9
+ return config.openclawConfigPath || null
 
10
  }
11
 
12
  /**
 
18
 
19
  const configPath = getConfigPath()
20
  if (!configPath) {
21
+ return NextResponse.json({ error: 'OPENCLAW_CONFIG_PATH not configured' }, { status: 404 })
22
  }
23
 
24
  try {
 
58
 
59
  const configPath = getConfigPath()
60
  if (!configPath) {
61
+ return NextResponse.json({ error: 'OPENCLAW_CONFIG_PATH not configured' }, { status: 404 })
62
  }
63
 
64
  const result = await validateBody(request, gatewayConfigUpdateSchema)
src/app/api/gateways/connect/route.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { getDatabase } from '@/lib/db'
4
+ import { buildGatewayWebSocketUrl } from '@/lib/gateway-url'
5
+
6
+ interface GatewayEntry {
7
+ id: number
8
+ host: string
9
+ port: number
10
+ token: string
11
+ }
12
+
13
+ function ensureTable(db: ReturnType<typeof getDatabase>) {
14
+ db.exec(`
15
+ CREATE TABLE IF NOT EXISTS gateways (
16
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
17
+ name TEXT NOT NULL UNIQUE,
18
+ host TEXT NOT NULL DEFAULT '127.0.0.1',
19
+ port INTEGER NOT NULL DEFAULT 18789,
20
+ token TEXT NOT NULL DEFAULT '',
21
+ is_primary INTEGER NOT NULL DEFAULT 0,
22
+ status TEXT NOT NULL DEFAULT 'unknown',
23
+ last_seen INTEGER,
24
+ latency INTEGER,
25
+ sessions_count INTEGER NOT NULL DEFAULT 0,
26
+ agents_count INTEGER NOT NULL DEFAULT 0,
27
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
28
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch())
29
+ )
30
+ `)
31
+ }
32
+
33
+ /**
34
+ * POST /api/gateways/connect
35
+ * Resolves websocket URL and token for a selected gateway without exposing tokens in list payloads.
36
+ */
37
+ export async function POST(request: NextRequest) {
38
+ const auth = requireRole(request, 'operator')
39
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
40
+
41
+ const db = getDatabase()
42
+ ensureTable(db)
43
+
44
+ let id: number | null = null
45
+ try {
46
+ const body = await request.json()
47
+ id = Number(body?.id)
48
+ } catch {
49
+ return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
50
+ }
51
+
52
+ if (!id || !Number.isInteger(id) || id < 1) {
53
+ return NextResponse.json({ error: 'id is required' }, { status: 400 })
54
+ }
55
+
56
+ const gateway = db.prepare('SELECT id, host, port, token FROM gateways WHERE id = ?').get(id) as GatewayEntry | undefined
57
+ if (!gateway) {
58
+ return NextResponse.json({ error: 'Gateway not found' }, { status: 404 })
59
+ }
60
+
61
+ const ws_url = buildGatewayWebSocketUrl({
62
+ host: gateway.host,
63
+ port: gateway.port,
64
+ browserProtocol: request.nextUrl.protocol,
65
+ })
66
+
67
+ const envToken = (process.env.NEXT_PUBLIC_GATEWAY_TOKEN || process.env.NEXT_PUBLIC_WS_TOKEN || '').trim()
68
+ const token = (gateway.token || '').trim() || envToken
69
+
70
+ return NextResponse.json({
71
+ id: gateway.id,
72
+ ws_url,
73
+ token,
74
+ token_set: token.length > 0,
75
+ })
76
+ }
src/app/api/gateways/health/route.ts CHANGED
@@ -19,9 +19,33 @@ interface HealthResult {
19
  latency: number | null
20
  agents: string[]
21
  sessions_count: number
 
 
22
  error?: string
23
  }
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  function isBlockedUrl(urlStr: string): boolean {
26
  try {
27
  const url = new URL(urlStr)
@@ -77,6 +101,10 @@ export async function POST(request: NextRequest) {
77
 
78
  const latency = Date.now() - start
79
  const status = res.ok ? "online" : "error"
 
 
 
 
80
 
81
  updateOnlineStmt.run(status, latency, gw.id)
82
 
@@ -87,6 +115,8 @@ export async function POST(request: NextRequest) {
87
  latency,
88
  agents: [],
89
  sessions_count: 0,
 
 
90
  })
91
  } catch (err: any) {
92
  updateOfflineStmt.run("offline", gw.id)
 
19
  latency: number | null
20
  agents: string[]
21
  sessions_count: number
22
+ gateway_version?: string | null
23
+ compatibility_warning?: string
24
  error?: string
25
  }
26
 
27
+ function parseGatewayVersion(res: Response): string | null {
28
+ const direct = res.headers.get('x-openclaw-version') || res.headers.get('x-clawdbot-version')
29
+ if (direct) return direct.trim()
30
+ const server = res.headers.get('server') || ''
31
+ const m = server.match(/(\d{4}\.\d+\.\d+)/)
32
+ return m?.[1] || null
33
+ }
34
+
35
+ function hasOpenClaw32ToolsProfileRisk(version: string | null): boolean {
36
+ if (!version) return false
37
+ const m = version.match(/^(\d{4})\.(\d+)\.(\d+)/)
38
+ if (!m) return false
39
+ const year = Number(m[1])
40
+ const major = Number(m[2])
41
+ const minor = Number(m[3])
42
+ if (year > 2026) return true
43
+ if (year < 2026) return false
44
+ if (major > 3) return true
45
+ if (major < 3) return false
46
+ return minor >= 2
47
+ }
48
+
49
  function isBlockedUrl(urlStr: string): boolean {
50
  try {
51
  const url = new URL(urlStr)
 
101
 
102
  const latency = Date.now() - start
103
  const status = res.ok ? "online" : "error"
104
+ const gatewayVersion = parseGatewayVersion(res)
105
+ const compatibilityWarning = hasOpenClaw32ToolsProfileRisk(gatewayVersion)
106
+ ? 'OpenClaw 2026.3.2+ defaults tools.profile=messaging; Mission Control should enforce coding profile when spawning.'
107
+ : undefined
108
 
109
  updateOnlineStmt.run(status, latency, gw.id)
110
 
 
115
  latency,
116
  agents: [],
117
  sessions_count: 0,
118
+ gateway_version: gatewayVersion,
119
+ compatibility_warning: compatibilityWarning,
120
  })
121
  } catch (err: any) {
122
  updateOfflineStmt.run("offline", gw.id)
src/app/api/integrations/route.ts CHANGED
@@ -108,8 +108,8 @@ function serializeEnv(lines: EnvLine[]): string {
108
  }
109
 
110
  function getEnvPath(): string | null {
111
- if (!config.openclawHome) return null
112
- return join(config.openclawHome, '.env')
113
  }
114
 
115
  async function readEnvFile(): Promise<{ lines: EnvLine[]; raw: string } | null> {
@@ -184,7 +184,7 @@ export async function GET(request: NextRequest) {
184
 
185
  const envData = await readEnvFile()
186
  if (!envData) {
187
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
188
  }
189
 
190
  const envMap = new Map<string, string>()
@@ -261,7 +261,7 @@ export async function PUT(request: NextRequest) {
261
 
262
  const envData = await readEnvFile()
263
  if (!envData) {
264
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
265
  }
266
 
267
  const { lines } = envData
@@ -324,7 +324,7 @@ export async function DELETE(request: NextRequest) {
324
 
325
  const envData = await readEnvFile()
326
  if (!envData) {
327
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
328
  }
329
 
330
  const removed: string[] = []
@@ -408,7 +408,7 @@ async function handleTest(
408
 
409
  const envData = await readEnvFile()
410
  if (!envData) {
411
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
412
  }
413
 
414
  const envMap = new Map<string, string>()
@@ -552,7 +552,7 @@ async function handlePull(
552
  // Write to .env
553
  const envData = await readEnvFile()
554
  if (!envData) {
555
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
556
  }
557
 
558
  const { lines } = envData
@@ -621,7 +621,7 @@ async function handlePullAll(
621
 
622
  const envData = await readEnvFile()
623
  if (!envData) {
624
- return NextResponse.json({ error: 'OPENCLAW_HOME not configured' }, { status: 404 })
625
  }
626
 
627
  const { lines } = envData
 
108
  }
109
 
110
  function getEnvPath(): string | null {
111
+ if (!config.openclawStateDir) return null
112
+ return join(config.openclawStateDir, '.env')
113
  }
114
 
115
  async function readEnvFile(): Promise<{ lines: EnvLine[]; raw: string } | null> {
 
184
 
185
  const envData = await readEnvFile()
186
  if (!envData) {
187
+ return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 })
188
  }
189
 
190
  const envMap = new Map<string, string>()
 
261
 
262
  const envData = await readEnvFile()
263
  if (!envData) {
264
+ return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 })
265
  }
266
 
267
  const { lines } = envData
 
324
 
325
  const envData = await readEnvFile()
326
  if (!envData) {
327
+ return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 })
328
  }
329
 
330
  const removed: string[] = []
 
408
 
409
  const envData = await readEnvFile()
410
  if (!envData) {
411
+ return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 })
412
  }
413
 
414
  const envMap = new Map<string, string>()
 
552
  // Write to .env
553
  const envData = await readEnvFile()
554
  if (!envData) {
555
+ return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 })
556
  }
557
 
558
  const { lines } = envData
 
621
 
622
  const envData = await readEnvFile()
623
  if (!envData) {
624
+ return NextResponse.json({ error: 'OPENCLAW_STATE_DIR not configured' }, { status: 404 })
625
  }
626
 
627
  const { lines } = envData
src/app/api/memory/route.ts CHANGED
@@ -9,6 +9,7 @@ import { readLimiter, mutationLimiter } from '@/lib/rate-limit'
9
  import { logger } from '@/lib/logger'
10
 
11
  const MEMORY_PATH = config.memoryDir
 
12
 
13
  // Ensure memory directory exists on startup
14
  if (MEMORY_PATH && !existsSync(MEMORY_PATH)) {
@@ -24,6 +25,16 @@ interface MemoryFile {
24
  children?: MemoryFile[]
25
  }
26
 
 
 
 
 
 
 
 
 
 
 
27
  function isWithinBase(base: string, candidate: string): boolean {
28
  if (candidate === base) return true
29
  return candidate.startsWith(base + sep)
@@ -33,17 +44,22 @@ async function resolveSafeMemoryPath(baseDir: string, relativePath: string): Pro
33
  const baseReal = await realpath(baseDir)
34
  const fullPath = resolveWithin(baseDir, relativePath)
35
 
36
- // For non-existent paths, validate containment using the parent directory realpath.
37
- // This also blocks symlinked parent segments that escape the base.
38
- let parentReal: string
39
- try {
40
- parentReal = await realpath(dirname(fullPath))
41
- } catch (err) {
42
- const code = (err as NodeJS.ErrnoException).code
43
- if (code === 'ENOENT') {
44
- throw new Error('Parent directory not found')
 
 
 
 
 
 
45
  }
46
- throw err
47
  }
48
  if (!isWithinBase(baseReal, parentReal)) {
49
  throw new Error('Path escapes base directory (symlink)')
@@ -137,12 +153,37 @@ export async function GET(request: NextRequest) {
137
  if (!MEMORY_PATH) {
138
  return NextResponse.json({ tree: [] })
139
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  const tree = await buildFileTree(MEMORY_PATH)
141
  return NextResponse.json({ tree })
142
  }
143
 
144
  if (action === 'content' && path) {
145
  // Return file content
 
 
 
146
  if (!MEMORY_PATH) {
147
  return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 })
148
  }
@@ -227,7 +268,16 @@ export async function GET(request: NextRequest) {
227
  }
228
  }
229
 
230
- await searchDirectory(MEMORY_PATH)
 
 
 
 
 
 
 
 
 
231
 
232
  return NextResponse.json({
233
  query,
@@ -256,6 +306,9 @@ export async function POST(request: NextRequest) {
256
  if (!path) {
257
  return NextResponse.json({ error: 'Path is required' }, { status: 400 })
258
  }
 
 
 
259
 
260
  if (!MEMORY_PATH) {
261
  return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 })
@@ -316,6 +369,9 @@ export async function DELETE(request: NextRequest) {
316
  if (!path) {
317
  return NextResponse.json({ error: 'Path is required' }, { status: 400 })
318
  }
 
 
 
319
 
320
  if (!MEMORY_PATH) {
321
  return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 })
 
9
  import { logger } from '@/lib/logger'
10
 
11
  const MEMORY_PATH = config.memoryDir
12
+ const MEMORY_ALLOWED_PREFIXES = (config.memoryAllowedPrefixes || []).map((p) => p.replace(/\\/g, '/'))
13
 
14
  // Ensure memory directory exists on startup
15
  if (MEMORY_PATH && !existsSync(MEMORY_PATH)) {
 
25
  children?: MemoryFile[]
26
  }
27
 
28
+ function normalizeRelativePath(value: string): string {
29
+ return String(value || '').replace(/\\/g, '/').replace(/^\/+/, '')
30
+ }
31
+
32
+ function isPathAllowed(relativePath: string): boolean {
33
+ if (!MEMORY_ALLOWED_PREFIXES.length) return true
34
+ const normalized = normalizeRelativePath(relativePath)
35
+ return MEMORY_ALLOWED_PREFIXES.some((prefix) => normalized === prefix.slice(0, -1) || normalized.startsWith(prefix))
36
+ }
37
+
38
  function isWithinBase(base: string, candidate: string): boolean {
39
  if (candidate === base) return true
40
  return candidate.startsWith(base + sep)
 
44
  const baseReal = await realpath(baseDir)
45
  const fullPath = resolveWithin(baseDir, relativePath)
46
 
47
+ // For non-existent targets, validate containment using the nearest existing ancestor.
48
+ // This allows nested creates (mkdir -p) while still blocking symlink escapes.
49
+ let current = dirname(fullPath)
50
+ let parentReal = ''
51
+ while (!parentReal) {
52
+ try {
53
+ parentReal = await realpath(current)
54
+ } catch (err) {
55
+ const code = (err as NodeJS.ErrnoException).code
56
+ if (code !== 'ENOENT') throw err
57
+ const next = dirname(current)
58
+ if (next === current) {
59
+ throw new Error('Parent directory not found')
60
+ }
61
+ current = next
62
  }
 
63
  }
64
  if (!isWithinBase(baseReal, parentReal)) {
65
  throw new Error('Path escapes base directory (symlink)')
 
153
  if (!MEMORY_PATH) {
154
  return NextResponse.json({ tree: [] })
155
  }
156
+ if (MEMORY_ALLOWED_PREFIXES.length) {
157
+ const tree: MemoryFile[] = []
158
+ for (const prefix of MEMORY_ALLOWED_PREFIXES) {
159
+ const folder = prefix.replace(/\/$/, '')
160
+ const fullPath = join(MEMORY_PATH, folder)
161
+ if (!existsSync(fullPath)) continue
162
+ try {
163
+ const stats = await stat(fullPath)
164
+ if (!stats.isDirectory()) continue
165
+ tree.push({
166
+ path: folder,
167
+ name: folder,
168
+ type: 'directory',
169
+ modified: stats.mtime.getTime(),
170
+ children: await buildFileTree(fullPath, folder),
171
+ })
172
+ } catch {
173
+ // Skip unreadable roots
174
+ }
175
+ }
176
+ return NextResponse.json({ tree })
177
+ }
178
  const tree = await buildFileTree(MEMORY_PATH)
179
  return NextResponse.json({ tree })
180
  }
181
 
182
  if (action === 'content' && path) {
183
  // Return file content
184
+ if (!isPathAllowed(path)) {
185
+ return NextResponse.json({ error: 'Path not allowed' }, { status: 403 })
186
+ }
187
  if (!MEMORY_PATH) {
188
  return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 })
189
  }
 
268
  }
269
  }
270
 
271
+ if (MEMORY_ALLOWED_PREFIXES.length) {
272
+ for (const prefix of MEMORY_ALLOWED_PREFIXES) {
273
+ const folder = prefix.replace(/\/$/, '')
274
+ const fullPath = join(MEMORY_PATH, folder)
275
+ if (!existsSync(fullPath)) continue
276
+ await searchDirectory(fullPath, folder)
277
+ }
278
+ } else {
279
+ await searchDirectory(MEMORY_PATH)
280
+ }
281
 
282
  return NextResponse.json({
283
  query,
 
306
  if (!path) {
307
  return NextResponse.json({ error: 'Path is required' }, { status: 400 })
308
  }
309
+ if (!isPathAllowed(path)) {
310
+ return NextResponse.json({ error: 'Path not allowed' }, { status: 403 })
311
+ }
312
 
313
  if (!MEMORY_PATH) {
314
  return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 })
 
369
  if (!path) {
370
  return NextResponse.json({ error: 'Path is required' }, { status: 400 })
371
  }
372
+ if (!isPathAllowed(path)) {
373
+ return NextResponse.json({ error: 'Path not allowed' }, { status: 403 })
374
+ }
375
 
376
  if (!MEMORY_PATH) {
377
  return NextResponse.json({ error: 'Memory directory not configured' }, { status: 500 })
src/app/api/mentions/route.ts ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { getDatabase } from '@/lib/db'
4
+ import { getMentionTargets } from '@/lib/mentions'
5
+ import { logger } from '@/lib/logger'
6
+
7
+ /**
8
+ * GET /api/mentions - autocomplete source for @mentions (users + agents)
9
+ * Query: q?, limit?, type?
10
+ */
11
+ export async function GET(request: NextRequest) {
12
+ const auth = requireRole(request, 'viewer')
13
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
14
+
15
+ try {
16
+ const db = getDatabase()
17
+ const workspaceId = auth.user.workspace_id ?? 1
18
+ const { searchParams } = new URL(request.url)
19
+
20
+ const q = String(searchParams.get('q') || '').trim().toLowerCase()
21
+ const typeFilter = String(searchParams.get('type') || '').trim().toLowerCase()
22
+ const limitRaw = Number.parseInt(searchParams.get('limit') || '25', 10)
23
+ const limit = Math.max(1, Math.min(Number.isFinite(limitRaw) ? limitRaw : 25, 200))
24
+
25
+ let targets = getMentionTargets(db, workspaceId)
26
+
27
+ if (typeFilter === 'user' || typeFilter === 'agent') {
28
+ targets = targets.filter((target) => target.type === typeFilter)
29
+ }
30
+
31
+ if (q) {
32
+ targets = targets.filter((target) => (
33
+ target.handle.includes(q) ||
34
+ target.recipient.toLowerCase().includes(q) ||
35
+ target.display.toLowerCase().includes(q)
36
+ ))
37
+ }
38
+
39
+ targets = targets.slice(0, limit)
40
+
41
+ return NextResponse.json({
42
+ mentions: targets,
43
+ total: targets.length,
44
+ q,
45
+ })
46
+ } catch (error) {
47
+ logger.error({ err: error }, 'GET /api/mentions error')
48
+ return NextResponse.json({ error: 'Failed to fetch mention targets' }, { status: 500 })
49
+ }
50
+ }
src/app/api/projects/[id]/route.ts ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { getDatabase } from '@/lib/db'
3
+ import { requireRole } from '@/lib/auth'
4
+ import { mutationLimiter } from '@/lib/rate-limit'
5
+ import { logger } from '@/lib/logger'
6
+
7
+ function normalizePrefix(input: string): string {
8
+ const normalized = input.trim().toUpperCase().replace(/[^A-Z0-9]/g, '')
9
+ return normalized.slice(0, 12)
10
+ }
11
+
12
+ function toProjectId(raw: string): number {
13
+ const id = Number.parseInt(raw, 10)
14
+ return Number.isFinite(id) ? id : NaN
15
+ }
16
+
17
+ export async function GET(
18
+ request: NextRequest,
19
+ { params }: { params: Promise<{ id: string }> }
20
+ ) {
21
+ const auth = requireRole(request, 'viewer')
22
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
23
+
24
+ try {
25
+ const db = getDatabase()
26
+ const workspaceId = auth.user.workspace_id ?? 1
27
+ const { id } = await params
28
+ const projectId = toProjectId(id)
29
+ if (Number.isNaN(projectId)) return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 })
30
+
31
+ const project = db.prepare(`
32
+ SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at
33
+ FROM projects
34
+ WHERE id = ? AND workspace_id = ?
35
+ `).get(projectId, workspaceId)
36
+ if (!project) return NextResponse.json({ error: 'Project not found' }, { status: 404 })
37
+
38
+ return NextResponse.json({ project })
39
+ } catch (error) {
40
+ logger.error({ err: error }, 'GET /api/projects/[id] error')
41
+ return NextResponse.json({ error: 'Failed to fetch project' }, { status: 500 })
42
+ }
43
+ }
44
+
45
+ export async function PATCH(
46
+ request: NextRequest,
47
+ { params }: { params: Promise<{ id: string }> }
48
+ ) {
49
+ const auth = requireRole(request, 'operator')
50
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
51
+
52
+ const rateCheck = mutationLimiter(request)
53
+ if (rateCheck) return rateCheck
54
+
55
+ try {
56
+ const db = getDatabase()
57
+ const workspaceId = auth.user.workspace_id ?? 1
58
+ const { id } = await params
59
+ const projectId = toProjectId(id)
60
+ if (Number.isNaN(projectId)) return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 })
61
+
62
+ const current = db.prepare(`SELECT * FROM projects WHERE id = ? AND workspace_id = ?`).get(projectId, workspaceId) as any
63
+ if (!current) return NextResponse.json({ error: 'Project not found' }, { status: 404 })
64
+ if (current.slug === 'general' && current.workspace_id === workspaceId && current.id === projectId) {
65
+ const body = await request.json()
66
+ if (body?.status === 'archived') {
67
+ return NextResponse.json({ error: 'Default project cannot be archived' }, { status: 400 })
68
+ }
69
+ }
70
+
71
+ const body = await request.json()
72
+ const updates: string[] = []
73
+ const paramsList: Array<string | number | null> = []
74
+
75
+ if (typeof body?.name === 'string') {
76
+ const name = body.name.trim()
77
+ if (!name) return NextResponse.json({ error: 'Project name cannot be empty' }, { status: 400 })
78
+ updates.push('name = ?')
79
+ paramsList.push(name)
80
+ }
81
+ if (typeof body?.description === 'string') {
82
+ updates.push('description = ?')
83
+ paramsList.push(body.description.trim() || null)
84
+ }
85
+ if (typeof body?.ticket_prefix === 'string' || typeof body?.ticketPrefix === 'string') {
86
+ const raw = String(body.ticket_prefix ?? body.ticketPrefix)
87
+ const prefix = normalizePrefix(raw)
88
+ if (!prefix) return NextResponse.json({ error: 'Invalid ticket prefix' }, { status: 400 })
89
+ const conflict = db.prepare(`
90
+ SELECT id FROM projects
91
+ WHERE workspace_id = ? AND ticket_prefix = ? AND id != ?
92
+ `).get(workspaceId, prefix, projectId)
93
+ if (conflict) return NextResponse.json({ error: 'Ticket prefix already in use' }, { status: 409 })
94
+ updates.push('ticket_prefix = ?')
95
+ paramsList.push(prefix)
96
+ }
97
+ if (typeof body?.status === 'string') {
98
+ const status = body.status === 'archived' ? 'archived' : 'active'
99
+ updates.push('status = ?')
100
+ paramsList.push(status)
101
+ }
102
+
103
+ if (updates.length === 0) return NextResponse.json({ error: 'No fields to update' }, { status: 400 })
104
+
105
+ updates.push('updated_at = unixepoch()')
106
+ db.prepare(`
107
+ UPDATE projects
108
+ SET ${updates.join(', ')}
109
+ WHERE id = ? AND workspace_id = ?
110
+ `).run(...paramsList, projectId, workspaceId)
111
+
112
+ const project = db.prepare(`
113
+ SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at
114
+ FROM projects
115
+ WHERE id = ? AND workspace_id = ?
116
+ `).get(projectId, workspaceId)
117
+
118
+ return NextResponse.json({ project })
119
+ } catch (error) {
120
+ logger.error({ err: error }, 'PATCH /api/projects/[id] error')
121
+ return NextResponse.json({ error: 'Failed to update project' }, { status: 500 })
122
+ }
123
+ }
124
+
125
+ export async function DELETE(
126
+ request: NextRequest,
127
+ { params }: { params: Promise<{ id: string }> }
128
+ ) {
129
+ const auth = requireRole(request, 'admin')
130
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
131
+
132
+ const rateCheck = mutationLimiter(request)
133
+ if (rateCheck) return rateCheck
134
+
135
+ try {
136
+ const db = getDatabase()
137
+ const workspaceId = auth.user.workspace_id ?? 1
138
+ const { id } = await params
139
+ const projectId = toProjectId(id)
140
+ if (Number.isNaN(projectId)) return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 })
141
+
142
+ const current = db.prepare(`SELECT * FROM projects WHERE id = ? AND workspace_id = ?`).get(projectId, workspaceId) as any
143
+ if (!current) return NextResponse.json({ error: 'Project not found' }, { status: 404 })
144
+ if (current.slug === 'general') {
145
+ return NextResponse.json({ error: 'Default project cannot be deleted' }, { status: 400 })
146
+ }
147
+
148
+ const mode = new URL(request.url).searchParams.get('mode') || 'archive'
149
+ if (mode !== 'delete') {
150
+ db.prepare(`UPDATE projects SET status = 'archived', updated_at = unixepoch() WHERE id = ? AND workspace_id = ?`).run(projectId, workspaceId)
151
+ return NextResponse.json({ success: true, mode: 'archive' })
152
+ }
153
+
154
+ const fallback = db.prepare(`
155
+ SELECT id FROM projects
156
+ WHERE workspace_id = ? AND slug = 'general'
157
+ LIMIT 1
158
+ `).get(workspaceId) as { id: number } | undefined
159
+ if (!fallback) return NextResponse.json({ error: 'Default project missing' }, { status: 500 })
160
+
161
+ const tx = db.transaction(() => {
162
+ db.prepare(`
163
+ UPDATE tasks
164
+ SET project_id = ?
165
+ WHERE workspace_id = ? AND project_id = ?
166
+ `).run(fallback.id, workspaceId, projectId)
167
+
168
+ db.prepare(`DELETE FROM projects WHERE id = ? AND workspace_id = ?`).run(projectId, workspaceId)
169
+ })
170
+ tx()
171
+
172
+ return NextResponse.json({ success: true, mode: 'delete' })
173
+ } catch (error) {
174
+ logger.error({ err: error }, 'DELETE /api/projects/[id] error')
175
+ return NextResponse.json({ error: 'Failed to delete project' }, { status: 500 })
176
+ }
177
+ }
src/app/api/projects/[id]/tasks/route.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { getDatabase } from '@/lib/db'
3
+ import { requireRole } from '@/lib/auth'
4
+ import { logger } from '@/lib/logger'
5
+
6
+ function formatTicketRef(prefix?: string | null, num?: number | null): string | undefined {
7
+ if (!prefix || typeof num !== 'number' || !Number.isFinite(num) || num <= 0) return undefined
8
+ return `${prefix}-${String(num).padStart(3, '0')}`
9
+ }
10
+
11
+ export async function GET(
12
+ request: NextRequest,
13
+ { params }: { params: Promise<{ id: string }> }
14
+ ) {
15
+ const auth = requireRole(request, 'viewer')
16
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
17
+
18
+ try {
19
+ const db = getDatabase()
20
+ const workspaceId = auth.user.workspace_id ?? 1
21
+ const { id } = await params
22
+ const projectId = Number.parseInt(id, 10)
23
+ if (!Number.isFinite(projectId)) {
24
+ return NextResponse.json({ error: 'Invalid project ID' }, { status: 400 })
25
+ }
26
+
27
+ const project = db.prepare(`
28
+ SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at
29
+ FROM projects
30
+ WHERE id = ? AND workspace_id = ?
31
+ `).get(projectId, workspaceId)
32
+ if (!project) return NextResponse.json({ error: 'Project not found' }, { status: 404 })
33
+
34
+ const tasks = db.prepare(`
35
+ SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix
36
+ FROM tasks t
37
+ LEFT JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id
38
+ WHERE t.workspace_id = ? AND t.project_id = ?
39
+ ORDER BY t.created_at DESC
40
+ `).all(workspaceId, projectId)
41
+
42
+ return NextResponse.json({
43
+ project,
44
+ tasks: tasks.map((task: any) => ({
45
+ ...task,
46
+ tags: task.tags ? JSON.parse(task.tags) : [],
47
+ metadata: task.metadata ? JSON.parse(task.metadata) : {},
48
+ ticket_ref: formatTicketRef(task.project_prefix, task.project_ticket_no),
49
+ }))
50
+ })
51
+ } catch (error) {
52
+ logger.error({ err: error }, 'GET /api/projects/[id]/tasks error')
53
+ return NextResponse.json({ error: 'Failed to fetch project tasks' }, { status: 500 })
54
+ }
55
+ }
src/app/api/projects/route.ts ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { getDatabase } from '@/lib/db'
3
+ import { requireRole } from '@/lib/auth'
4
+ import { mutationLimiter } from '@/lib/rate-limit'
5
+ import { logger } from '@/lib/logger'
6
+
7
+ function slugify(input: string): string {
8
+ return input
9
+ .trim()
10
+ .toLowerCase()
11
+ .replace(/[^a-z0-9]+/g, '-')
12
+ .replace(/^-+|-+$/g, '')
13
+ .slice(0, 64)
14
+ }
15
+
16
+ function normalizePrefix(input: string): string {
17
+ const normalized = input.trim().toUpperCase().replace(/[^A-Z0-9]/g, '')
18
+ return normalized.slice(0, 12)
19
+ }
20
+
21
+ export async function GET(request: NextRequest) {
22
+ const auth = requireRole(request, 'viewer')
23
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
24
+
25
+ try {
26
+ const db = getDatabase()
27
+ const workspaceId = auth.user.workspace_id ?? 1
28
+ const includeArchived = new URL(request.url).searchParams.get('includeArchived') === '1'
29
+
30
+ const projects = db.prepare(`
31
+ SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at
32
+ FROM projects
33
+ WHERE workspace_id = ?
34
+ ${includeArchived ? '' : "AND status = 'active'"}
35
+ ORDER BY name COLLATE NOCASE ASC
36
+ `).all(workspaceId)
37
+
38
+ return NextResponse.json({ projects })
39
+ } catch (error) {
40
+ logger.error({ err: error }, 'GET /api/projects error')
41
+ return NextResponse.json({ error: 'Failed to fetch projects' }, { status: 500 })
42
+ }
43
+ }
44
+
45
+ export async function POST(request: NextRequest) {
46
+ const auth = requireRole(request, 'operator')
47
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
48
+
49
+ const rateCheck = mutationLimiter(request)
50
+ if (rateCheck) return rateCheck
51
+
52
+ try {
53
+ const db = getDatabase()
54
+ const workspaceId = auth.user.workspace_id ?? 1
55
+ const body = await request.json()
56
+
57
+ const name = String(body?.name || '').trim()
58
+ const description = typeof body?.description === 'string' ? body.description.trim() : ''
59
+ const prefixInput = String(body?.ticket_prefix || body?.ticketPrefix || '').trim()
60
+ const slugInput = String(body?.slug || '').trim()
61
+
62
+ if (!name) return NextResponse.json({ error: 'Project name is required' }, { status: 400 })
63
+
64
+ const slug = slugInput ? slugify(slugInput) : slugify(name)
65
+ const ticketPrefix = normalizePrefix(prefixInput || name.slice(0, 5))
66
+ if (!slug) return NextResponse.json({ error: 'Invalid project slug' }, { status: 400 })
67
+ if (!ticketPrefix) return NextResponse.json({ error: 'Invalid ticket prefix' }, { status: 400 })
68
+
69
+ const exists = db.prepare(`
70
+ SELECT id FROM projects
71
+ WHERE workspace_id = ? AND (slug = ? OR ticket_prefix = ?)
72
+ LIMIT 1
73
+ `).get(workspaceId, slug, ticketPrefix) as { id: number } | undefined
74
+ if (exists) {
75
+ return NextResponse.json({ error: 'Project slug or ticket prefix already exists' }, { status: 409 })
76
+ }
77
+
78
+ const result = db.prepare(`
79
+ INSERT INTO projects (workspace_id, name, slug, description, ticket_prefix, status, created_at, updated_at)
80
+ VALUES (?, ?, ?, ?, ?, 'active', unixepoch(), unixepoch())
81
+ `).run(workspaceId, name, slug, description || null, ticketPrefix)
82
+
83
+ const project = db.prepare(`
84
+ SELECT id, workspace_id, name, slug, description, ticket_prefix, ticket_counter, status, created_at, updated_at
85
+ FROM projects
86
+ WHERE id = ?
87
+ `).get(Number(result.lastInsertRowid))
88
+
89
+ return NextResponse.json({ project }, { status: 201 })
90
+ } catch (error) {
91
+ logger.error({ err: error }, 'POST /api/projects error')
92
+ return NextResponse.json({ error: 'Failed to create project' }, { status: 500 })
93
+ }
94
+ }
src/app/api/settings/route.ts CHANGED
@@ -23,6 +23,7 @@ const settingDefinitions: Record<string, { category: string; description: string
23
  'retention.notifications_days': { category: 'retention', description: 'Days to keep notifications', default: String(config.retention.notifications) },
24
  'retention.pipeline_runs_days': { category: 'retention', description: 'Days to keep pipeline run history', default: String(config.retention.pipelineRuns) },
25
  'retention.token_usage_days': { category: 'retention', description: 'Days to keep token usage data', default: String(config.retention.tokenUsage) },
 
26
 
27
  // Gateway
28
  'gateway.host': { category: 'gateway', description: 'Gateway hostname', default: config.gatewayHost },
 
23
  'retention.notifications_days': { category: 'retention', description: 'Days to keep notifications', default: String(config.retention.notifications) },
24
  'retention.pipeline_runs_days': { category: 'retention', description: 'Days to keep pipeline run history', default: String(config.retention.pipelineRuns) },
25
  'retention.token_usage_days': { category: 'retention', description: 'Days to keep token usage data', default: String(config.retention.tokenUsage) },
26
+ 'retention.gateway_sessions_days': { category: 'retention', description: 'Days to keep inactive gateway session metadata', default: String(config.retention.gatewaySessions) },
27
 
28
  // Gateway
29
  'gateway.host': { category: 'gateway', description: 'Gateway hostname', default: config.gatewayHost },
src/app/api/spawn/route.ts CHANGED
@@ -8,6 +8,15 @@ import { heavyLimiter } from '@/lib/rate-limit'
8
  import { logger } from '@/lib/logger'
9
  import { validateBody, spawnAgentSchema } from '@/lib/validation'
10
 
 
 
 
 
 
 
 
 
 
11
  export async function POST(request: NextRequest) {
12
  const auth = requireRole(request, 'operator')
13
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
@@ -31,15 +40,38 @@ export async function POST(request: NextRequest) {
31
  task,
32
  model,
33
  label,
34
- runTimeoutSeconds: timeout
 
 
 
35
  }
36
- const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})`
37
 
38
  try {
39
- // Execute the spawn command
40
- const { stdout, stderr } = await runClawdbot(['-c', commandArg], {
41
- timeoutMs: 10000
42
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  // Parse the response to extract session info
45
  let sessionInfo = null
@@ -63,7 +95,11 @@ export async function POST(request: NextRequest) {
63
  timeoutSeconds: timeout,
64
  createdAt: Date.now(),
65
  stdout: stdout.trim(),
66
- stderr: stderr.trim()
 
 
 
 
67
  })
68
 
69
  } catch (execError: any) {
 
8
  import { logger } from '@/lib/logger'
9
  import { validateBody, spawnAgentSchema } from '@/lib/validation'
10
 
11
+ function getPreferredToolsProfile(): string {
12
+ return String(process.env.OPENCLAW_TOOLS_PROFILE || 'coding').trim() || 'coding'
13
+ }
14
+
15
+ async function runSpawnWithCompatibility(spawnPayload: Record<string, unknown>) {
16
+ const commandArg = `sessions_spawn(${JSON.stringify(spawnPayload)})`
17
+ return runClawdbot(['-c', commandArg], { timeoutMs: 10000 })
18
+ }
19
+
20
  export async function POST(request: NextRequest) {
21
  const auth = requireRole(request, 'operator')
22
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
 
40
  task,
41
  model,
42
  label,
43
+ runTimeoutSeconds: timeout,
44
+ tools: {
45
+ profile: getPreferredToolsProfile(),
46
+ },
47
  }
 
48
 
49
  try {
50
+ // Execute the spawn command (OpenClaw 2026.3.2+ defaults tools.profile to messaging).
51
+ let stdout = ''
52
+ let stderr = ''
53
+ let compatibilityFallbackUsed = false
54
+ try {
55
+ const result = await runSpawnWithCompatibility(spawnPayload)
56
+ stdout = result.stdout
57
+ stderr = result.stderr
58
+ } catch (firstError: any) {
59
+ const rawErr = String(firstError?.stderr || firstError?.message || '').toLowerCase()
60
+ const likelySchemaMismatch =
61
+ rawErr.includes('unknown field') ||
62
+ rawErr.includes('unknown key') ||
63
+ rawErr.includes('invalid argument') ||
64
+ rawErr.includes('tools') ||
65
+ rawErr.includes('profile')
66
+ if (!likelySchemaMismatch) throw firstError
67
+
68
+ const fallbackPayload = { ...spawnPayload }
69
+ delete (fallbackPayload as any).tools
70
+ const fallback = await runSpawnWithCompatibility(fallbackPayload)
71
+ stdout = fallback.stdout
72
+ stderr = fallback.stderr
73
+ compatibilityFallbackUsed = true
74
+ }
75
 
76
  // Parse the response to extract session info
77
  let sessionInfo = null
 
95
  timeoutSeconds: timeout,
96
  createdAt: Date.now(),
97
  stdout: stdout.trim(),
98
+ stderr: stderr.trim(),
99
+ compatibility: {
100
+ toolsProfile: getPreferredToolsProfile(),
101
+ fallbackUsed: compatibilityFallbackUsed,
102
+ },
103
  })
104
 
105
  } catch (execError: any) {
src/app/api/status/route.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import net from 'node:net'
3
- import { existsSync, readFileSync, statSync } from 'node:fs'
 
4
  import path from 'node:path'
5
  import { runCommand, runOpenClaw, runClawdbot } from '@/lib/command'
6
  import { config } from '@/lib/config'
@@ -9,6 +10,7 @@ import { getAllGatewaySessions, getAgentLiveStatuses } from '@/lib/sessions'
9
  import { requireRole } from '@/lib/auth'
10
  import { MODEL_CATALOG } from '@/lib/models'
11
  import { logger } from '@/lib/logger'
 
12
 
13
  export async function GET(request: NextRequest) {
14
  const auth = requireRole(request, 'viewer')
@@ -194,29 +196,48 @@ async function getSystemStatus(workspaceId: number) {
194
  }
195
 
196
  try {
197
- // System uptime
198
- const { stdout: uptimeOutput } = await runCommand('uptime', ['-s'], {
199
- timeoutMs: 3000
200
- })
201
- const bootTime = new Date(uptimeOutput.trim())
202
- status.uptime = Date.now() - bootTime.getTime()
 
 
 
 
 
 
 
 
 
 
 
203
  } catch (error) {
204
  logger.error({ err: error }, 'Error getting uptime')
205
  }
206
 
207
  try {
208
- // Memory info
209
- const { stdout: memOutput } = await runCommand('free', ['-m'], {
210
- timeoutMs: 3000
211
- })
212
- const memLines = memOutput.split('\n')
213
- const memLine = memLines.find(line => line.startsWith('Mem:'))
214
- if (memLine) {
215
- const parts = memLine.split(/\s+/)
216
- status.memory = {
217
- total: parseInt(parts[1]) || 0,
218
- used: parseInt(parts[2]) || 0,
219
- available: parseInt(parts[6]) || 0
 
 
 
 
 
 
 
 
220
  }
221
  }
222
  } catch (error) {
@@ -413,14 +434,17 @@ async function performHealthCheck() {
413
  })
414
  }
415
 
416
- // Check disk space
417
  try {
418
- const { stdout } = await runCommand('df', ['/', '--output=pcent'], {
419
  timeoutMs: 3000
420
  })
421
  const lines = stdout.trim().split('\n')
422
  const last = lines[lines.length - 1] || ''
423
- const usagePercent = parseInt(last.replace('%', '').trim() || '0')
 
 
 
424
 
425
  health.checks.push({
426
  name: 'Disk Space',
@@ -435,15 +459,21 @@ async function performHealthCheck() {
435
  })
436
  }
437
 
438
- // Check memory usage
439
  try {
440
- const { stdout } = await runCommand('free', ['-m'], { timeoutMs: 3000 })
441
- const lines = stdout.split('\n')
442
- const memLine = lines.find((line) => line.startsWith('Mem:'))
443
- const parts = (memLine || '').split(/\s+/)
444
- const total = parseInt(parts[1] || '0')
445
- const available = parseInt(parts[6] || '0')
446
- const usagePercent = Math.round(((total - available) / total) * 100)
 
 
 
 
 
 
447
 
448
  health.checks.push({
449
  name: 'Memory Usage',
@@ -475,7 +505,10 @@ async function performHealthCheck() {
475
  async function getCapabilities() {
476
  const gateway = await isPortOpen(config.gatewayHost, config.gatewayPort)
477
 
478
- const openclawHome = !!(config.openclawHome && existsSync(config.openclawHome))
 
 
 
479
 
480
  const claudeProjectsPath = path.join(config.claudeHome, 'projects')
481
  const claudeHome = existsSync(claudeProjectsPath)
@@ -491,25 +524,14 @@ async function getCapabilities() {
491
  // claude_sessions table may not exist
492
  }
493
 
494
- // Detect Claude subscription type from credentials
495
- let subscription: { type: string; rateLimitTier?: string } | null = null
496
- try {
497
- const credsPath = path.join(config.claudeHome, '.credentials.json')
498
- if (existsSync(credsPath)) {
499
- const creds = JSON.parse(readFileSync(credsPath, 'utf-8'))
500
- const oauth = creds.claudeAiOauth
501
- if (oauth?.subscriptionType) {
502
- subscription = {
503
- type: oauth.subscriptionType,
504
- rateLimitTier: oauth.rateLimitTier || undefined,
505
- }
506
- }
507
- }
508
- } catch {
509
- // credentials file may not exist or be unreadable
510
- }
511
 
512
- return { gateway, openclawHome, claudeHome, claudeSessions, subscription }
513
  }
514
 
515
  function isPortOpen(host: string, port: number): Promise<boolean> {
 
1
  import { NextRequest, NextResponse } from 'next/server'
2
  import net from 'node:net'
3
+ import os from 'node:os'
4
+ import { existsSync, statSync } from 'node:fs'
5
  import path from 'node:path'
6
  import { runCommand, runOpenClaw, runClawdbot } from '@/lib/command'
7
  import { config } from '@/lib/config'
 
10
  import { requireRole } from '@/lib/auth'
11
  import { MODEL_CATALOG } from '@/lib/models'
12
  import { logger } from '@/lib/logger'
13
+ import { detectProviderSubscriptions, getPrimarySubscription } from '@/lib/provider-subscriptions'
14
 
15
  export async function GET(request: NextRequest) {
16
  const auth = requireRole(request, 'viewer')
 
196
  }
197
 
198
  try {
199
+ // System uptime (cross-platform)
200
+ if (process.platform === 'darwin') {
201
+ const { stdout } = await runCommand('sysctl', ['-n', 'kern.boottime'], {
202
+ timeoutMs: 3000
203
+ })
204
+ // Output format: { sec = 1234567890, usec = 0 } ...
205
+ const match = stdout.match(/sec\s*=\s*(\d+)/)
206
+ if (match) {
207
+ status.uptime = Date.now() - parseInt(match[1]) * 1000
208
+ }
209
+ } else {
210
+ const { stdout } = await runCommand('uptime', ['-s'], {
211
+ timeoutMs: 3000
212
+ })
213
+ const bootTime = new Date(stdout.trim())
214
+ status.uptime = Date.now() - bootTime.getTime()
215
+ }
216
  } catch (error) {
217
  logger.error({ err: error }, 'Error getting uptime')
218
  }
219
 
220
  try {
221
+ // Memory info (cross-platform)
222
+ if (process.platform === 'darwin') {
223
+ const totalBytes = os.totalmem()
224
+ const freeBytes = os.freemem()
225
+ const totalMB = Math.round(totalBytes / (1024 * 1024))
226
+ const usedMB = Math.round((totalBytes - freeBytes) / (1024 * 1024))
227
+ const availableMB = Math.round(freeBytes / (1024 * 1024))
228
+ status.memory = { total: totalMB, used: usedMB, available: availableMB }
229
+ } else {
230
+ const { stdout: memOutput } = await runCommand('free', ['-m'], {
231
+ timeoutMs: 3000
232
+ })
233
+ const memLine = memOutput.split('\n').find(line => line.startsWith('Mem:'))
234
+ if (memLine) {
235
+ const parts = memLine.split(/\s+/)
236
+ status.memory = {
237
+ total: parseInt(parts[1]) || 0,
238
+ used: parseInt(parts[2]) || 0,
239
+ available: parseInt(parts[6]) || 0
240
+ }
241
  }
242
  }
243
  } catch (error) {
 
434
  })
435
  }
436
 
437
+ // Check disk space (cross-platform: use df -h / and parse capacity column)
438
  try {
439
+ const { stdout } = await runCommand('df', ['-h', '/'], {
440
  timeoutMs: 3000
441
  })
442
  const lines = stdout.trim().split('\n')
443
  const last = lines[lines.length - 1] || ''
444
+ const parts = last.split(/\s+/)
445
+ // On macOS capacity is col 4 ("85%"), on Linux use% is col 4 as well
446
+ const pctField = parts.find(p => p.endsWith('%')) || '0%'
447
+ const usagePercent = parseInt(pctField.replace('%', '') || '0')
448
 
449
  health.checks.push({
450
  name: 'Disk Space',
 
459
  })
460
  }
461
 
462
+ // Check memory usage (cross-platform)
463
  try {
464
+ let usagePercent: number
465
+ if (process.platform === 'darwin') {
466
+ const totalBytes = os.totalmem()
467
+ const freeBytes = os.freemem()
468
+ usagePercent = Math.round(((totalBytes - freeBytes) / totalBytes) * 100)
469
+ } else {
470
+ const { stdout } = await runCommand('free', ['-m'], { timeoutMs: 3000 })
471
+ const memLine = stdout.split('\n').find((line) => line.startsWith('Mem:'))
472
+ const parts = (memLine || '').split(/\s+/)
473
+ const total = parseInt(parts[1] || '0')
474
+ const available = parseInt(parts[6] || '0')
475
+ usagePercent = Math.round(((total - available) / total) * 100)
476
+ }
477
 
478
  health.checks.push({
479
  name: 'Memory Usage',
 
505
  async function getCapabilities() {
506
  const gateway = await isPortOpen(config.gatewayHost, config.gatewayPort)
507
 
508
+ const openclawHome = Boolean(
509
+ (config.openclawStateDir && existsSync(config.openclawStateDir)) ||
510
+ (config.openclawConfigPath && existsSync(config.openclawConfigPath))
511
+ )
512
 
513
  const claudeProjectsPath = path.join(config.claudeHome, 'projects')
514
  const claudeHome = existsSync(claudeProjectsPath)
 
524
  // claude_sessions table may not exist
525
  }
526
 
527
+ const subscriptions = detectProviderSubscriptions().active
528
+ const primary = getPrimarySubscription()
529
+ const subscription = primary ? {
530
+ type: primary.type,
531
+ provider: primary.provider,
532
+ } : null
 
 
 
 
 
 
 
 
 
 
 
533
 
534
+ return { gateway, openclawHome, claudeHome, claudeSessions, subscription, subscriptions }
535
  }
536
 
537
  function isPortOpen(host: string, port: number): Promise<boolean> {
src/app/api/tasks/[id]/comments/route.ts CHANGED
@@ -4,6 +4,7 @@ import { requireRole } from '@/lib/auth';
4
  import { validateBody, createCommentSchema } from '@/lib/validation';
5
  import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
 
7
 
8
  /**
9
  * GET /api/tasks/[id]/comments - Get all comments for a task
@@ -128,8 +129,13 @@ export async function POST(
128
  }
129
  }
130
 
131
- // Parse @mentions from content
132
- const mentions = db_helpers.parseMentions(content);
 
 
 
 
 
133
 
134
  const now = Math.floor(Date.now() / 1000);
135
 
@@ -145,7 +151,7 @@ export async function POST(
145
  content,
146
  now,
147
  parent_id || null,
148
- mentions.length > 0 ? JSON.stringify(mentions) : null,
149
  workspaceId
150
  );
151
 
@@ -166,7 +172,7 @@ export async function POST(
166
  task_id: taskId,
167
  task_title: task.title,
168
  parent_id,
169
- mentions,
170
  content_preview: content.substring(0, 100)
171
  },
172
  workspaceId
@@ -174,9 +180,9 @@ export async function POST(
174
 
175
  // Ensure subscriptions for author, mentions, and assignee
176
  db_helpers.ensureTaskSubscription(taskId, author, workspaceId);
177
- const uniqueMentions = Array.from(new Set(mentions));
178
- uniqueMentions.forEach((mentionedAgent) => {
179
- db_helpers.ensureTaskSubscription(taskId, mentionedAgent, workspaceId);
180
  });
181
  if (task.assigned_to) {
182
  db_helpers.ensureTaskSubscription(taskId, task.assigned_to, workspaceId);
@@ -185,7 +191,7 @@ export async function POST(
185
  // Notify subscribers
186
  const subscribers = new Set(db_helpers.getTaskSubscribers(taskId, workspaceId));
187
  subscribers.delete(author);
188
- const mentionSet = new Set(uniqueMentions);
189
 
190
  for (const subscriber of subscribers) {
191
  const isMention = mentionSet.has(subscriber);
 
4
  import { validateBody, createCommentSchema } from '@/lib/validation';
5
  import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
+ import { resolveMentionRecipients } from '@/lib/mentions';
8
 
9
  /**
10
  * GET /api/tasks/[id]/comments - Get all comments for a task
 
129
  }
130
  }
131
 
132
+ const mentionResolution = resolveMentionRecipients(content, db, workspaceId);
133
+ if (mentionResolution.unresolved.length > 0) {
134
+ return NextResponse.json({
135
+ error: `Unknown mentions: ${mentionResolution.unresolved.map((m) => `@${m}`).join(', ')}`,
136
+ missing_mentions: mentionResolution.unresolved
137
+ }, { status: 400 });
138
+ }
139
 
140
  const now = Math.floor(Date.now() / 1000);
141
 
 
151
  content,
152
  now,
153
  parent_id || null,
154
+ mentionResolution.tokens.length > 0 ? JSON.stringify(mentionResolution.tokens) : null,
155
  workspaceId
156
  );
157
 
 
172
  task_id: taskId,
173
  task_title: task.title,
174
  parent_id,
175
+ mentions: mentionResolution.tokens,
176
  content_preview: content.substring(0, 100)
177
  },
178
  workspaceId
 
180
 
181
  // Ensure subscriptions for author, mentions, and assignee
182
  db_helpers.ensureTaskSubscription(taskId, author, workspaceId);
183
+ const mentionRecipients = mentionResolution.recipients;
184
+ mentionRecipients.forEach((mentionedRecipient) => {
185
+ db_helpers.ensureTaskSubscription(taskId, mentionedRecipient, workspaceId);
186
  });
187
  if (task.assigned_to) {
188
  db_helpers.ensureTaskSubscription(taskId, task.assigned_to, workspaceId);
 
191
  // Notify subscribers
192
  const subscribers = new Set(db_helpers.getTaskSubscribers(taskId, workspaceId));
193
  subscribers.delete(author);
194
+ const mentionSet = new Set(mentionRecipients);
195
 
196
  for (const subscriber of subscribers) {
197
  const isMention = mentionSet.has(subscriber);
src/app/api/tasks/[id]/route.ts CHANGED
@@ -5,6 +5,22 @@ import { requireRole } from '@/lib/auth';
5
  import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
  import { validateBody, updateTaskSchema } from '@/lib/validation';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  function hasAegisApproval(
10
  db: ReturnType<typeof getDatabase>,
@@ -40,7 +56,12 @@ export async function GET(
40
  return NextResponse.json({ error: 'Invalid task ID' }, { status: 400 });
41
  }
42
 
43
- const stmt = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?');
 
 
 
 
 
44
  const task = stmt.get(taskId, workspaceId) as Task;
45
 
46
  if (!task) {
@@ -48,11 +69,7 @@ export async function GET(
48
  }
49
 
50
  // Parse JSON fields
51
- const taskWithParsedData = {
52
- ...task,
53
- tags: task.tags ? JSON.parse(task.tags) : [],
54
- metadata: task.metadata ? JSON.parse(task.metadata) : {}
55
- };
56
 
57
  return NextResponse.json({ task: taskWithParsedData });
58
  } catch (error) {
@@ -99,21 +116,47 @@ export async function PUT(
99
  const {
100
  title,
101
  description,
102
- status,
103
  priority,
 
104
  assigned_to,
105
  due_date,
106
  estimated_hours,
107
  actual_hours,
 
 
 
 
 
 
 
108
  tags,
109
  metadata
110
  } = body;
 
 
 
 
 
 
111
 
112
  const now = Math.floor(Date.now() / 1000);
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  // Build dynamic update query
115
  const fieldsToUpdate = [];
116
  const updateParams: any[] = [];
 
117
 
118
  if (title !== undefined) {
119
  fieldsToUpdate.push('title = ?');
@@ -123,20 +166,50 @@ export async function PUT(
123
  fieldsToUpdate.push('description = ?');
124
  updateParams.push(description);
125
  }
126
- if (status !== undefined) {
127
- if (status === 'done' && !hasAegisApproval(db, taskId, workspaceId)) {
128
  return NextResponse.json(
129
  { error: 'Aegis approval is required to move task to done.' },
130
  { status: 403 }
131
  )
132
  }
133
  fieldsToUpdate.push('status = ?');
134
- updateParams.push(status);
135
  }
136
  if (priority !== undefined) {
137
  fieldsToUpdate.push('priority = ?');
138
  updateParams.push(priority);
139
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  if (assigned_to !== undefined) {
141
  fieldsToUpdate.push('assigned_to = ?');
142
  updateParams.push(assigned_to);
@@ -153,6 +226,37 @@ export async function PUT(
153
  fieldsToUpdate.push('actual_hours = ?');
154
  updateParams.push(actual_hours);
155
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  if (tags !== undefined) {
157
  fieldsToUpdate.push('tags = ?');
158
  updateParams.push(JSON.stringify(tags));
@@ -181,8 +285,8 @@ export async function PUT(
181
  // Track changes and log activities
182
  const changes: string[] = [];
183
 
184
- if (status && status !== currentTask.status) {
185
- changes.push(`status: ${currentTask.status} → ${status}`);
186
 
187
  // Create notification for status change if assigned
188
  if (currentTask.assigned_to) {
@@ -190,7 +294,7 @@ export async function PUT(
190
  currentTask.assigned_to,
191
  'status_change',
192
  'Task Status Updated',
193
- `Task "${currentTask.title}" status changed to ${status}`,
194
  'task',
195
  taskId,
196
  workspaceId
@@ -223,6 +327,32 @@ export async function PUT(
223
  if (priority && priority !== currentTask.priority) {
224
  changes.push(`priority: ${currentTask.priority} → ${priority}`);
225
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
  // Log activity if there were meaningful changes
228
  if (changes.length > 0) {
@@ -240,21 +370,20 @@ export async function PUT(
240
  priority: currentTask.priority,
241
  assigned_to: currentTask.assigned_to
242
  },
243
- newValues: { title, status, priority, assigned_to }
244
  },
245
  workspaceId
246
  );
247
  }
248
 
249
  // Fetch updated task
250
- const updatedTask = db
251
- .prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?')
252
- .get(taskId, workspaceId) as Task;
253
- const parsedTask = {
254
- ...updatedTask,
255
- tags: updatedTask.tags ? JSON.parse(updatedTask.tags) : [],
256
- metadata: updatedTask.metadata ? JSON.parse(updatedTask.metadata) : {}
257
- };
258
 
259
  // Broadcast to SSE clients
260
  eventBus.broadcast('task.updated', parsedTask);
 
5
  import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
  import { validateBody, updateTaskSchema } from '@/lib/validation';
8
+ import { resolveMentionRecipients } from '@/lib/mentions';
9
+ import { normalizeTaskUpdateStatus } from '@/lib/task-status';
10
+
11
+ function formatTicketRef(prefix?: string | null, num?: number | null): string | undefined {
12
+ if (!prefix || typeof num !== 'number' || !Number.isFinite(num) || num <= 0) return undefined
13
+ return `${prefix}-${String(num).padStart(3, '0')}`
14
+ }
15
+
16
+ function mapTaskRow(task: any): Task & { tags: string[]; metadata: Record<string, unknown> } {
17
+ return {
18
+ ...task,
19
+ tags: task.tags ? JSON.parse(task.tags) : [],
20
+ metadata: task.metadata ? JSON.parse(task.metadata) : {},
21
+ ticket_ref: formatTicketRef(task.project_prefix, task.project_ticket_no),
22
+ }
23
+ }
24
 
25
  function hasAegisApproval(
26
  db: ReturnType<typeof getDatabase>,
 
56
  return NextResponse.json({ error: 'Invalid task ID' }, { status: 400 });
57
  }
58
 
59
+ const stmt = db.prepare(`
60
+ SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix
61
+ FROM tasks t
62
+ LEFT JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id
63
+ WHERE t.id = ? AND t.workspace_id = ?
64
+ `);
65
  const task = stmt.get(taskId, workspaceId) as Task;
66
 
67
  if (!task) {
 
69
  }
70
 
71
  // Parse JSON fields
72
+ const taskWithParsedData = mapTaskRow(task);
 
 
 
 
73
 
74
  return NextResponse.json({ task: taskWithParsedData });
75
  } catch (error) {
 
116
  const {
117
  title,
118
  description,
119
+ status: requestedStatus,
120
  priority,
121
+ project_id,
122
  assigned_to,
123
  due_date,
124
  estimated_hours,
125
  actual_hours,
126
+ outcome,
127
+ error_message,
128
+ resolution,
129
+ feedback_rating,
130
+ feedback_notes,
131
+ retry_count,
132
+ completed_at,
133
  tags,
134
  metadata
135
  } = body;
136
+ const normalizedStatus = normalizeTaskUpdateStatus({
137
+ currentStatus: currentTask.status,
138
+ requestedStatus,
139
+ assignedTo: assigned_to,
140
+ assignedToProvided: assigned_to !== undefined,
141
+ })
142
 
143
  const now = Math.floor(Date.now() / 1000);
144
+ const descriptionMentionResolution = description !== undefined
145
+ ? resolveMentionRecipients(description || '', db, workspaceId)
146
+ : null;
147
+ if (descriptionMentionResolution && descriptionMentionResolution.unresolved.length > 0) {
148
+ return NextResponse.json({
149
+ error: `Unknown mentions: ${descriptionMentionResolution.unresolved.map((m) => `@${m}`).join(', ')}`,
150
+ missing_mentions: descriptionMentionResolution.unresolved
151
+ }, { status: 400 });
152
+ }
153
+
154
+ const previousDescriptionMentionRecipients = resolveMentionRecipients(currentTask.description || '', db, workspaceId).recipients;
155
 
156
  // Build dynamic update query
157
  const fieldsToUpdate = [];
158
  const updateParams: any[] = [];
159
+ let nextProjectTicketNo: number | null = null;
160
 
161
  if (title !== undefined) {
162
  fieldsToUpdate.push('title = ?');
 
166
  fieldsToUpdate.push('description = ?');
167
  updateParams.push(description);
168
  }
169
+ if (normalizedStatus !== undefined) {
170
+ if (normalizedStatus === 'done' && !hasAegisApproval(db, taskId, workspaceId)) {
171
  return NextResponse.json(
172
  { error: 'Aegis approval is required to move task to done.' },
173
  { status: 403 }
174
  )
175
  }
176
  fieldsToUpdate.push('status = ?');
177
+ updateParams.push(normalizedStatus);
178
  }
179
  if (priority !== undefined) {
180
  fieldsToUpdate.push('priority = ?');
181
  updateParams.push(priority);
182
  }
183
+ if (project_id !== undefined) {
184
+ const project = db.prepare(`
185
+ SELECT id FROM projects
186
+ WHERE id = ? AND workspace_id = ? AND status = 'active'
187
+ `).get(project_id, workspaceId) as { id: number } | undefined
188
+ if (!project) {
189
+ return NextResponse.json({ error: 'Project not found or archived' }, { status: 400 })
190
+ }
191
+ if (project_id !== currentTask.project_id) {
192
+ db.prepare(`
193
+ UPDATE projects
194
+ SET ticket_counter = ticket_counter + 1, updated_at = unixepoch()
195
+ WHERE id = ? AND workspace_id = ?
196
+ `).run(project_id, workspaceId)
197
+ const row = db.prepare(`
198
+ SELECT ticket_counter FROM projects
199
+ WHERE id = ? AND workspace_id = ?
200
+ `).get(project_id, workspaceId) as { ticket_counter: number } | undefined
201
+ if (!row || !row.ticket_counter) {
202
+ return NextResponse.json({ error: 'Failed to allocate project ticket number' }, { status: 500 })
203
+ }
204
+ nextProjectTicketNo = row.ticket_counter
205
+ }
206
+ fieldsToUpdate.push('project_id = ?');
207
+ updateParams.push(project_id);
208
+ if (nextProjectTicketNo !== null) {
209
+ fieldsToUpdate.push('project_ticket_no = ?');
210
+ updateParams.push(nextProjectTicketNo);
211
+ }
212
+ }
213
  if (assigned_to !== undefined) {
214
  fieldsToUpdate.push('assigned_to = ?');
215
  updateParams.push(assigned_to);
 
226
  fieldsToUpdate.push('actual_hours = ?');
227
  updateParams.push(actual_hours);
228
  }
229
+ if (outcome !== undefined) {
230
+ fieldsToUpdate.push('outcome = ?');
231
+ updateParams.push(outcome);
232
+ }
233
+ if (error_message !== undefined) {
234
+ fieldsToUpdate.push('error_message = ?');
235
+ updateParams.push(error_message);
236
+ }
237
+ if (resolution !== undefined) {
238
+ fieldsToUpdate.push('resolution = ?');
239
+ updateParams.push(resolution);
240
+ }
241
+ if (feedback_rating !== undefined) {
242
+ fieldsToUpdate.push('feedback_rating = ?');
243
+ updateParams.push(feedback_rating);
244
+ }
245
+ if (feedback_notes !== undefined) {
246
+ fieldsToUpdate.push('feedback_notes = ?');
247
+ updateParams.push(feedback_notes);
248
+ }
249
+ if (retry_count !== undefined) {
250
+ fieldsToUpdate.push('retry_count = ?');
251
+ updateParams.push(retry_count);
252
+ }
253
+ if (completed_at !== undefined) {
254
+ fieldsToUpdate.push('completed_at = ?');
255
+ updateParams.push(completed_at);
256
+ } else if (normalizedStatus === 'done' && !currentTask.completed_at) {
257
+ fieldsToUpdate.push('completed_at = ?');
258
+ updateParams.push(now);
259
+ }
260
  if (tags !== undefined) {
261
  fieldsToUpdate.push('tags = ?');
262
  updateParams.push(JSON.stringify(tags));
 
285
  // Track changes and log activities
286
  const changes: string[] = [];
287
 
288
+ if (normalizedStatus !== undefined && normalizedStatus !== currentTask.status) {
289
+ changes.push(`status: ${currentTask.status} → ${normalizedStatus}`);
290
 
291
  // Create notification for status change if assigned
292
  if (currentTask.assigned_to) {
 
294
  currentTask.assigned_to,
295
  'status_change',
296
  'Task Status Updated',
297
+ `Task "${currentTask.title}" status changed to ${normalizedStatus}`,
298
  'task',
299
  taskId,
300
  workspaceId
 
327
  if (priority && priority !== currentTask.priority) {
328
  changes.push(`priority: ${currentTask.priority} → ${priority}`);
329
  }
330
+
331
+ if (project_id !== undefined && project_id !== currentTask.project_id) {
332
+ changes.push(`project: ${currentTask.project_id || 'none'} → ${project_id}`);
333
+ }
334
+ if (outcome !== undefined && outcome !== currentTask.outcome) {
335
+ changes.push(`outcome: ${currentTask.outcome || 'unset'} → ${outcome || 'unset'}`);
336
+ }
337
+
338
+ if (descriptionMentionResolution) {
339
+ const newMentionRecipients = new Set(descriptionMentionResolution.recipients);
340
+ const previousRecipients = new Set(previousDescriptionMentionRecipients);
341
+ for (const recipient of newMentionRecipients) {
342
+ if (previousRecipients.has(recipient)) continue;
343
+ db_helpers.ensureTaskSubscription(taskId, recipient, workspaceId);
344
+ if (recipient === auth.user.username) continue;
345
+ db_helpers.createNotification(
346
+ recipient,
347
+ 'mention',
348
+ 'You were mentioned in a task description',
349
+ `${auth.user.username} mentioned you in task "${title || currentTask.title}"`,
350
+ 'task',
351
+ taskId,
352
+ workspaceId
353
+ );
354
+ }
355
+ }
356
 
357
  // Log activity if there were meaningful changes
358
  if (changes.length > 0) {
 
370
  priority: currentTask.priority,
371
  assigned_to: currentTask.assigned_to
372
  },
373
+ newValues: { title, status: normalizedStatus ?? currentTask.status, priority, assigned_to }
374
  },
375
  workspaceId
376
  );
377
  }
378
 
379
  // Fetch updated task
380
+ const updatedTask = db.prepare(`
381
+ SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix
382
+ FROM tasks t
383
+ LEFT JOIN projects p ON p.id = t.project_id AND p.workspace_id = t.workspace_id
384
+ WHERE t.id = ? AND t.workspace_id = ?
385
+ `).get(taskId, workspaceId) as Task;
386
+ const parsedTask = mapTaskRow(updatedTask);
 
387
 
388
  // Broadcast to SSE clients
389
  eventBus.broadcast('task.updated', parsedTask);
src/app/api/tasks/outcomes/route.ts ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { getDatabase } from '@/lib/db'
4
+ import { logger } from '@/lib/logger'
5
+
6
+ type Outcome = 'success' | 'failed' | 'partial' | 'abandoned'
7
+
8
+ function resolveSince(timeframe: string): number {
9
+ const now = Math.floor(Date.now() / 1000)
10
+ switch (timeframe) {
11
+ case 'day':
12
+ return now - 24 * 60 * 60
13
+ case 'week':
14
+ return now - 7 * 24 * 60 * 60
15
+ case 'month':
16
+ return now - 30 * 24 * 60 * 60
17
+ case 'all':
18
+ default:
19
+ return 0
20
+ }
21
+ }
22
+
23
+ function outcomeBuckets() {
24
+ return {
25
+ success: 0,
26
+ failed: 0,
27
+ partial: 0,
28
+ abandoned: 0,
29
+ unknown: 0,
30
+ }
31
+ }
32
+
33
+ export async function GET(request: NextRequest) {
34
+ const auth = requireRole(request, 'viewer')
35
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
36
+
37
+ try {
38
+ const workspaceId = auth.user.workspace_id ?? 1
39
+ const { searchParams } = new URL(request.url)
40
+ const timeframe = (searchParams.get('timeframe') || 'all').trim().toLowerCase()
41
+ const since = resolveSince(timeframe)
42
+
43
+ const db = getDatabase()
44
+ const rows = db.prepare(`
45
+ SELECT
46
+ id,
47
+ assigned_to,
48
+ priority,
49
+ outcome,
50
+ error_message,
51
+ retry_count,
52
+ created_at,
53
+ completed_at
54
+ FROM tasks
55
+ WHERE workspace_id = ?
56
+ AND status = 'done'
57
+ AND (? = 0 OR COALESCE(completed_at, updated_at) >= ?)
58
+ `).all(workspaceId, since, since) as Array<{
59
+ id: number
60
+ assigned_to?: string | null
61
+ priority?: string | null
62
+ outcome?: string | null
63
+ error_message?: string | null
64
+ retry_count?: number | null
65
+ created_at?: number | null
66
+ completed_at?: number | null
67
+ }>
68
+
69
+ const summary = {
70
+ total_done: rows.length,
71
+ with_outcome: 0,
72
+ by_outcome: outcomeBuckets(),
73
+ avg_retry_count: 0,
74
+ avg_time_to_resolution_seconds: 0,
75
+ success_rate: 0,
76
+ }
77
+
78
+ const byAgent: Record<string, ReturnType<typeof outcomeBuckets> & { total: number; success_rate: number }> = {}
79
+ const byPriority: Record<string, ReturnType<typeof outcomeBuckets> & { total: number; success_rate: number }> = {}
80
+ const errorMap = new Map<string, number>()
81
+
82
+ let totalRetryCount = 0
83
+ let totalResolutionSeconds = 0
84
+ let resolutionCount = 0
85
+
86
+ for (const row of rows) {
87
+ const outcome = (row.outcome || 'unknown') as Outcome | 'unknown'
88
+ const assignedTo = row.assigned_to || 'unassigned'
89
+ const priority = row.priority || 'unknown'
90
+ const retryCount = Number.isFinite(row.retry_count) ? Number(row.retry_count) : 0
91
+
92
+ if (outcome !== 'unknown') summary.with_outcome += 1
93
+ if (outcome in summary.by_outcome) {
94
+ summary.by_outcome[outcome as keyof typeof summary.by_outcome] += 1
95
+ } else {
96
+ summary.by_outcome.unknown += 1
97
+ }
98
+
99
+ if (!byAgent[assignedTo]) {
100
+ byAgent[assignedTo] = { ...outcomeBuckets(), total: 0, success_rate: 0 }
101
+ }
102
+ byAgent[assignedTo].total += 1
103
+ if (outcome in byAgent[assignedTo]) {
104
+ byAgent[assignedTo][outcome as keyof ReturnType<typeof outcomeBuckets>] += 1
105
+ } else {
106
+ byAgent[assignedTo].unknown += 1
107
+ }
108
+
109
+ if (!byPriority[priority]) {
110
+ byPriority[priority] = { ...outcomeBuckets(), total: 0, success_rate: 0 }
111
+ }
112
+ byPriority[priority].total += 1
113
+ if (outcome in byPriority[priority]) {
114
+ byPriority[priority][outcome as keyof ReturnType<typeof outcomeBuckets>] += 1
115
+ } else {
116
+ byPriority[priority].unknown += 1
117
+ }
118
+
119
+ totalRetryCount += retryCount
120
+
121
+ if (row.completed_at && row.created_at && row.completed_at >= row.created_at) {
122
+ totalResolutionSeconds += (row.completed_at - row.created_at)
123
+ resolutionCount += 1
124
+ }
125
+
126
+ const errorMessage = (row.error_message || '').trim()
127
+ if (errorMessage) {
128
+ errorMap.set(errorMessage, (errorMap.get(errorMessage) || 0) + 1)
129
+ }
130
+ }
131
+
132
+ summary.avg_retry_count = rows.length > 0 ? totalRetryCount / rows.length : 0
133
+ summary.avg_time_to_resolution_seconds = resolutionCount > 0 ? totalResolutionSeconds / resolutionCount : 0
134
+ summary.success_rate = summary.with_outcome > 0 ? summary.by_outcome.success / summary.with_outcome : 0
135
+
136
+ for (const agent of Object.values(byAgent)) {
137
+ const withOutcome = agent.total - agent.unknown
138
+ agent.success_rate = withOutcome > 0 ? agent.success / withOutcome : 0
139
+ }
140
+
141
+ for (const priority of Object.values(byPriority)) {
142
+ const withOutcome = priority.total - priority.unknown
143
+ priority.success_rate = withOutcome > 0 ? priority.success / withOutcome : 0
144
+ }
145
+
146
+ const commonErrors = [...errorMap.entries()]
147
+ .sort((a, b) => b[1] - a[1])
148
+ .slice(0, 10)
149
+ .map(([error_message, count]) => ({ error_message, count }))
150
+
151
+ return NextResponse.json({
152
+ timeframe,
153
+ summary,
154
+ by_agent: byAgent,
155
+ by_priority: byPriority,
156
+ common_errors: commonErrors,
157
+ record_count: rows.length,
158
+ })
159
+ } catch (error) {
160
+ logger.error({ err: error }, 'GET /api/tasks/outcomes error')
161
+ return NextResponse.json({ error: 'Failed to fetch task outcomes' }, { status: 500 })
162
+ }
163
+ }
src/app/api/tasks/queue/route.ts ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { getDatabase } from '@/lib/db'
3
+ import { requireRole } from '@/lib/auth'
4
+ import { logger } from '@/lib/logger'
5
+
6
+ type QueueReason = 'continue_current' | 'assigned' | 'at_capacity' | 'no_tasks_available'
7
+
8
+ function safeParseJson<T>(raw: string | null | undefined, fallback: T): T {
9
+ if (!raw) return fallback
10
+ try {
11
+ return JSON.parse(raw) as T
12
+ } catch {
13
+ return fallback
14
+ }
15
+ }
16
+
17
+ function mapTaskRow(task: any) {
18
+ return {
19
+ ...task,
20
+ tags: safeParseJson(task.tags, [] as string[]),
21
+ metadata: safeParseJson(task.metadata, {} as Record<string, unknown>),
22
+ }
23
+ }
24
+
25
+ function priorityRankSql() {
26
+ return `
27
+ CASE priority
28
+ WHEN 'critical' THEN 0
29
+ WHEN 'high' THEN 1
30
+ WHEN 'medium' THEN 2
31
+ WHEN 'low' THEN 3
32
+ ELSE 4
33
+ END
34
+ `
35
+ }
36
+
37
+ /**
38
+ * GET /api/tasks/queue - Poll next task for an agent.
39
+ *
40
+ * Query params:
41
+ * - agent: required agent name (or use x-agent-name header)
42
+ * - max_capacity: optional integer 1..20 (default 1)
43
+ */
44
+ export async function GET(request: NextRequest) {
45
+ const auth = requireRole(request, 'operator')
46
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
47
+
48
+ try {
49
+ const db = getDatabase()
50
+ const workspaceId = auth.user.workspace_id
51
+ const { searchParams } = new URL(request.url)
52
+
53
+ const agent =
54
+ (searchParams.get('agent') || '').trim() ||
55
+ (request.headers.get('x-agent-name') || '').trim()
56
+
57
+ if (!agent) {
58
+ return NextResponse.json({ error: 'Missing agent. Provide ?agent=... or x-agent-name header.' }, { status: 400 })
59
+ }
60
+
61
+ const maxCapacityRaw = searchParams.get('max_capacity') || '1'
62
+ if (!/^\d+$/.test(maxCapacityRaw)) {
63
+ return NextResponse.json({ error: 'Invalid max_capacity. Expected integer 1..20.' }, { status: 400 })
64
+ }
65
+ const maxCapacity = Number(maxCapacityRaw)
66
+ if (!Number.isInteger(maxCapacity) || maxCapacity < 1 || maxCapacity > 20) {
67
+ return NextResponse.json({ error: 'Invalid max_capacity. Expected integer 1..20.' }, { status: 400 })
68
+ }
69
+
70
+ const now = Math.floor(Date.now() / 1000)
71
+
72
+ const currentTask = db.prepare(`
73
+ SELECT *
74
+ FROM tasks
75
+ WHERE workspace_id = ? AND assigned_to = ? AND status = 'in_progress'
76
+ ORDER BY updated_at DESC
77
+ LIMIT 1
78
+ `).get(workspaceId, agent) as any | undefined
79
+
80
+ if (currentTask) {
81
+ return NextResponse.json({
82
+ task: mapTaskRow(currentTask),
83
+ reason: 'continue_current' as QueueReason,
84
+ agent,
85
+ timestamp: now,
86
+ })
87
+ }
88
+
89
+ const inProgressCount = (db.prepare(`
90
+ SELECT COUNT(*) as c
91
+ FROM tasks
92
+ WHERE workspace_id = ? AND assigned_to = ? AND status = 'in_progress'
93
+ `).get(workspaceId, agent) as { c: number }).c
94
+
95
+ if (inProgressCount >= maxCapacity) {
96
+ return NextResponse.json({
97
+ task: null,
98
+ reason: 'at_capacity' as QueueReason,
99
+ agent,
100
+ timestamp: now,
101
+ })
102
+ }
103
+
104
+ // Best-effort atomic pickup loop for race safety.
105
+ for (let attempt = 0; attempt < 5; attempt += 1) {
106
+ const candidate = db.prepare(`
107
+ SELECT *
108
+ FROM tasks
109
+ WHERE workspace_id = ?
110
+ AND status IN ('assigned', 'inbox')
111
+ AND (assigned_to IS NULL OR assigned_to = ?)
112
+ ORDER BY ${priorityRankSql()} ASC, due_date ASC NULLS LAST, created_at ASC
113
+ LIMIT 1
114
+ `).get(workspaceId, agent) as any | undefined
115
+
116
+ if (!candidate) break
117
+
118
+ const claimed = db.prepare(`
119
+ UPDATE tasks
120
+ SET status = 'in_progress', assigned_to = ?, updated_at = ?
121
+ WHERE id = ? AND workspace_id = ?
122
+ AND status IN ('assigned', 'inbox')
123
+ AND (assigned_to IS NULL OR assigned_to = ?)
124
+ `).run(agent, now, candidate.id, workspaceId, agent)
125
+
126
+ if (claimed.changes > 0) {
127
+ const task = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?').get(candidate.id, workspaceId) as any
128
+ return NextResponse.json({
129
+ task: mapTaskRow(task),
130
+ reason: 'assigned' as QueueReason,
131
+ agent,
132
+ timestamp: now,
133
+ })
134
+ }
135
+ }
136
+
137
+ return NextResponse.json({
138
+ task: null,
139
+ reason: 'no_tasks_available' as QueueReason,
140
+ agent,
141
+ timestamp: now,
142
+ })
143
+ } catch (error) {
144
+ logger.error({ err: error }, 'GET /api/tasks/queue error')
145
+ return NextResponse.json({ error: 'Failed to poll task queue' }, { status: 500 })
146
+ }
147
+ }
src/app/api/tasks/route.ts CHANGED
@@ -5,6 +5,45 @@ import { requireRole } from '@/lib/auth';
5
  import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
  import { validateBody, createTaskSchema, bulkUpdateTaskStatusSchema } from '@/lib/validation';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  function hasAegisApproval(db: ReturnType<typeof getDatabase>, taskId: number, workspaceId: number): boolean {
10
  const review = db.prepare(`
@@ -18,7 +57,7 @@ function hasAegisApproval(db: ReturnType<typeof getDatabase>, taskId: number, wo
18
 
19
  /**
20
  * GET /api/tasks - List all tasks with optional filtering
21
- * Query params: status, assigned_to, priority, limit, offset
22
  */
23
  export async function GET(request: NextRequest) {
24
  const auth = requireRole(request, 'viewer');
@@ -33,40 +72,48 @@ export async function GET(request: NextRequest) {
33
  const status = searchParams.get('status');
34
  const assigned_to = searchParams.get('assigned_to');
35
  const priority = searchParams.get('priority');
 
36
  const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200);
37
  const offset = parseInt(searchParams.get('offset') || '0');
38
 
39
  // Build dynamic query
40
- let query = 'SELECT * FROM tasks WHERE workspace_id = ?';
 
 
 
 
 
 
41
  const params: any[] = [workspaceId];
42
 
43
  if (status) {
44
- query += ' AND status = ?';
45
  params.push(status);
46
  }
47
 
48
  if (assigned_to) {
49
- query += ' AND assigned_to = ?';
50
  params.push(assigned_to);
51
  }
52
 
53
  if (priority) {
54
- query += ' AND priority = ?';
55
  params.push(priority);
56
  }
 
 
 
 
 
57
 
58
- query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
59
  params.push(limit, offset);
60
 
61
  const stmt = db.prepare(query);
62
  const tasks = stmt.all(...params) as Task[];
63
 
64
  // Parse JSON fields
65
- const tasksWithParsedData = tasks.map(task => ({
66
- ...task,
67
- tags: task.tags ? JSON.parse(task.tags) : [],
68
- metadata: task.metadata ? JSON.parse(task.metadata) : {}
69
- }));
70
 
71
  // Get total count for pagination
72
  let countQuery = 'SELECT COUNT(*) as total FROM tasks WHERE workspace_id = ?';
@@ -83,6 +130,10 @@ export async function GET(request: NextRequest) {
83
  countQuery += ' AND priority = ?';
84
  countParams.push(priority);
85
  }
 
 
 
 
86
  const countRow = db.prepare(countQuery).get(...countParams) as { total: number };
87
 
88
  return NextResponse.json({ tasks: tasksWithParsedData, total: countRow.total, page: Math.floor(offset / limit) + 1, limit });
@@ -113,15 +164,25 @@ export async function POST(request: NextRequest) {
113
  const {
114
  title,
115
  description,
116
- status = 'inbox',
117
  priority = 'medium',
 
118
  assigned_to,
119
  created_by = user?.username || 'system',
120
  due_date,
121
  estimated_hours,
 
 
 
 
 
 
 
 
122
  tags = [],
123
  metadata = {}
124
  } = body;
 
125
 
126
  // Check for duplicate title
127
  const existingTask = db.prepare('SELECT id FROM tasks WHERE title = ? AND workspace_id = ?').get(title, workspaceId);
@@ -130,44 +191,95 @@ export async function POST(request: NextRequest) {
130
  }
131
 
132
  const now = Math.floor(Date.now() / 1000);
133
-
134
- const stmt = db.prepare(`
135
- INSERT INTO tasks (
136
- title, description, status, priority, assigned_to, created_by,
137
- created_at, updated_at, due_date, estimated_hours, tags, metadata, workspace_id
138
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
139
- `);
140
-
141
- const dbResult = stmt.run(
142
- title,
143
- description,
144
- status,
145
- priority,
146
- assigned_to,
147
- created_by,
148
- now,
149
- now,
150
- due_date,
151
- estimated_hours,
152
- JSON.stringify(tags),
153
- JSON.stringify(metadata),
154
- workspaceId
155
- );
156
 
157
- const taskId = dbResult.lastInsertRowid as number;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
  // Log activity
160
  db_helpers.logActivity('task_created', 'task', taskId, created_by, `Created task: ${title}`, {
161
  title,
162
- status,
163
  priority,
164
- assigned_to
 
165
  }, workspaceId);
166
 
167
  if (created_by) {
168
  db_helpers.ensureTaskSubscription(taskId, created_by, workspaceId)
169
  }
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  // Create notification if assigned
172
  if (assigned_to) {
173
  db_helpers.ensureTaskSubscription(taskId, assigned_to, workspaceId)
@@ -183,12 +295,14 @@ export async function POST(request: NextRequest) {
183
  }
184
 
185
  // Fetch the created task
186
- const createdTask = db.prepare('SELECT * FROM tasks WHERE id = ? AND workspace_id = ?').get(taskId, workspaceId) as Task;
187
- const parsedTask = {
188
- ...createdTask,
189
- tags: JSON.parse(createdTask.tags || '[]'),
190
- metadata: JSON.parse(createdTask.metadata || '{}')
191
- };
 
 
192
 
193
  // Broadcast to SSE clients
194
  eventBus.broadcast('task.created', parsedTask);
@@ -224,6 +338,11 @@ export async function PUT(request: NextRequest) {
224
  SET status = ?, updated_at = ?
225
  WHERE id = ? AND workspace_id = ?
226
  `);
 
 
 
 
 
227
 
228
  const actor = auth.user.username
229
 
@@ -236,7 +355,11 @@ export async function PUT(request: NextRequest) {
236
  throw new Error(`Aegis approval required for task ${task.id}`)
237
  }
238
 
239
- updateStmt.run(task.status, now, task.id, workspaceId);
 
 
 
 
240
 
241
  // Log status change if different
242
  if (oldTask && oldTask.status !== task.status) {
 
5
  import { mutationLimiter } from '@/lib/rate-limit';
6
  import { logger } from '@/lib/logger';
7
  import { validateBody, createTaskSchema, bulkUpdateTaskStatusSchema } from '@/lib/validation';
8
+ import { resolveMentionRecipients } from '@/lib/mentions';
9
+ import { normalizeTaskCreateStatus } from '@/lib/task-status';
10
+
11
+ function formatTicketRef(prefix?: string | null, num?: number | null): string | undefined {
12
+ if (!prefix || typeof num !== 'number' || !Number.isFinite(num) || num <= 0) return undefined
13
+ return `${prefix}-${String(num).padStart(3, '0')}`
14
+ }
15
+
16
+ function mapTaskRow(task: any): Task & { tags: string[]; metadata: Record<string, unknown> } {
17
+ return {
18
+ ...task,
19
+ tags: task.tags ? JSON.parse(task.tags) : [],
20
+ metadata: task.metadata ? JSON.parse(task.metadata) : {},
21
+ ticket_ref: formatTicketRef(task.project_prefix, task.project_ticket_no),
22
+ }
23
+ }
24
+
25
+ function resolveProjectId(db: ReturnType<typeof getDatabase>, workspaceId: number, requestedProjectId?: number): number {
26
+ if (typeof requestedProjectId === 'number' && Number.isFinite(requestedProjectId)) {
27
+ const project = db.prepare(`
28
+ SELECT id FROM projects
29
+ WHERE id = ? AND workspace_id = ? AND status = 'active'
30
+ LIMIT 1
31
+ `).get(requestedProjectId, workspaceId) as { id: number } | undefined
32
+ if (project) return project.id
33
+ }
34
+
35
+ const fallback = db.prepare(`
36
+ SELECT id FROM projects
37
+ WHERE workspace_id = ? AND status = 'active'
38
+ ORDER BY CASE WHEN slug = 'general' THEN 0 ELSE 1 END, id ASC
39
+ LIMIT 1
40
+ `).get(workspaceId) as { id: number } | undefined
41
+
42
+ if (!fallback) {
43
+ throw new Error('No active project available in workspace')
44
+ }
45
+ return fallback.id
46
+ }
47
 
48
  function hasAegisApproval(db: ReturnType<typeof getDatabase>, taskId: number, workspaceId: number): boolean {
49
  const review = db.prepare(`
 
57
 
58
  /**
59
  * GET /api/tasks - List all tasks with optional filtering
60
+ * Query params: status, assigned_to, priority, project_id, limit, offset
61
  */
62
  export async function GET(request: NextRequest) {
63
  const auth = requireRole(request, 'viewer');
 
72
  const status = searchParams.get('status');
73
  const assigned_to = searchParams.get('assigned_to');
74
  const priority = searchParams.get('priority');
75
+ const projectIdParam = Number.parseInt(searchParams.get('project_id') || '', 10);
76
  const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200);
77
  const offset = parseInt(searchParams.get('offset') || '0');
78
 
79
  // Build dynamic query
80
+ let query = `
81
+ SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix
82
+ FROM tasks t
83
+ LEFT JOIN projects p
84
+ ON p.id = t.project_id AND p.workspace_id = t.workspace_id
85
+ WHERE t.workspace_id = ?
86
+ `;
87
  const params: any[] = [workspaceId];
88
 
89
  if (status) {
90
+ query += ' AND t.status = ?';
91
  params.push(status);
92
  }
93
 
94
  if (assigned_to) {
95
+ query += ' AND t.assigned_to = ?';
96
  params.push(assigned_to);
97
  }
98
 
99
  if (priority) {
100
+ query += ' AND t.priority = ?';
101
  params.push(priority);
102
  }
103
+
104
+ if (Number.isFinite(projectIdParam)) {
105
+ query += ' AND t.project_id = ?';
106
+ params.push(projectIdParam);
107
+ }
108
 
109
+ query += ' ORDER BY t.created_at DESC LIMIT ? OFFSET ?';
110
  params.push(limit, offset);
111
 
112
  const stmt = db.prepare(query);
113
  const tasks = stmt.all(...params) as Task[];
114
 
115
  // Parse JSON fields
116
+ const tasksWithParsedData = tasks.map(mapTaskRow);
 
 
 
 
117
 
118
  // Get total count for pagination
119
  let countQuery = 'SELECT COUNT(*) as total FROM tasks WHERE workspace_id = ?';
 
130
  countQuery += ' AND priority = ?';
131
  countParams.push(priority);
132
  }
133
+ if (Number.isFinite(projectIdParam)) {
134
+ countQuery += ' AND project_id = ?';
135
+ countParams.push(projectIdParam);
136
+ }
137
  const countRow = db.prepare(countQuery).get(...countParams) as { total: number };
138
 
139
  return NextResponse.json({ tasks: tasksWithParsedData, total: countRow.total, page: Math.floor(offset / limit) + 1, limit });
 
164
  const {
165
  title,
166
  description,
167
+ status,
168
  priority = 'medium',
169
+ project_id,
170
  assigned_to,
171
  created_by = user?.username || 'system',
172
  due_date,
173
  estimated_hours,
174
+ actual_hours,
175
+ outcome,
176
+ error_message,
177
+ resolution,
178
+ feedback_rating,
179
+ feedback_notes,
180
+ retry_count = 0,
181
+ completed_at,
182
  tags = [],
183
  metadata = {}
184
  } = body;
185
+ const normalizedStatus = normalizeTaskCreateStatus(status, assigned_to)
186
 
187
  // Check for duplicate title
188
  const existingTask = db.prepare('SELECT id FROM tasks WHERE title = ? AND workspace_id = ?').get(title, workspaceId);
 
191
  }
192
 
193
  const now = Math.floor(Date.now() / 1000);
194
+ const mentionResolution = resolveMentionRecipients(description || '', db, workspaceId);
195
+ if (mentionResolution.unresolved.length > 0) {
196
+ return NextResponse.json({
197
+ error: `Unknown mentions: ${mentionResolution.unresolved.map((m) => `@${m}`).join(', ')}`,
198
+ missing_mentions: mentionResolution.unresolved
199
+ }, { status: 400 });
200
+ }
201
+
202
+ const resolvedCompletedAt = completed_at ?? (normalizedStatus === 'done' ? now : null)
203
+
204
+ const createTaskTx = db.transaction(() => {
205
+ const resolvedProjectId = resolveProjectId(db, workspaceId, project_id)
206
+ db.prepare(`
207
+ UPDATE projects
208
+ SET ticket_counter = ticket_counter + 1, updated_at = unixepoch()
209
+ WHERE id = ? AND workspace_id = ?
210
+ `).run(resolvedProjectId, workspaceId)
211
+ const row = db.prepare(`
212
+ SELECT ticket_counter FROM projects
213
+ WHERE id = ? AND workspace_id = ?
214
+ `).get(resolvedProjectId, workspaceId) as { ticket_counter: number } | undefined
215
+ if (!row || !row.ticket_counter) throw new Error('Failed to allocate project ticket number')
 
216
 
217
+ const insertStmt = db.prepare(`
218
+ INSERT INTO tasks (
219
+ title, description, status, priority, project_id, project_ticket_no, assigned_to, created_by,
220
+ created_at, updated_at, due_date, estimated_hours, actual_hours,
221
+ outcome, error_message, resolution, feedback_rating, feedback_notes, retry_count, completed_at,
222
+ tags, metadata, workspace_id
223
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
224
+ `)
225
+
226
+ const dbResult = insertStmt.run(
227
+ title,
228
+ description,
229
+ normalizedStatus,
230
+ priority,
231
+ resolvedProjectId,
232
+ row.ticket_counter,
233
+ assigned_to,
234
+ created_by,
235
+ now,
236
+ now,
237
+ due_date,
238
+ estimated_hours,
239
+ actual_hours,
240
+ outcome,
241
+ error_message,
242
+ resolution,
243
+ feedback_rating,
244
+ feedback_notes,
245
+ retry_count,
246
+ resolvedCompletedAt,
247
+ JSON.stringify(tags),
248
+ JSON.stringify(metadata),
249
+ workspaceId
250
+ )
251
+ return Number(dbResult.lastInsertRowid)
252
+ })
253
+
254
+ const taskId = createTaskTx()
255
 
256
  // Log activity
257
  db_helpers.logActivity('task_created', 'task', taskId, created_by, `Created task: ${title}`, {
258
  title,
259
+ status: normalizedStatus,
260
  priority,
261
+ assigned_to,
262
+ ...(outcome ? { outcome } : {})
263
  }, workspaceId);
264
 
265
  if (created_by) {
266
  db_helpers.ensureTaskSubscription(taskId, created_by, workspaceId)
267
  }
268
 
269
+ for (const recipient of mentionResolution.recipients) {
270
+ db_helpers.ensureTaskSubscription(taskId, recipient, workspaceId);
271
+ if (recipient === created_by) continue;
272
+ db_helpers.createNotification(
273
+ recipient,
274
+ 'mention',
275
+ 'You were mentioned in a task description',
276
+ `${created_by} mentioned you in task "${title}"`,
277
+ 'task',
278
+ taskId,
279
+ workspaceId
280
+ );
281
+ }
282
+
283
  // Create notification if assigned
284
  if (assigned_to) {
285
  db_helpers.ensureTaskSubscription(taskId, assigned_to, workspaceId)
 
295
  }
296
 
297
  // Fetch the created task
298
+ const createdTask = db.prepare(`
299
+ SELECT t.*, p.name as project_name, p.ticket_prefix as project_prefix
300
+ FROM tasks t
301
+ LEFT JOIN projects p
302
+ ON p.id = t.project_id AND p.workspace_id = t.workspace_id
303
+ WHERE t.id = ? AND t.workspace_id = ?
304
+ `).get(taskId, workspaceId) as Task;
305
+ const parsedTask = mapTaskRow(createdTask);
306
 
307
  // Broadcast to SSE clients
308
  eventBus.broadcast('task.created', parsedTask);
 
338
  SET status = ?, updated_at = ?
339
  WHERE id = ? AND workspace_id = ?
340
  `);
341
+ const updateDoneStmt = db.prepare(`
342
+ UPDATE tasks
343
+ SET status = ?, updated_at = ?, completed_at = COALESCE(completed_at, ?)
344
+ WHERE id = ? AND workspace_id = ?
345
+ `);
346
 
347
  const actor = auth.user.username
348
 
 
355
  throw new Error(`Aegis approval required for task ${task.id}`)
356
  }
357
 
358
+ if (task.status === 'done') {
359
+ updateDoneStmt.run(task.status, now, now, task.id, workspaceId);
360
+ } else {
361
+ updateStmt.run(task.status, now, task.id, workspaceId);
362
+ }
363
 
364
  // Log status change if different
365
  if (oldTask && oldTask.status !== task.status) {
src/app/api/tokens/route.ts CHANGED
@@ -6,6 +6,9 @@ import { requireRole } from '@/lib/auth'
6
  import { getAllGatewaySessions } from '@/lib/sessions'
7
  import { logger } from '@/lib/logger'
8
  import { getDatabase } from '@/lib/db'
 
 
 
9
 
10
  const DATA_PATH = config.tokensPath
11
 
@@ -20,6 +23,8 @@ interface TokenUsageRecord {
20
  totalTokens: number
21
  cost: number
22
  operation: string
 
 
23
  duration?: number
24
  }
25
 
@@ -38,22 +43,7 @@ interface ExportData {
38
  sessions: Record<string, TokenStats>
39
  }
40
 
41
- // Model pricing (cost per 1K tokens)
42
- const MODEL_PRICING: Record<string, number> = {
43
- 'anthropic/claude-3-5-haiku-latest': 0.25,
44
- 'claude-3-5-haiku': 0.25,
45
- 'anthropic/claude-sonnet-4-20250514': 3.0,
46
- 'claude-sonnet-4': 3.0,
47
- 'anthropic/claude-opus-4-5': 15.0,
48
- 'claude-opus-4-5': 15.0,
49
- 'groq/llama-3.1-8b-instant': 0.05,
50
- 'groq/llama-3.3-70b-versatile': 0.59,
51
- 'moonshot/kimi-k2.5': 1.0,
52
- 'minimax/minimax-m2.1': 0.3,
53
- 'ollama/deepseek-r1:14b': 0.0,
54
- 'ollama/qwen2.5-coder:7b': 0.0,
55
- 'ollama/qwen2.5-coder:14b': 0.0,
56
- }
57
 
58
  function extractAgentName(sessionId: string): string {
59
  const trimmed = sessionId.trim()
@@ -62,36 +52,30 @@ function extractAgentName(sessionId: string): string {
62
  return agent?.trim() || 'unknown'
63
  }
64
 
65
- function getModelCost(modelName: string): number {
66
- if (MODEL_PRICING[modelName] !== undefined) return MODEL_PRICING[modelName]
67
- for (const [model, cost] of Object.entries(MODEL_PRICING)) {
68
- if (modelName.includes(model.split('/').pop() || '')) return cost
69
- }
70
- return 1.0
71
- }
72
-
73
  interface DbTokenUsageRow {
74
  id: number
75
  model: string
76
  session_id: string
77
  input_tokens: number
78
  output_tokens: number
 
 
79
  created_at: number
80
  }
81
 
82
- function loadTokenDataFromDb(): TokenUsageRecord[] {
83
  try {
84
  const db = getDatabase()
85
  const rows = db.prepare(`
86
- SELECT id, model, session_id, input_tokens, output_tokens, created_at
87
  FROM token_usage
 
88
  ORDER BY created_at DESC, id DESC
89
  LIMIT 10000
90
- `).all() as DbTokenUsageRow[]
91
 
92
  return rows.map((row) => {
93
  const totalTokens = row.input_tokens + row.output_tokens
94
- const costPer1k = getModelCost(row.model)
95
  return {
96
  id: `db-${row.id}`,
97
  model: row.model,
@@ -101,8 +85,10 @@ function loadTokenDataFromDb(): TokenUsageRecord[] {
101
  inputTokens: row.input_tokens,
102
  outputTokens: row.output_tokens,
103
  totalTokens,
104
- cost: (totalTokens / 1000) * costPer1k,
105
  operation: 'heartbeat',
 
 
106
  }
107
  })
108
  } catch (error) {
@@ -111,7 +97,10 @@ function loadTokenDataFromDb(): TokenUsageRecord[] {
111
  }
112
  }
113
 
114
- function normalizeTokenRecord(record: Partial<TokenUsageRecord>): TokenUsageRecord | null {
 
 
 
115
  if (!record.model || !record.sessionId) return null
116
  const inputTokens = Number(record.inputTokens ?? 0)
117
  const outputTokens = Number(record.outputTokens ?? 0)
@@ -126,8 +115,10 @@ function normalizeTokenRecord(record: Partial<TokenUsageRecord>): TokenUsageReco
126
  inputTokens,
127
  outputTokens,
128
  totalTokens,
129
- cost: Number(record.cost ?? (totalTokens / 1000) * getModelCost(model)),
130
  operation: String(record.operation ?? 'chat_completion'),
 
 
131
  duration: record.duration,
132
  }
133
  }
@@ -145,6 +136,8 @@ function dedupeTokenRecords(records: TokenUsageRecord[]): TokenUsageRecord[] {
145
  record.outputTokens,
146
  record.totalTokens,
147
  record.operation,
 
 
148
  record.duration ?? '',
149
  ].join('|')
150
  if (seen.has(key)) continue
@@ -155,7 +148,7 @@ function dedupeTokenRecords(records: TokenUsageRecord[]): TokenUsageRecord[] {
155
  return deduped
156
  }
157
 
158
- async function loadTokenDataFromFile(): Promise<TokenUsageRecord[]> {
159
  try {
160
  ensureDirExists(dirname(DATA_PATH))
161
  await access(DATA_PATH)
@@ -164,8 +157,13 @@ async function loadTokenDataFromFile(): Promise<TokenUsageRecord[]> {
164
  if (!Array.isArray(parsed)) return []
165
 
166
  return parsed
167
- .map((record: Partial<TokenUsageRecord>) => normalizeTokenRecord(record))
168
  .filter((record): record is TokenUsageRecord => record !== null)
 
 
 
 
 
169
  } catch {
170
  return []
171
  }
@@ -174,34 +172,33 @@ async function loadTokenDataFromFile(): Promise<TokenUsageRecord[]> {
174
  /**
175
  * Load token data from persistent file, falling back to deriving from session stores.
176
  */
177
- async function loadTokenData(): Promise<TokenUsageRecord[]> {
178
- const dbRecords = loadTokenDataFromDb()
179
- const fileRecords = await loadTokenDataFromFile()
 
180
  const combined = dedupeTokenRecords([...dbRecords, ...fileRecords]).sort((a, b) => b.timestamp - a.timestamp)
181
  if (combined.length > 0) {
182
  return combined
183
  }
184
 
185
  // Final fallback: derive from in-memory sessions
186
- return deriveFromSessions()
187
  }
188
 
189
  /**
190
  * Derive token usage records from OpenClaw session stores.
191
  * Each session has totalTokens, inputTokens, outputTokens, model, etc.
192
  */
193
- function deriveFromSessions(): TokenUsageRecord[] {
194
  const sessions = getAllGatewaySessions(Infinity) // Get ALL sessions regardless of age
195
  const records: TokenUsageRecord[] = []
196
 
197
  for (const session of sessions) {
198
- if (!session.totalTokens && !session.model) continue // Skip empty sessions
199
-
200
- const totalTokens = session.totalTokens || 0
201
- const inputTokens = session.inputTokens || Math.round(totalTokens * 0.7)
202
- const outputTokens = session.outputTokens || totalTokens - inputTokens
203
- const costPer1k = getModelCost(session.model || '')
204
- const cost = (totalTokens / 1000) * costPer1k
205
 
206
  records.push({
207
  id: `session-${session.agent}-${session.key}`,
@@ -214,6 +211,8 @@ function deriveFromSessions(): TokenUsageRecord[] {
214
  totalTokens,
215
  cost,
216
  operation: session.chatType || 'chat',
 
 
217
  })
218
  }
219
 
@@ -275,17 +274,48 @@ function filterByTimeframe(records: TokenUsageRecord[], timeframe: string): Toke
275
  return records.filter(record => record.timestamp >= cutoffTime)
276
  }
277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  export async function GET(request: NextRequest) {
279
  const auth = requireRole(request, 'viewer')
280
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
281
 
282
  try {
283
  const { searchParams } = new URL(request.url)
284
- const action = searchParams.get('action') || 'list'
285
  const timeframe = searchParams.get('timeframe') || 'all'
286
  const format = searchParams.get('format') || 'json'
287
 
288
- const tokenData = await loadTokenData()
 
289
  const filteredData = filterByTimeframe(tokenData, timeframe)
290
 
291
  if (action === 'list') {
@@ -399,6 +429,34 @@ export async function GET(request: NextRequest) {
399
  })
400
  }
401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  if (action === 'export') {
403
  const overallStats = calculateStats(filteredData)
404
  const modelStats: Record<string, TokenStats> = {}
@@ -490,7 +548,7 @@ export async function GET(request: NextRequest) {
490
  return NextResponse.json({ trends, timeframe })
491
  }
492
 
493
- return NextResponse.json({ error: 'Invalid action' }, { status: 400 })
494
  } catch (error) {
495
  logger.error({ err: error }, 'Tokens API error')
496
  return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
@@ -503,15 +561,29 @@ export async function POST(request: NextRequest) {
503
 
504
  try {
505
  const body = await request.json()
506
- const { model, sessionId, inputTokens, outputTokens, operation = 'chat_completion', duration } = body
 
507
 
508
  if (!model || !sessionId || typeof inputTokens !== 'number' || typeof outputTokens !== 'number') {
509
  return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
510
  }
511
 
512
  const totalTokens = inputTokens + outputTokens
513
- const costPer1k = getModelCost(model)
514
- const cost = (totalTokens / 1000) * costPer1k
 
 
 
 
 
 
 
 
 
 
 
 
 
515
 
516
  const record: TokenUsageRecord = {
517
  id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
@@ -524,11 +596,13 @@ export async function POST(request: NextRequest) {
524
  totalTokens,
525
  cost,
526
  operation,
 
 
527
  duration,
528
  }
529
 
530
  // Persist only manually posted usage records in the JSON file.
531
- const existingData = await loadTokenDataFromFile()
532
  existingData.unshift(record)
533
 
534
  if (existingData.length > 10000) {
 
6
  import { getAllGatewaySessions } from '@/lib/sessions'
7
  import { logger } from '@/lib/logger'
8
  import { getDatabase } from '@/lib/db'
9
+ import { calculateTokenCost } from '@/lib/token-pricing'
10
+ import { getProviderSubscriptionFlags } from '@/lib/provider-subscriptions'
11
+ import { buildTaskCostReport, type TaskCostMetadata } from '@/lib/task-costs'
12
 
13
  const DATA_PATH = config.tokensPath
14
 
 
23
  totalTokens: number
24
  cost: number
25
  operation: string
26
+ taskId?: number | null
27
+ workspaceId?: number
28
  duration?: number
29
  }
30
 
 
43
  sessions: Record<string, TokenStats>
44
  }
45
 
46
+ interface TaskMetadataRow extends TaskCostMetadata {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  function extractAgentName(sessionId: string): string {
49
  const trimmed = sessionId.trim()
 
52
  return agent?.trim() || 'unknown'
53
  }
54
 
 
 
 
 
 
 
 
 
55
  interface DbTokenUsageRow {
56
  id: number
57
  model: string
58
  session_id: string
59
  input_tokens: number
60
  output_tokens: number
61
+ task_id?: number | null
62
+ workspace_id?: number
63
  created_at: number
64
  }
65
 
66
+ function loadTokenDataFromDb(workspaceId: number, providerSubscriptions: Record<string, boolean>): TokenUsageRecord[] {
67
  try {
68
  const db = getDatabase()
69
  const rows = db.prepare(`
70
+ SELECT id, model, session_id, input_tokens, output_tokens, task_id, workspace_id, created_at
71
  FROM token_usage
72
+ WHERE workspace_id = ?
73
  ORDER BY created_at DESC, id DESC
74
  LIMIT 10000
75
+ `).all(workspaceId) as DbTokenUsageRow[]
76
 
77
  return rows.map((row) => {
78
  const totalTokens = row.input_tokens + row.output_tokens
 
79
  return {
80
  id: `db-${row.id}`,
81
  model: row.model,
 
85
  inputTokens: row.input_tokens,
86
  outputTokens: row.output_tokens,
87
  totalTokens,
88
+ cost: calculateTokenCost(row.model, row.input_tokens, row.output_tokens, { providerSubscriptions }),
89
  operation: 'heartbeat',
90
+ taskId: row.task_id ?? null,
91
+ workspaceId: row.workspace_id ?? workspaceId,
92
  }
93
  })
94
  } catch (error) {
 
97
  }
98
  }
99
 
100
+ function normalizeTokenRecord(
101
+ record: Partial<TokenUsageRecord>,
102
+ providerSubscriptions: Record<string, boolean>,
103
+ ): TokenUsageRecord | null {
104
  if (!record.model || !record.sessionId) return null
105
  const inputTokens = Number(record.inputTokens ?? 0)
106
  const outputTokens = Number(record.outputTokens ?? 0)
 
115
  inputTokens,
116
  outputTokens,
117
  totalTokens,
118
+ cost: Number(record.cost ?? calculateTokenCost(model, inputTokens, outputTokens, { providerSubscriptions })),
119
  operation: String(record.operation ?? 'chat_completion'),
120
+ taskId: record.taskId != null && Number.isFinite(Number(record.taskId)) ? Number(record.taskId) : null,
121
+ workspaceId: record.workspaceId != null && Number.isFinite(Number(record.workspaceId)) ? Number(record.workspaceId) : 1,
122
  duration: record.duration,
123
  }
124
  }
 
136
  record.outputTokens,
137
  record.totalTokens,
138
  record.operation,
139
+ record.taskId ?? '',
140
+ record.workspaceId ?? 1,
141
  record.duration ?? '',
142
  ].join('|')
143
  if (seen.has(key)) continue
 
148
  return deduped
149
  }
150
 
151
+ async function loadTokenDataFromFile(workspaceId: number, providerSubscriptions: Record<string, boolean>): Promise<TokenUsageRecord[]> {
152
  try {
153
  ensureDirExists(dirname(DATA_PATH))
154
  await access(DATA_PATH)
 
157
  if (!Array.isArray(parsed)) return []
158
 
159
  return parsed
160
+ .map((record: Partial<TokenUsageRecord>) => normalizeTokenRecord(record, providerSubscriptions))
161
  .filter((record): record is TokenUsageRecord => record !== null)
162
+ .filter((record) => {
163
+ if (record.workspaceId === workspaceId) return true
164
+ // Backward compatibility for pre-workspace records
165
+ return workspaceId === 1 && (!record.workspaceId || record.workspaceId === 1)
166
+ })
167
  } catch {
168
  return []
169
  }
 
172
  /**
173
  * Load token data from persistent file, falling back to deriving from session stores.
174
  */
175
+ async function loadTokenData(workspaceId: number): Promise<TokenUsageRecord[]> {
176
+ const providerSubscriptions = getProviderSubscriptionFlags()
177
+ const dbRecords = loadTokenDataFromDb(workspaceId, providerSubscriptions)
178
+ const fileRecords = await loadTokenDataFromFile(workspaceId, providerSubscriptions)
179
  const combined = dedupeTokenRecords([...dbRecords, ...fileRecords]).sort((a, b) => b.timestamp - a.timestamp)
180
  if (combined.length > 0) {
181
  return combined
182
  }
183
 
184
  // Final fallback: derive from in-memory sessions
185
+ return deriveFromSessions(workspaceId, providerSubscriptions)
186
  }
187
 
188
  /**
189
  * Derive token usage records from OpenClaw session stores.
190
  * Each session has totalTokens, inputTokens, outputTokens, model, etc.
191
  */
192
+ function deriveFromSessions(workspaceId: number, providerSubscriptions: Record<string, boolean>): TokenUsageRecord[] {
193
  const sessions = getAllGatewaySessions(Infinity) // Get ALL sessions regardless of age
194
  const records: TokenUsageRecord[] = []
195
 
196
  for (const session of sessions) {
197
+ const inputTokens = session.inputTokens || 0
198
+ const outputTokens = session.outputTokens || 0
199
+ const totalTokens = inputTokens + outputTokens
200
+ if (totalTokens <= 0 && !session.model) continue // Skip empty sessions
201
+ const cost = calculateTokenCost(session.model || '', inputTokens, outputTokens, { providerSubscriptions })
 
 
202
 
203
  records.push({
204
  id: `session-${session.agent}-${session.key}`,
 
211
  totalTokens,
212
  cost,
213
  operation: session.chatType || 'chat',
214
+ taskId: null,
215
+ workspaceId,
216
  })
217
  }
218
 
 
274
  return records.filter(record => record.timestamp >= cutoffTime)
275
  }
276
 
277
+ function loadTaskMetadataById(workspaceId: number, taskIds: number[]): Record<number, TaskCostMetadata> {
278
+ if (taskIds.length === 0) return {}
279
+ const db = getDatabase()
280
+ const placeholders = taskIds.map(() => '?').join(', ')
281
+ const rows = db.prepare(`
282
+ SELECT
283
+ t.id,
284
+ t.title,
285
+ t.status,
286
+ t.priority,
287
+ t.assigned_to,
288
+ t.project_id,
289
+ p.name as project_name,
290
+ p.slug as project_slug,
291
+ p.ticket_prefix as project_prefix,
292
+ t.project_ticket_no
293
+ FROM tasks t
294
+ LEFT JOIN projects p
295
+ ON p.id = t.project_id AND p.workspace_id = t.workspace_id
296
+ WHERE t.workspace_id = ?
297
+ AND t.id IN (${placeholders})
298
+ `).all(workspaceId, ...taskIds) as TaskMetadataRow[]
299
+
300
+ const out: Record<number, TaskCostMetadata> = {}
301
+ for (const row of rows) {
302
+ out[row.id] = row
303
+ }
304
+ return out
305
+ }
306
+
307
  export async function GET(request: NextRequest) {
308
  const auth = requireRole(request, 'viewer')
309
  if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
310
 
311
  try {
312
  const { searchParams } = new URL(request.url)
313
+ const action = (searchParams.get('action') || 'list').trim().toLowerCase()
314
  const timeframe = searchParams.get('timeframe') || 'all'
315
  const format = searchParams.get('format') || 'json'
316
 
317
+ const workspaceId = auth.user.workspace_id ?? 1
318
+ const tokenData = await loadTokenData(workspaceId)
319
  const filteredData = filterByTimeframe(tokenData, timeframe)
320
 
321
  if (action === 'list') {
 
429
  })
430
  }
431
 
432
+ if (action === 'task-costs' || action === 'task_costs' || action === 'taskcosts') {
433
+ const attributedTaskIds = [...new Set(
434
+ filteredData
435
+ .map((record) => record.taskId)
436
+ .filter((taskId): taskId is number => Number.isFinite(taskId) && Number(taskId) > 0)
437
+ .map((taskId) => Number(taskId))
438
+ )]
439
+ const taskMetadataById = loadTaskMetadataById(workspaceId, attributedTaskIds)
440
+ const report = buildTaskCostReport(
441
+ filteredData.map((record) => ({
442
+ model: record.model,
443
+ agentName: record.agentName || extractAgentName(record.sessionId),
444
+ timestamp: record.timestamp,
445
+ totalTokens: record.totalTokens,
446
+ cost: record.cost,
447
+ taskId: record.taskId ?? null,
448
+ })),
449
+ taskMetadataById
450
+ )
451
+
452
+ return NextResponse.json({
453
+ ...report,
454
+ timeframe,
455
+ recordCount: filteredData.length,
456
+ attributedRecordCount: filteredData.filter((record) => Number.isFinite(record.taskId)).length,
457
+ })
458
+ }
459
+
460
  if (action === 'export') {
461
  const overallStats = calculateStats(filteredData)
462
  const modelStats: Record<string, TokenStats> = {}
 
548
  return NextResponse.json({ trends, timeframe })
549
  }
550
 
551
+ return NextResponse.json({ error: 'Invalid action', action }, { status: 400 })
552
  } catch (error) {
553
  logger.error({ err: error }, 'Tokens API error')
554
  return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
 
561
 
562
  try {
563
  const body = await request.json()
564
+ const workspaceId = auth.user.workspace_id ?? 1
565
+ const { model, sessionId, inputTokens, outputTokens, operation = 'chat_completion', duration, taskId } = body
566
 
567
  if (!model || !sessionId || typeof inputTokens !== 'number' || typeof outputTokens !== 'number') {
568
  return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
569
  }
570
 
571
  const totalTokens = inputTokens + outputTokens
572
+ const providerSubscriptions = getProviderSubscriptionFlags()
573
+ const cost = calculateTokenCost(model, inputTokens, outputTokens, { providerSubscriptions })
574
+ const parsedTaskId =
575
+ taskId != null && Number.isFinite(Number(taskId)) && Number(taskId) > 0
576
+ ? Number(taskId)
577
+ : null
578
+
579
+ let validatedTaskId: number | null = null
580
+ if (parsedTaskId) {
581
+ const db = getDatabase()
582
+ const taskRow = db.prepare(
583
+ 'SELECT id FROM tasks WHERE id = ? AND workspace_id = ?'
584
+ ).get(parsedTaskId, workspaceId) as { id?: number } | undefined
585
+ if (taskRow?.id) validatedTaskId = taskRow.id
586
+ }
587
 
588
  const record: TokenUsageRecord = {
589
  id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
 
596
  totalTokens,
597
  cost,
598
  operation,
599
+ taskId: validatedTaskId,
600
+ workspaceId,
601
  duration,
602
  }
603
 
604
  // Persist only manually posted usage records in the JSON file.
605
+ const existingData = await loadTokenDataFromFile(workspaceId, providerSubscriptions)
606
  existingData.unshift(record)
607
 
608
  if (existingData.length > 10000) {
src/app/api/workload/route.ts ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ import { getDatabase } from '@/lib/db';
3
+ import { requireRole } from '@/lib/auth';
4
+ import { logger } from '@/lib/logger';
5
+
6
+ /**
7
+ * GET /api/workload - Real-Time Workload Signals
8
+ *
9
+ * Provides system-wide capacity metrics and throttle recommendations
10
+ * so agents can make informed decisions about work submission.
11
+ *
12
+ * Response:
13
+ * capacity - Current system capacity metrics
14
+ * queue - Task queue depth and breakdown
15
+ * agents - Agent availability and load distribution
16
+ * recommendation - Actionable signal: normal | throttle | shed | pause
17
+ * thresholds - Current threshold configuration
18
+ *
19
+ * Agents should call this before submitting new work to avoid
20
+ * cascading failures and SLO breaches.
21
+ */
22
+ export async function GET(request: NextRequest) {
23
+ const auth = requireRole(request, 'viewer');
24
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status });
25
+
26
+ try {
27
+ const db = getDatabase();
28
+ const workspaceId = auth.user.workspace_id ?? 1;
29
+ const now = Math.floor(Date.now() / 1000);
30
+
31
+ // --- Capacity metrics ---
32
+ const capacity = buildCapacityMetrics(db, workspaceId, now);
33
+
34
+ // --- Queue depth ---
35
+ const queue = buildQueueMetrics(db, workspaceId);
36
+
37
+ // --- Agent availability ---
38
+ const agents = buildAgentMetrics(db, workspaceId, now);
39
+
40
+ // --- Recommendation ---
41
+ const recommendation = computeRecommendation(capacity, queue, agents);
42
+
43
+ return NextResponse.json({
44
+ timestamp: now,
45
+ workspace_id: workspaceId,
46
+ capacity,
47
+ queue,
48
+ agents,
49
+ recommendation,
50
+ thresholds: THRESHOLDS,
51
+ });
52
+ } catch (error) {
53
+ logger.error({ err: error }, 'GET /api/workload error');
54
+ return NextResponse.json({ error: 'Failed to fetch workload signals' }, { status: 500 });
55
+ }
56
+ }
57
+
58
+ // Configurable thresholds for recommendation engine
59
+ function numEnv(name: string, fallback: number): number {
60
+ const raw = process.env[name];
61
+ if (!raw || raw.trim().length === 0) return fallback;
62
+ const parsed = Number(raw);
63
+ return Number.isFinite(parsed) ? parsed : fallback;
64
+ }
65
+
66
+ function buildThresholds() {
67
+ return {
68
+ queue_depth_normal: numEnv('MC_WORKLOAD_QUEUE_DEPTH_NORMAL', 20),
69
+ queue_depth_throttle: numEnv('MC_WORKLOAD_QUEUE_DEPTH_THROTTLE', 50),
70
+ queue_depth_shed: numEnv('MC_WORKLOAD_QUEUE_DEPTH_SHED', 100),
71
+ busy_agent_ratio_throttle: numEnv('MC_WORKLOAD_BUSY_RATIO_THROTTLE', 0.8),
72
+ busy_agent_ratio_shed: numEnv('MC_WORKLOAD_BUSY_RATIO_SHED', 0.95),
73
+ error_rate_throttle: numEnv('MC_WORKLOAD_ERROR_RATE_THROTTLE', 0.1),
74
+ error_rate_shed: numEnv('MC_WORKLOAD_ERROR_RATE_SHED', 0.25),
75
+ recent_window_seconds: Math.max(1, Math.floor(numEnv('MC_WORKLOAD_RECENT_WINDOW_SECONDS', 300))),
76
+ };
77
+ }
78
+
79
+ const THRESHOLDS = buildThresholds();
80
+
81
+ interface CapacityMetrics {
82
+ active_tasks: number;
83
+ tasks_last_5m: number;
84
+ errors_last_5m: number;
85
+ error_rate_5m: number;
86
+ completions_last_hour: number;
87
+ avg_completion_rate_per_hour: number;
88
+ }
89
+
90
+ interface QueueMetrics {
91
+ total_pending: number;
92
+ by_status: Record<string, number>;
93
+ by_priority: Record<string, number>;
94
+ oldest_pending_age_seconds: number | null;
95
+ estimated_wait_seconds: number | null;
96
+ estimated_wait_confidence: 'calculated' | 'unknown';
97
+ }
98
+
99
+ interface AgentMetrics {
100
+ total: number;
101
+ online: number;
102
+ busy: number;
103
+ idle: number;
104
+ offline: number;
105
+ busy_ratio: number;
106
+ load_distribution: Array<{ agent: string; assigned: number; in_progress: number }>;
107
+ }
108
+
109
+ function buildCapacityMetrics(db: any, workspaceId: number, now: number): CapacityMetrics {
110
+ const recentWindow = now - THRESHOLDS.recent_window_seconds;
111
+ const hourAgo = now - 3600;
112
+
113
+ const activeTasks = (db.prepare(
114
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status IN ('assigned', 'in_progress', 'review', 'quality_review')`
115
+ ).get(workspaceId) as any).c;
116
+
117
+ const tasksLast5m = (db.prepare(
118
+ `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ? AND type IN ('task_created', 'task_assigned')`
119
+ ).get(workspaceId, recentWindow) as any).c;
120
+
121
+ const errorsLast5m = (db.prepare(
122
+ `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ? AND (type LIKE '%error%' OR type LIKE '%fail%')`
123
+ ).get(workspaceId, recentWindow) as any).c;
124
+
125
+ const totalLast5m = (db.prepare(
126
+ `SELECT COUNT(*) as c FROM activities WHERE workspace_id = ? AND created_at >= ?`
127
+ ).get(workspaceId, recentWindow) as any).c;
128
+
129
+ const completionsLastHour = (db.prepare(
130
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?`
131
+ ).get(workspaceId, hourAgo) as any).c;
132
+
133
+ // Average completion rate over last 24h
134
+ const dayAgo = now - 86400;
135
+ const completionsLastDay = (db.prepare(
136
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?`
137
+ ).get(workspaceId, dayAgo) as any).c;
138
+
139
+ const safeErrorRate = totalLast5m > 0 ? errorsLast5m / totalLast5m : 0;
140
+
141
+ return {
142
+ active_tasks: activeTasks,
143
+ tasks_last_5m: tasksLast5m,
144
+ errors_last_5m: errorsLast5m,
145
+ error_rate_5m: Math.max(0, Math.min(1, Math.round(safeErrorRate * 10000) / 10000)),
146
+ completions_last_hour: completionsLastHour,
147
+ avg_completion_rate_per_hour: Math.round((completionsLastDay / 24) * 100) / 100,
148
+ };
149
+ }
150
+
151
+ function buildQueueMetrics(db: any, workspaceId: number): QueueMetrics {
152
+ const now = Math.floor(Date.now() / 1000);
153
+
154
+ const pendingStatuses = ['inbox', 'assigned', 'in_progress', 'review', 'quality_review'];
155
+
156
+ const byStatus = db.prepare(
157
+ `SELECT status, COUNT(*) as count FROM tasks WHERE workspace_id = ? AND status IN (${pendingStatuses.map(() => '?').join(',')}) GROUP BY status`
158
+ ).all(workspaceId, ...pendingStatuses) as Array<{ status: string; count: number }>;
159
+
160
+ const byPriority = db.prepare(
161
+ `SELECT priority, COUNT(*) as count FROM tasks WHERE workspace_id = ? AND status IN (${pendingStatuses.map(() => '?').join(',')}) GROUP BY priority`
162
+ ).all(workspaceId, ...pendingStatuses) as Array<{ priority: string; count: number }>;
163
+
164
+ const totalPending = byStatus.reduce((sum, r) => sum + r.count, 0);
165
+
166
+ const oldest = db.prepare(
167
+ `SELECT MIN(created_at) as oldest FROM tasks WHERE workspace_id = ? AND status IN ('inbox', 'assigned')`
168
+ ).get(workspaceId) as any;
169
+
170
+ const oldestAge = oldest?.oldest ? now - oldest.oldest : null;
171
+
172
+ // Estimate wait: pending tasks / completion rate per hour * 3600
173
+ const hourAgo = now - 3600;
174
+ const completionsLastHour = (db.prepare(
175
+ `SELECT COUNT(*) as c FROM tasks WHERE workspace_id = ? AND status = 'done' AND updated_at >= ?`
176
+ ).get(workspaceId, hourAgo) as any).c;
177
+
178
+ const estimatedWait = completionsLastHour > 0
179
+ ? Math.round((totalPending / completionsLastHour) * 3600)
180
+ : null;
181
+
182
+ const statusMap = Object.fromEntries(byStatus.map(r => [r.status, r.count]));
183
+ for (const status of pendingStatuses) {
184
+ if (typeof statusMap[status] !== 'number') statusMap[status] = 0;
185
+ }
186
+
187
+ const priorityMap = Object.fromEntries(byPriority.map(r => [r.priority, r.count]));
188
+ for (const priority of ['low', 'medium', 'high', 'critical', 'urgent']) {
189
+ if (typeof priorityMap[priority] !== 'number') priorityMap[priority] = 0;
190
+ }
191
+
192
+ return {
193
+ total_pending: totalPending,
194
+ by_status: statusMap,
195
+ by_priority: priorityMap,
196
+ oldest_pending_age_seconds: oldestAge,
197
+ estimated_wait_seconds: estimatedWait,
198
+ estimated_wait_confidence: estimatedWait === null ? 'unknown' : 'calculated',
199
+ };
200
+ }
201
+
202
+ function buildAgentMetrics(db: any, workspaceId: number, now: number): AgentMetrics {
203
+ const agentStatuses = db.prepare(
204
+ `SELECT status, COUNT(*) as count FROM agents WHERE workspace_id = ? GROUP BY status`
205
+ ).all(workspaceId) as Array<{ status: string; count: number }>;
206
+
207
+ const statusMap: Record<string, number> = {};
208
+ let total = 0;
209
+ for (const row of agentStatuses) {
210
+ statusMap[row.status] = row.count;
211
+ total += row.count;
212
+ }
213
+
214
+ const online = (statusMap['idle'] || 0) + (statusMap['busy'] || 0);
215
+ const busy = statusMap['busy'] || 0;
216
+ const idle = statusMap['idle'] || 0;
217
+ const offline = statusMap['offline'] || 0;
218
+
219
+ // Load distribution per agent
220
+ const loadDist = db.prepare(`
221
+ SELECT a.name as agent,
222
+ SUM(CASE WHEN t.status = 'assigned' THEN 1 ELSE 0 END) as assigned,
223
+ SUM(CASE WHEN t.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress
224
+ FROM agents a
225
+ LEFT JOIN tasks t ON t.assigned_to = a.name AND t.workspace_id = a.workspace_id AND t.status IN ('assigned', 'in_progress')
226
+ WHERE a.workspace_id = ? AND a.status != 'offline'
227
+ GROUP BY a.name
228
+ ORDER BY (assigned + in_progress) DESC
229
+ `).all(workspaceId) as Array<{ agent: string; assigned: number; in_progress: number }>;
230
+
231
+ return {
232
+ total,
233
+ online,
234
+ busy,
235
+ idle,
236
+ offline,
237
+ busy_ratio: online > 0 ? Math.round((busy / online) * 100) / 100 : 0,
238
+ load_distribution: loadDist,
239
+ };
240
+ }
241
+
242
+ type RecommendationLevel = 'normal' | 'throttle' | 'shed' | 'pause';
243
+
244
+ interface Recommendation {
245
+ action: RecommendationLevel;
246
+ reason: string;
247
+ details: string[];
248
+ submit_ok: boolean;
249
+ suggested_delay_ms: number;
250
+ }
251
+
252
+ function computeRecommendation(
253
+ capacity: CapacityMetrics,
254
+ queue: QueueMetrics,
255
+ agents: AgentMetrics
256
+ ): Recommendation {
257
+ const reasons: string[] = [];
258
+ let level: RecommendationLevel = 'normal';
259
+
260
+ // Check error rate
261
+ if (capacity.error_rate_5m >= THRESHOLDS.error_rate_shed) {
262
+ level = escalate(level, 'shed');
263
+ reasons.push(`High error rate: ${(capacity.error_rate_5m * 100).toFixed(1)}%`);
264
+ } else if (capacity.error_rate_5m >= THRESHOLDS.error_rate_throttle) {
265
+ level = escalate(level, 'throttle');
266
+ reasons.push(`Elevated error rate: ${(capacity.error_rate_5m * 100).toFixed(1)}%`);
267
+ }
268
+
269
+ // Check queue depth
270
+ if (queue.total_pending >= THRESHOLDS.queue_depth_shed) {
271
+ level = escalate(level, 'shed');
272
+ reasons.push(`Queue depth critical: ${queue.total_pending} pending tasks`);
273
+ } else if (queue.total_pending >= THRESHOLDS.queue_depth_throttle) {
274
+ level = escalate(level, 'throttle');
275
+ reasons.push(`Queue depth high: ${queue.total_pending} pending tasks`);
276
+ }
277
+
278
+ // Check agent saturation
279
+ if (agents.busy_ratio >= THRESHOLDS.busy_agent_ratio_shed) {
280
+ level = escalate(level, 'shed');
281
+ reasons.push(`Agent saturation critical: ${(agents.busy_ratio * 100).toFixed(0)}% busy`);
282
+ } else if (agents.busy_ratio >= THRESHOLDS.busy_agent_ratio_throttle) {
283
+ level = escalate(level, 'throttle');
284
+ reasons.push(`Agent saturation high: ${(agents.busy_ratio * 100).toFixed(0)}% busy`);
285
+ }
286
+
287
+ // No online agents = pause
288
+ if (agents.online === 0) {
289
+ level = 'pause';
290
+ reasons.push(agents.total > 0 ? 'No agents online' : 'No agents registered');
291
+ }
292
+
293
+ const delayMap: Record<RecommendationLevel, number> = {
294
+ normal: 0,
295
+ throttle: 2000,
296
+ shed: 10000,
297
+ pause: 30000,
298
+ };
299
+
300
+ const actionDescriptions: Record<RecommendationLevel, string> = {
301
+ normal: 'System healthy — submit work freely',
302
+ throttle: 'System under load — reduce submission rate and defer non-critical work',
303
+ shed: 'System overloaded — submit only critical/high-priority work, defer everything else',
304
+ pause: 'System unavailable — hold all submissions until capacity returns',
305
+ };
306
+
307
+ return {
308
+ action: level,
309
+ reason: actionDescriptions[level],
310
+ details: reasons.length > 0 ? reasons : ['All metrics within normal bounds'],
311
+ submit_ok: level === 'normal' || level === 'throttle',
312
+ suggested_delay_ms: delayMap[level],
313
+ };
314
+ }
315
+
316
+ function escalate(current: RecommendationLevel, proposed: RecommendationLevel): RecommendationLevel {
317
+ const order: RecommendationLevel[] = ['normal', 'throttle', 'shed', 'pause'];
318
+ return order.indexOf(proposed) > order.indexOf(current) ? proposed : current;
319
+ }
src/components/ErrorBoundary.tsx CHANGED
@@ -1,6 +1,9 @@
1
  'use client'
2
 
3
  import { Component, type ErrorInfo, type ReactNode } from 'react'
 
 
 
4
 
5
  interface Props {
6
  children: ReactNode
@@ -23,7 +26,7 @@ export class ErrorBoundary extends Component<Props, State> {
23
  }
24
 
25
  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
26
- console.error('Panel error:', error, errorInfo)
27
  }
28
 
29
  render() {
 
1
  'use client'
2
 
3
  import { Component, type ErrorInfo, type ReactNode } from 'react'
4
+ import { createClientLogger } from '@/lib/client-logger'
5
+
6
+ const log = createClientLogger('ErrorBoundary')
7
 
8
  interface Props {
9
  children: ReactNode
 
26
  }
27
 
28
  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
29
+ log.error('Panel error:', error, errorInfo)
30
  }
31
 
32
  render() {
src/components/chat/chat-panel.tsx CHANGED
@@ -3,10 +3,13 @@
3
  import { useEffect, useCallback, useState, useRef } from 'react'
4
  import { useMissionControl } from '@/store'
5
  import { useSmartPoll } from '@/lib/use-smart-poll'
 
6
  import { ConversationList } from './conversation-list'
7
  import { MessageList } from './message-list'
8
  import { ChatInput } from './chat-input'
9
 
 
 
10
  export function ChatPanel() {
11
  const {
12
  chatPanelOpen,
@@ -52,7 +55,7 @@ export function ChatPanel() {
52
  const data = await res.json()
53
  if (data.agents) setAgents(data.agents)
54
  } catch (err) {
55
- console.error('Failed to load agents:', err)
56
  }
57
  }
58
  if (chatPanelOpen) loadAgents()
@@ -67,7 +70,7 @@ export function ChatPanel() {
67
  const data = await res.json()
68
  if (data.messages) setChatMessages(data.messages)
69
  } catch (err) {
70
- console.error('Failed to load messages:', err)
71
  }
72
  }, [activeConversation, setChatMessages])
73
 
@@ -145,7 +148,7 @@ export function ChatPanel() {
145
  updatePendingMessage(tempId, { pendingStatus: 'failed' })
146
  }
147
  } catch (err) {
148
- console.error('Failed to send message:', err)
149
  updatePendingMessage(tempId, { pendingStatus: 'failed' })
150
  }
151
  }
 
3
  import { useEffect, useCallback, useState, useRef } from 'react'
4
  import { useMissionControl } from '@/store'
5
  import { useSmartPoll } from '@/lib/use-smart-poll'
6
+ import { createClientLogger } from '@/lib/client-logger'
7
  import { ConversationList } from './conversation-list'
8
  import { MessageList } from './message-list'
9
  import { ChatInput } from './chat-input'
10
 
11
+ const log = createClientLogger('ChatPanel')
12
+
13
  export function ChatPanel() {
14
  const {
15
  chatPanelOpen,
 
55
  const data = await res.json()
56
  if (data.agents) setAgents(data.agents)
57
  } catch (err) {
58
+ log.error('Failed to load agents:', err)
59
  }
60
  }
61
  if (chatPanelOpen) loadAgents()
 
70
  const data = await res.json()
71
  if (data.messages) setChatMessages(data.messages)
72
  } catch (err) {
73
+ log.error('Failed to load messages:', err)
74
  }
75
  }, [activeConversation, setChatMessages])
76
 
 
148
  updatePendingMessage(tempId, { pendingStatus: 'failed' })
149
  }
150
  } catch (err) {
151
+ log.error('Failed to send message:', err)
152
  updatePendingMessage(tempId, { pendingStatus: 'failed' })
153
  }
154
  }
src/components/chat/conversation-list.tsx CHANGED
@@ -3,6 +3,9 @@
3
  import { useState, useCallback } from 'react'
4
  import { useMissionControl, Conversation, Agent } from '@/store'
5
  import { useSmartPoll } from '@/lib/use-smart-poll'
 
 
 
6
 
7
  function timeAgo(timestamp: number): string {
8
  const diff = Math.floor(Date.now() / 1000) - timestamp
@@ -64,7 +67,7 @@ export function ConversationList({ onNewConversation }: ConversationListProps) {
64
  )
65
  }
66
  } catch (err) {
67
- console.error('Failed to load conversations:', err)
68
  }
69
  }, [setConversations])
70
 
 
3
  import { useState, useCallback } from 'react'
4
  import { useMissionControl, Conversation, Agent } from '@/store'
5
  import { useSmartPoll } from '@/lib/use-smart-poll'
6
+ import { createClientLogger } from '@/lib/client-logger'
7
+
8
+ const log = createClientLogger('ConversationList')
9
 
10
  function timeAgo(timestamp: number): string {
11
  const diff = Math.floor(Date.now() / 1000) - timestamp
 
67
  )
68
  }
69
  } catch (err) {
70
+ log.error('Failed to load conversations:', err)
71
  }
72
  }, [setConversations])
73