The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
Mcp cli write path (#404)
narrow-adventureefcddf07fde9
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex a0445274..1e3c15df 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -8,7 +8,12 @@{"name": "tw","source": "./",- "description": "Traceway skills: /tw:traceway debugs production issues through the traceway CLI, /tw:traceway-setup instruments a project to report to a Traceway instance."+ "description": "Traceway skills: /tw:traceway debugs production issues through the traceway CLI, /tw:traceway-learn is the full guide to every part of Traceway, /tw:traceway-setup instruments a project to report to a Traceway instance."+ },+ {+ "name": "tw-write",+ "source": "./plugins/tw-write",+ "description": "Traceway write skill: lets an agent make routine on-call changes through the traceway-write CLI. Opt-in, separate from the read-only tw plugin."}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 31102371..87bc4427 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "tw",- "description": "Traceway skills: /tw:traceway debugs production issues through the traceway CLI, /tw:traceway-setup instruments a project to report to a Traceway instance.",- "version": "1.0.0",+ "description": "Traceway skills: /tw:traceway debugs production issues through the traceway CLI, /tw:traceway-learn is the full guide to every part of Traceway, /tw:traceway-setup instruments a project to report to a Traceway instance.",+ "version": "1.0.1","author": {"name": "Traceway"},diff --git a/.github/workflows/cli-lint.yml b/.github/workflows/cli-lint.ymlindex 482e2a5e..202a7a77 100644--- a/.github/workflows/cli-lint.yml+++ b/.github/workflows/cli-lint.yml@@ -64,6 +64,15 @@ jobs:version: v2.13.1working-directory: cli+ # .golangci.yml lints the read build; the write build's files+ # (edition_write.go, exceptions_write.go) need a pass with its tag.+ - name: Lint (write build)+ uses: golangci/golangci-lint-action@v9+ with:+ version: v2.13.1+ working-directory: cli+ args: --build-tags write+vulncheck:if: github.event_name != 'pull_request' || github.event.label.name == 'ci'runs-on: ubuntu-latestdiff --git a/.github/workflows/cli.yml b/.github/workflows/cli.ymlindex 113ccd3d..d84b2da4 100644--- a/.github/workflows/cli.yml+++ b/.github/workflows/cli.yml@@ -7,6 +7,8 @@ on:- "cli/**"- "backend/**"- "skills/traceway/**"+ - "skills/traceway-learn/**"+ - "plugins/tw-write/**"- ".github/workflows/cli.yml"pull_request:types: [labeled]@@ -14,6 +16,8 @@ on:- "cli/**"- "backend/**"- "skills/traceway/**"+ - "skills/traceway-learn/**"+ - "plugins/tw-write/**"- ".github/workflows/cli.yml"workflow_dispatch:@@ -38,12 +42,17 @@ jobs:cache-dependency-path: cli/go.sum- name: Build- run: go build ./...+ run: |+ go build ./...+ go build -tags write ./...- name: Test- run: go test ./...+ run: |+ go test ./...+ go test -tags write ./cmd/... ./pkg/mcpserver/...- name: Skill drift checkrun: |go run ./tools/skillgen- git diff --exit-code ../skills/traceway+ git diff --exit-code ../skills/traceway ../skills/traceway-learn ../plugins/tw-write+ test -z "$(git status --porcelain ../skills/traceway-learn ../plugins/tw-write)"diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.ymlindex f47d39b8..7c06b6a2 100644--- a/.github/workflows/release-cli.yml+++ b/.github/workflows/release-cli.yml@@ -70,22 +70,32 @@ jobs:"darwin arm64 arm64""windows amd64 x86_64")- for entry in "${PAIRS[@]}"; do- read -r OS ARCH LABEL <<< "$entry"- STAGE="dist/staging/${OS}_${LABEL}"- mkdir -p "$STAGE"- BIN="traceway"- [[ "$OS" == "windows" ]] && BIN="traceway.exe"- echo "Building $OS/$ARCH -> $STAGE/$BIN"- GOOS="$OS" GOARCH="$ARCH" go build -trimpath -ldflags "-X main.version=${VERSION}" -o "$STAGE/$BIN" ./cmd/traceway- cp README.md "$STAGE/"- cp ../LICENSE "$STAGE/"- ARCHIVE_BASE="traceway_${VERSION}_${OS}_${LABEL}"- if [[ "$OS" == "windows" ]]; then- (cd "$STAGE" && zip -q "../../${ARCHIVE_BASE}.zip" *)- else- tar -C "$STAGE" -czf "dist/${ARCHIVE_BASE}.tar.gz" .- fi+ # NAME TAGS: the read-only traceway and the separate traceway-write+ # build, each in its own archive so installing one never installs the other.+ EDITIONS=(+ "traceway -"+ "traceway-write write"+ )+ for edition in "${EDITIONS[@]}"; do+ read -r NAME TAGS <<< "$edition"+ [[ "$TAGS" == "-" ]] && TAGS=""+ for entry in "${PAIRS[@]}"; do+ read -r OS ARCH LABEL <<< "$entry"+ STAGE="dist/staging/${NAME}_${OS}_${LABEL}"+ mkdir -p "$STAGE"+ BIN="$NAME"+ [[ "$OS" == "windows" ]] && BIN="${NAME}.exe"+ echo "Building $NAME $OS/$ARCH -> $STAGE/$BIN"+ GOOS="$OS" GOARCH="$ARCH" go build -trimpath -tags "$TAGS" -ldflags "-X main.version=${VERSION}" -o "$STAGE/$BIN" ./cmd/traceway+ cp README.md "$STAGE/"+ cp ../LICENSE "$STAGE/"+ ARCHIVE_BASE="${NAME}_${VERSION}_${OS}_${LABEL}"+ if [[ "$OS" == "windows" ]]; then+ (cd "$STAGE" && zip -q "../../${ARCHIVE_BASE}.zip" *)+ else+ tar -C "$STAGE" -czf "dist/${ARCHIVE_BASE}.tar.gz" .+ fi+ donedonerm -rf dist/stagingls -la distdiff --git a/CLAUDE.md b/CLAUDE.mdindex 1c43a52a..84a2a7d9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7,7 +7,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with coTraceway is an error tracking and monitoring platform consisting of:- **Frontend**: SvelteKit 2 dashboard application with Svelte 5- **Backend**: Go/Gin API server with ClickHouse database-- **CLI**: Go/Cobra command-line client for the backend HTTP API (`/cli`)+- **CLI**: Go/Cobra command-line client for the backend HTTP API (`/cli`), built twice from one source: read-only `traceway`, and `traceway-write` (`-tags write`, own config dir and OAuth client, write commands in `cmd/traceway/edition_write.go`). Skills: `skills/traceway` (read), `skills/traceway-learn` (the product guide, one file per area from `knowledge/learn/`, also served as `traceway://knowledge/learn/*`) and `plugins/tw-write/skills/traceway-write` (write, separate plugin), all generated from `cli/pkg/mcpserver/knowledge` by `just gen-skills`---@@ -350,6 +350,8 @@ Two-tier system:- **Personal access token (PAT)** — opaque `twp_`-prefixed token; looked up by SHA-256 hash in `personal_access_tokens`, resolves to its user. Created/listed/revoked from the account page (`/api/personal-access-tokens*`). Non-expiring or with an optional TTL; `last_used_at` is touched (throttled to 1/min, off the request path).- **Device-flow access token** — a short-lived (15-min) JWT minted by the CLI's OAuth device flow.+**Agent scopes and the agent gate.** Every credential except a dashboard session is an *agent* credential with a scope, `traceway:read` or `traceway:write` (`models.ScopeRead/ScopeWrite`). PATs store it (`personal_access_tokens.scope`; read tokens are `twp_`, write tokens `tww_` and must expire within 90 days), refresh tokens and authorization codes store it, and access JWTs carry it as the `scope` claim (plus `cid`, the OAuth client). Device logins take their scope from the client id (`knownDeviceClients`: `traceway-cli` and `traceway-mcp` read, `traceway-cli-write` write); the authorization-code grant takes it from the request's `scope` param (`models.ParseRequestedScope`, default read); a refresh keeps the family's scope; `POST /api/login` with a `scope` field returns a token set instead of a session (`token` is a 15-minute scoped access JWT, plus `refreshToken`/`expiresIn` in a refresh family with client id `traceway-cli` or `traceway-cli-write`, so `POST /api/auth/logout` revokes it; the CLI's password login always sends a scope and stores the result like a device login). An unscoped JWT that lives one hour or less predates scopes and is held to read. `UseAppAuth` sends agent credentials through `authorizeAgentRequest` (`middleware/agent_gate.go`): the route must be in the allowlist `agentRoutes` (`middleware/agent_routes.go`, keyed `METHOD /api/path` by `c.FullPath()`, default deny, so new dashboard routes are never agent-reachable by accident; `TestAgentRoutesAreRegistered` keeps entries pointing at real routes); a write route needs the write scope (else 403 with a `scope="traceway:write"` challenge) and the owning organization's opt-in `organizations.agent_write_enabled` (Settings > Agent Access, `PUT /api/organizations/:organizationId/agent-access`, else 403), resolved from `?projectId=` together with membership, which is why every allowlisted write is project-scoped. Accepted and opt-in-refused agent writes are recorded in `agent_write_events` (main DB, pruned after 90 days by the auth-tokens worker, listed at `GET /api/organizations/:organizationId/agent-activity`). The role checks (`RequireWriteAccess` etc.) still apply after the gate. Dashboard sessions skip the gate entirely. Docs: `docs/pages/learn/agent-write-access.mdx`.+**CLI / OAuth device flow** (`backend/app/services/authserver/`, controllers `device_auth.controller.go` / `wellknown.controller.go` / `pat.controller.go`): RFC 8628 device authorization grant plus rotating refresh tokens. `traceway login` (default) → `POST /api/auth/device/authorize` (client_id allowlisted, per-IP rate-limited, opportunistically prunes expired rows) → user approves at `/device` → the CLI polls `POST /api/auth/device/token` (grant `device_code`; `/api/auth/token` is an equivalent alias) which issues a 15-min access token + 90-day rotating refresh token (family-tracked in `refresh_tokens`). Refresh (`grant_type=refresh_token`) rotates the token atomically and revokes the whole family on genuine reuse; within a 30s grace window a benign concurrent retry is answered with the same rotated token set (from an in-memory rotation cache) instead of `invalid_grant`. `POST /api/auth/logout` revokes a family server-side. Tokens are stored SHA-256-hashed. The grant endpoints **self-manage their transactions** via `db.ExecuteTransaction` (not `middleware.Transactional`) because OAuth returns 400 for normal flow control (`authorization_pending`, reuse-revoke) and those side effects must still commit. `/.well-known/oauth-authorization-server` and `/.well-known/oauth-protected-resource` are served at the **origin root** (registered in `cmd/run.go`, not the `/api` group) per RFC 8414 / 9728. Beyond the device grant, the server implements the **authorization-code + PKCE grant** (S256 only) with **RFC 7591 dynamic client registration** for MCP clients: `POST /api/oauth/register` (rate-limited, open registration of public clients; https/custom-scheme redirect URIs anywhere, plain http only on loopback with port-flexible matching per RFC 8252) -> the client sends the user to `/oauth/authorize` (an SPA consent page like `/device`) -> the page calls `GET /api/oauth/client` + `POST /api/oauth/approve|deny` (approve mints a single-use 5-min `twa_` code bound to user/client/redirect/challenge; the redirect target is validated server-side) -> the client exchanges it at `POST /api/auth/token` (grant `authorization_code`; the code is consumed even on a failed exchange, wrong verifier/client/redirect are all `invalid_grant`). RFC 8707 `resource` params are validated against the issuer origin (`invalid_target`). Expired codes are pruned by the auth-tokens retention worker and opportunistically at approve time.---@@ -649,12 +651,13 @@ backend/| POST | `/api/oauth/deny` | App | Deny an authorization request; returns the error redirect || GET | `/.well-known/oauth-authorization-server` | None | RFC 8414 metadata (served at origin root, not `/api`) || GET | `/.well-known/oauth-protected-resource` | None | RFC 9728 metadata (served at origin root, not `/api`) |-| GET/POST/DELETE | `/mcp` | Bearer | Streamable HTTP MCP server (origin root); 401s carry a `WWW-Authenticate` resource-metadata challenge |+| GET/POST/DELETE | `/mcp` | Bearer | Streamable HTTP MCP server (origin root), read tools only for every credential; 401s carry a `WWW-Authenticate` resource-metadata challenge |+| GET/POST/DELETE | `/mcp/write` | Bearer (write scope) | Same server with `mcpserver.Config.AllowWrite`: adds the mutating tools and the operations playbook. Tokens without `traceway:write` get 403 with a scope challenge, and so do dashboard sessions (`BearerIdentity.HasAgentWriteScope`), which would otherwise skip the agent gate's opt-in and audit log; resource metadata at `/.well-known/oauth-protected-resource/mcp/write` |**Personal Access Tokens**| Method | Endpoint | Auth | Purpose ||--------|----------|------|---------|-| POST | `/api/personal-access-tokens` | App | Create a PAT (returns the `twp_` token once) |+| POST | `/api/personal-access-tokens` | App | Create a PAT (returns the token once). `scope` is `read` (default, `twp_`) or `write` (`tww_`, `expiresInDays` 1-90 required) || GET | `/api/personal-access-tokens` | App | List the current user's active PATs || DELETE | `/api/personal-access-tokens/:id` | App | Revoke a PAT |@@ -768,6 +771,8 @@ Frontend routes: `/ai-traces` (tabs: Traces, Conversations, Users), `/ai-traces/| POST | `/api/organizations` | App | Create an organization owned by the caller; the recovery path for a user removed from their last organization (self-hosted: 422 once one exists; cloud: `OrganizationLimitHook`). Runs `PostRegistrationHooks` like register and SSO finish-setup || GET | `/api/organizations/:orgId/settings` | Admin | Get org settings || PUT | `/api/organizations/:orgId/settings` | Admin | Update org settings |+| PUT | `/api/organizations/:orgId/agent-access` | Admin | `{agentWriteEnabled}`: allow agent write credentials to write in this org (settings GET returns the flag) |+| GET | `/api/organizations/:orgId/agent-activity` | Admin | Paginated agent write log (who, credential, project, route, status) || GET | `/api/organizations/:orgId/members` | Admin | List members || PUT | `/api/organizations/:orgId/members/:userId` | Admin | Update member role || DELETE | `/api/organizations/:orgId/members/:userId` | Admin | Remove member |@@ -861,7 +866,7 @@ Checks (`synthetic_checks`, main DB) are http/tcp/browser probes with per-check| PUT/DELETE | `/api/organizations/:organizationId/incidents/:incidentId` | Admin | Edit title (any incident) / times (manual only, empty resolvedAt reopens; 422 for auto) / delete (manual only, 422 for auto) || POST/DELETE | `/api/organizations/:organizationId/incidents/:incidentId/updates(/:updateId)` | Admin | Post / delete a public timeline update (a `resolved` update also closes an unresolved manual incident) || GET/POST | `/api/post-mortems` | App / App+Write | Paginated list for the project (query params search/page/pageSize + repeatable `tag` params ANDed together) / create in the project (422 on duplicate or cross-project incident link) |-| GET/PUT/DELETE | `/api/post-mortems/:id` | App / +Write / +Write | Full document with author names (contentMd) / update (records a `post_mortem_events` diff row; no-op saves change nothing) / delete |+| GET/PUT/DELETE | `/api/post-mortems/:id` | App / +Write / +Write | Full document with author names (contentMd) / update (records a `post_mortem_events` diff row; no-op saves change nothing; an optional `expectedUpdatedAt` answers 409 when the document changed since that read; the row is locked first (`LockForUpdate`) so concurrent Postgres updates cannot both pass the check. The CLI and MCP send the revision the caller's edit is based on, required when they replace the body (`--expected-updated-at` / `expected_updated_at`), and fall back to their own fresh read for title, tag and incident-only edits) / delete || GET | `/api/post-mortems/:id/activity` | App | Edit log for the Activity panel (who created/edited what, joined user names) |**Logs**diff --git a/README.md b/README.mdindex 8eb6f37b..b3336aca 100644--- a/README.md+++ b/README.md@@ -63,15 +63,19 @@ Plus: background-task (job) monitoring, configurable alerts (Slack / GitHub / emYour agent sets up Traceway, queries production telemetry, and finds the root cause:```bash-npx skills add tracewayapp/traceway+npx skills add tracewayapp/traceway --all```-One command installs two skills into Claude Code, Cursor, Codex, or any agent that reads `SKILL.md`:+One command installs all four skills into Claude Code, Cursor, Codex, or any agent that reads `SKILL.md`:- **`/traceway-setup`** reads your repo and wires it up: OTel for backends, Traceway SDKs for web and mobile. Then it verifies data actually arrives.- **`/traceway`** installs the `traceway` CLI and uses it to query exceptions, logs, endpoints, and metrics, from bug report to root cause.+- **`/traceway-learn`** is the full guide to the product: issues, endpoints, traces, logs, metrics, monitors, status pages, alerts, on-call schedules and paging, and settings. Ask it how anything in Traceway works.+- **`/traceway-write`** teaches an agent to make routine on-call changes safely. It does nothing until you opt in to agent write access (below).-The [CLI](./cli) is designed for agents first: JSON when piped, tables on a TTY, stable error identifiers and exit codes, `--fields` to trim responses. It's read-only apart from archiving exceptions, which needs an explicit `--yes`. Nothing hangs, nothing gets damaged.+The [CLI](./cli) is designed for agents first: JSON when piped, tables on a TTY, stable error identifiers and exit codes, `--fields` to trim responses. It's read only. Nothing hangs, nothing gets damaged.++Want the agent to act too? Agent write access is opt-in at three levels: a write credential (the separate `traceway-write` CLI, a `tww_` token, or the `/mcp/write` server), an organization admin switch, and the creator's own role. Then an agent can archive issues, acknowledge pages, snooze alerts, run monitors and write post-mortems, and every write lands in an audit log. In Claude Code the `traceway-write` skill is its own plugin (`plugins/tw-write`). [Learn more →](https://docs.tracewayapp.com/learn/agent-write-access)The skills are plain Markdown in [`skills/`](./skills), in the same MIT-licensed repo. No marketplace, no lock-in. [Learn more →](https://tracewayapp.com/product/agent-skills)@@ -240,7 +244,7 @@ A full-stack framework has two halves and two Traceway projects. Next.js and Rem| `backend/` | Go/Gin API server: OTLP ingest, REST API, notifications, migrations || `frontend/` | SvelteKit 2 dashboard SPA || `cli/` | Agent-first `traceway` command line for querying exceptions, logs, endpoints, and metrics |-| `skills/` | Agent skills (`/traceway-setup`, `/traceway`) for Claude Code, Cursor, Codex, and any SKILL.md-compatible agent |+| `skills/` | Agent skills (`/traceway-setup`, `/traceway`, `/traceway-learn`) for Claude Code, Cursor, Codex, and any SKILL.md-compatible agent || `docs/` | Documentation site (Nextra) || `examples/` | Working examples: embedded mode ([OTel](./examples/embedded-backend-otel), [Go client](./examples/embedded-backend-go-client)) and OTel-instrumented apps ([Express](./examples/express-otel), [NestJS](./examples/nestjs-otel), [Next.js](./examples/nextjs-otel), [Hono](./examples/hono-otel)) || `website/` | Landing page |diff --git a/backend/app/controllers/agent_access_sqlite_test.go b/backend/app/controllers/agent_access_sqlite_test.gonew file mode 100644index 00000000..5336a77e--- /dev/null+++ b/backend/app/controllers/agent_access_sqlite_test.go@@ -0,0 +1,566 @@+//go:build !transactional_pg && !telemetry_ch && !telemetry_duckdb++package controllers++import (+ "bytes"+ "database/sql"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/golang-jwt/jwt/v5"+ "github.com/google/uuid"++ "github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/dbtest"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ "github.com/tracewayapp/traceway/backend/app/services"+ "github.com/tracewayapp/traceway/backend/app/services/authserver"+)++const agentTestSecret = "agent-access-test-secret-0123456789abcdef"++type agentFixture struct {+ engine *gin.Engine+ orgId int+ project *models.Project+ otherProject *models.Project+ userId int+}++func setupAgentFixture(t *testing.T) *agentFixture {+ t.Helper()+ gin.SetMode(gin.TestMode)+ dbtest.SetupSQLite(t)+ previous := config.Config.JWTSecret+ config.Config.JWTSecret = agentTestSecret+ t.Cleanup(func() { config.Config.JWTSecret = previous })+ if err := services.InitJWT(); err != nil {+ t.Fatalf("init jwt: %v", err)+ }+ middleware.InitUseAppAuth()+ middleware.InitRequireWriteAccess()+ middleware.InitRequireProjectAccess()+ middleware.InitRequireAdminAccess()+ middleware.InitRequireOrganizationAccess()++ f := &agentFixture{}+ f.orgId = createTestOrg(t, "agent-org")+ otherOrg := createTestOrg(t, "foreign-org")+ var err error+ f.project, err = db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {+ return transactional.ProjectRepository.CreateWithOrganization(tx, "agent-project", "opentelemetry", f.orgId)+ })+ if err != nil {+ t.Fatalf("create project: %v", err)+ }+ f.otherProject, err = db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {+ return transactional.ProjectRepository.CreateWithOrganization(tx, "foreign-project", "opentelemetry", otherOrg)+ })+ if err != nil {+ t.Fatalf("create foreign project: %v", err)+ }+ user, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.User, error) {+ u, err := transactional.UserRepository.Create(tx, "[email protected]", "Agent Owner", "x")+ if err != nil {+ return nil, err+ }+ _, err = transactional.OrganizationRepository.AddUser(tx, f.orgId, u.Id, "owner")+ return u, err+ })+ if err != nil {+ t.Fatalf("create user: %v", err)+ }+ f.userId = user.Id++ f.engine = gin.New()+ RegisterControllers(f.engine.Group("/api"))+ return f+}++func (f *agentFixture) pat(t *testing.T, scope string) string {+ t.Helper()+ prefix := "twp_"+ if scope == models.ScopeWrite {+ prefix = "tww_"+ }+ token := prefix + uuid.NewString()+ expires := time.Now().Add(time.Hour)+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {+ return struct{}{}, transactional.PersonalAccessTokenRepository.Create(tx, uuid.NewString(), token, token[:12], f.userId, "test "+scope, scope, &expires)+ })+ if err != nil {+ t.Fatalf("create pat: %v", err)+ }+ return token+}++func (f *agentFixture) do(t *testing.T, token, method, path string, body any) *httptest.ResponseRecorder {+ t.Helper()+ var buf bytes.Buffer+ if body != nil {+ _ = json.NewEncoder(&buf).Encode(body)+ }+ req := httptest.NewRequest(method, path, &buf)+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ f.engine.ServeHTTP(rec, req)+ return rec+}++func (f *agentFixture) archivePath(project *models.Project) string {+ return "/api/exception-stack-traces/archive?projectId=" + project.Id.String()+}++func (f *agentFixture) archive(t *testing.T, token string) *httptest.ResponseRecorder {+ t.Helper()+ return f.do(t, token, http.MethodPost, f.archivePath(f.project), map[string]any{"hashes": []string{"abcdef0123456789"}})+}++func (f *agentFixture) setAgentWrites(t *testing.T, enabled bool) {+ t.Helper()+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {+ return struct{}{}, transactional.OrganizationRepository.SetAgentWriteEnabled(tx, f.orgId, enabled)+ })+ if err != nil {+ t.Fatalf("set agent writes: %v", err)+ }+}++func (f *agentFixture) auditEvents(t *testing.T) []*models.AgentWriteEvent {+ t.Helper()+ events, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.AgentWriteEvent, error) {+ events, _, err := transactional.AgentWriteEventRepository.ListByOrganization(tx, f.orgId, 1, 100)+ return events, err+ })+ if err != nil {+ t.Fatalf("list audit events: %v", err)+ }+ return events+}++func signTestJWT(t *testing.T, userId int, scope, clientId string, ttl time.Duration) string {+ t.Helper()+ now := time.Now()+ claims := services.JWTClaims{+ UserId: userId,+ Email: "[email protected]",+ Scope: scope,+ ClientId: clientId,+ RegisteredClaims: jwt.RegisteredClaims{+ ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),+ IssuedAt: jwt.NewNumericDate(now),+ NotBefore: jwt.NewNumericDate(now),+ },+ }+ token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(agentTestSecret))+ if err != nil {+ t.Fatalf("sign jwt: %v", err)+ }+ return token+}++func errorMessage(rec *httptest.ResponseRecorder) string {+ var body struct {+ Error string `json:"error"`+ }+ _ = json.Unmarshal(rec.Body.Bytes(), &body)+ return body.Error+}++func TestAgentGate_readTokenReadsButCannotWrite(t *testing.T) {+ f := setupAgentFixture(t)+ read := f.pat(t, models.ScopeRead)++ if rec := f.do(t, read, http.MethodGet, "/api/projects", nil); rec.Code != http.StatusOK {+ t.Fatalf("read token GET /api/projects = %d %s", rec.Code, rec.Body.String())+ }++ f.setAgentWrites(t, true)+ rec := f.archive(t, read)+ if rec.Code != http.StatusForbidden || !strings.Contains(errorMessage(rec), "read-only") {+ t.Fatalf("read token archive = %d %q, want 403 read-only", rec.Code, errorMessage(rec))+ }+ if got := rec.Header().Get("WWW-Authenticate"); !strings.Contains(got, `scope="traceway:write"`) {+ t.Errorf("insufficient scope challenge missing: %q", got)+ }+ if events := f.auditEvents(t); len(events) != 0 {+ t.Errorf("a scope rejection must not reach the audit log, got %d events", len(events))+ }+}++func TestAgentGate_routesOutsideAllowlistAreDenied(t *testing.T) {+ f := setupAgentFixture(t)+ f.setAgentWrites(t, true)+ write := f.pat(t, models.ScopeWrite)++ for _, tc := range []struct{ method, path string }{+ {http.MethodPost, "/api/personal-access-tokens"},+ {http.MethodPost, "/api/device/approve"},+ {http.MethodPost, "/api/oauth/approve"},+ {http.MethodDelete, "/api/projects?projectId=" + f.project.Id.String()},+ {http.MethodPut, "/api/organizations/" + itoa(f.orgId) + "/agent-access"},+ {http.MethodGet, "/api/me/login-bundle"},+ } {+ rec := f.do(t, write, tc.method, tc.path, map[string]any{})+ if rec.Code != http.StatusForbidden || !strings.Contains(errorMessage(rec), "not available") {+ t.Errorf("%s %s with a write token = %d %q, want 403 not available", tc.method, tc.path, rec.Code, errorMessage(rec))+ }+ }+}++func TestAgentGate_writeNeedsOrganizationOptIn(t *testing.T) {+ f := setupAgentFixture(t)+ write := f.pat(t, models.ScopeWrite)++ rec := f.archive(t, write)+ if rec.Code != http.StatusForbidden || !strings.Contains(errorMessage(rec), "turned off") {+ t.Fatalf("write before opt-in = %d %q, want 403 turned off", rec.Code, errorMessage(rec))+ }++ f.setAgentWrites(t, true)+ if rec := f.archive(t, write); rec.Code != http.StatusOK {+ t.Fatalf("write after opt-in = %d %s", rec.Code, rec.Body.String())+ }++ events := f.auditEvents(t)+ if len(events) != 2 {+ t.Fatalf("audit events = %d, want 2 (the refused and the accepted write)", len(events))+ }+ accepted, refused := events[0], events[1]+ if accepted.StatusCode != http.StatusOK || refused.StatusCode != http.StatusForbidden {+ t.Errorf("audit statuses = %d, %d; want 200 then 403 (newest first)", accepted.StatusCode, refused.StatusCode)+ }+ if accepted.CredentialKind != middleware.CredentialPAT || accepted.Route != "/api/exception-stack-traces/archive" || accepted.ProjectName != "agent-project" || accepted.UserEmail != "[email protected]" || accepted.CredentialName != "test traceway:write" {+ t.Errorf("audit row = %+v", accepted)+ }+}++func TestAgentGate_writeToForeignProjectIsRefused(t *testing.T) {+ f := setupAgentFixture(t)+ f.setAgentWrites(t, true)+ write := f.pat(t, models.ScopeWrite)++ rec := f.do(t, write, http.MethodPost, f.archivePath(f.otherProject), map[string]any{"hashes": []string{"abcdef0123456789"}})+ if rec.Code != http.StatusForbidden {+ t.Fatalf("write to a foreign org's project = %d, want 403", rec.Code)+ }+ if events := f.auditEvents(t); len(events) != 0 {+ t.Errorf("a foreign project write must not be recorded in this org, got %d", len(events))+ }+}++func TestAgentGate_jwtKinds(t *testing.T) {+ f := setupAgentFixture(t)+ f.setAgentWrites(t, true)++ session, err := services.GenerateToken(f.userId, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }+ if rec := f.archive(t, session); rec.Code != http.StatusOK {+ t.Fatalf("dashboard session archive = %d %s", rec.Code, rec.Body.String())+ }+ if rec := f.do(t, session, http.MethodGet, "/api/me/login-bundle", nil); rec.Code == http.StatusForbidden {+ t.Errorf("dashboard sessions must not be held to the agent allowlist")+ }+ if n := len(f.auditEvents(t)); n != 0 {+ t.Errorf("dashboard writes are not agent writes, got %d audit rows", n)+ }++ legacy := signTestJWT(t, f.userId, "", "", 15*time.Minute)+ if rec := f.archive(t, legacy); rec.Code != http.StatusForbidden {+ t.Errorf("unscoped 15-minute token archive = %d, want 403 (held to read)", rec.Code)+ }++ readOAuth := signTestJWT(t, f.userId, models.ScopeRead, "traceway-cli", 15*time.Minute)+ if rec := f.archive(t, readOAuth); rec.Code != http.StatusForbidden {+ t.Errorf("read OAuth token archive = %d, want 403", rec.Code)+ }++ writeOAuth := signTestJWT(t, f.userId, models.ScopeWrite, "traceway-cli-write", 15*time.Minute)+ if rec := f.archive(t, writeOAuth); rec.Code != http.StatusOK {+ t.Fatalf("write OAuth token archive = %d %s", rec.Code, rec.Body.String())+ }+ events := f.auditEvents(t)+ if len(events) != 1 || events[0].CredentialKind != middleware.CredentialOAuth || events[0].CredentialRef != "traceway-cli-write" {+ t.Errorf("OAuth write audit = %+v", events)+ }+}++func (f *agentFixture) member(t *testing.T, email, role string) (userId int, writeToken, session string) {+ t.Helper()+ user, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.User, error) {+ u, err := transactional.UserRepository.Create(tx, email, email, "x")+ if err != nil {+ return nil, err+ }+ _, err = transactional.OrganizationRepository.AddUser(tx, f.orgId, u.Id, role)+ return u, err+ })+ if err != nil {+ t.Fatalf("create member: %v", err)+ }+ writeToken = "tww_" + uuid.NewString()+ expires := time.Now().Add(time.Hour)+ _, err = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {+ return struct{}{}, transactional.PersonalAccessTokenRepository.Create(tx, uuid.NewString(), writeToken, writeToken[:12], user.Id, "member write", models.ScopeWrite, &expires)+ })+ if err != nil {+ t.Fatalf("create member pat: %v", err)+ }+ session, err = services.GenerateToken(user.Id, email)+ if err != nil {+ t.Fatal(err)+ }+ return user.Id, writeToken, session+}++func TestAgentGate_readonlyMemberWriteTokenStillNeedsWriteRole(t *testing.T) {+ f := setupAgentFixture(t)+ f.setAgentWrites(t, true)+ _, write, _ := f.member(t, "[email protected]", "readonly")++ rec := f.archive(t, write)+ if rec.Code != http.StatusForbidden {+ t.Fatalf("readonly member's write token archive = %d, want 403 from the role check after the gate", rec.Code)+ }+ events := f.auditEvents(t)+ if len(events) != 1 || events[0].StatusCode != http.StatusForbidden || events[0].UserEmail != "[email protected]" {+ t.Errorf("the refused write must be audited with its 403, got %+v", events)+ }+}++func TestAgentAccessSettings_adminOnly(t *testing.T) {+ f := setupAgentFixture(t)+ _, _, session := f.member(t, "[email protected]", "user")+ base := "/api/organizations/" + itoa(f.orgId)++ if rec := f.do(t, session, http.MethodPut, base+"/agent-access", map[string]any{"agentWriteEnabled": true}); rec.Code != http.StatusForbidden {+ t.Errorf("non-admin agent-access toggle = %d, want 403", rec.Code)+ }+ if rec := f.do(t, session, http.MethodGet, base+"/agent-activity", nil); rec.Code != http.StatusForbidden {+ t.Errorf("non-admin agent activity = %d, want 403", rec.Code)+ }+ enabled, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {+ return transactional.OrganizationRepository.GetAgentWriteEnabled(tx, f.orgId)+ })+ if err != nil || enabled {+ t.Errorf("agent writes enabled = %v (%v), want still off", enabled, err)+ }+}++func TestDeviceLookup_reportsRequestedScope(t *testing.T) {+ f := setupAgentFixture(t)+ session, err := services.GenerateToken(f.userId, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }+ for client, want := range map[string]string{"traceway-cli": models.ScopeRead, "traceway-cli-write": models.ScopeWrite} {+ da, err := authserver.CreateDeviceAuth(client, "http://localhost")+ if err != nil {+ t.Fatalf("create device auth for %s: %v", client, err)+ }+ rec := f.do(t, session, http.MethodGet, "/api/device?user_code="+url.QueryEscape(da.UserCode), nil)+ var body models.DeviceLookupResponse+ _ = json.Unmarshal(rec.Body.Bytes(), &body)+ if rec.Code != http.StatusOK || body.Scope != want {+ t.Errorf("%s lookup = %d scope %q, want %q (the approval screen's write warning depends on it)", client, rec.Code, body.Scope, want)+ }+ }+}++func TestAgentAccessSettings(t *testing.T) {+ f := setupAgentFixture(t)+ session, err := services.GenerateToken(f.userId, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }+ base := "/api/organizations/" + itoa(f.orgId)++ rec := f.do(t, session, http.MethodGet, base+"/settings", nil)+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"agentWriteEnabled":false`) {+ t.Fatalf("settings = %d %s", rec.Code, rec.Body.String())+ }+ if rec := f.do(t, session, http.MethodPut, base+"/agent-access", map[string]any{}); rec.Code != http.StatusUnprocessableEntity {+ t.Errorf("missing flag = %d, want 422", rec.Code)+ }+ if rec := f.do(t, session, http.MethodPut, base+"/agent-access", map[string]any{"agentWriteEnabled": true}); rec.Code != http.StatusOK {+ t.Fatalf("enable = %d %s", rec.Code, rec.Body.String())+ }+ if rec := f.do(t, session, http.MethodGet, base+"/settings", nil); !strings.Contains(rec.Body.String(), `"agentWriteEnabled":true`) {+ t.Errorf("settings after enable = %s", rec.Body.String())+ }++ write := f.pat(t, models.ScopeWrite)+ f.archive(t, write)+ rec = f.do(t, session, http.MethodGet, base+"/agent-activity", nil)+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"total":1`) {+ t.Errorf("agent activity = %d %s", rec.Code, rec.Body.String())+ }+}++func TestPATCreation_scopes(t *testing.T) {+ f := setupAgentFixture(t)+ session, err := services.GenerateToken(f.userId, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }+ days := 30+ tooLong := 120++ rec := f.do(t, session, http.MethodPost, "/api/personal-access-tokens", map[string]any{"name": "default"})+ if rec.Code != http.StatusCreated || !strings.Contains(rec.Body.String(), `"token":"twp_`) || !strings.Contains(rec.Body.String(), `"scope":"traceway:read"`) {+ t.Errorf("default PAT = %d %s", rec.Code, rec.Body.String())+ }+ rec = f.do(t, session, http.MethodPost, "/api/personal-access-tokens", map[string]any{"name": "w", "scope": "write", "expiresInDays": days})+ if rec.Code != http.StatusCreated || !strings.Contains(rec.Body.String(), `"token":"tww_`) {+ t.Errorf("write PAT = %d %s", rec.Code, rec.Body.String())+ }+ for _, body := range []map[string]any{+ {"name": "w", "scope": "write"},+ {"name": "w", "scope": "write", "expiresInDays": tooLong},+ {"name": "w", "scope": "admin"},+ } {+ if rec := f.do(t, session, http.MethodPost, "/api/personal-access-tokens", body); rec.Code != http.StatusUnprocessableEntity {+ t.Errorf("PAT %v = %d, want 422", body, rec.Code)+ }+ }+ rec = f.do(t, session, http.MethodGet, "/api/personal-access-tokens", nil)+ if !strings.Contains(rec.Body.String(), `"scope":"traceway:write"`) {+ t.Errorf("PAT list should carry scopes: %s", rec.Body.String())+ }+}++func TestPasswordLogin_scopedLoginIsARevocableTokenSet(t *testing.T) {+ f := setupAgentFixture(t)+ hash, err := services.HashPassword("cli-password-1")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.User, error) {+ return transactional.UserRepository.Create(tx, "[email protected]", "CLI User", hash)+ }); err != nil {+ t.Fatal(err)+ }++ rec := f.do(t, "", http.MethodPost, "/api/login", map[string]any{"email": "[email protected]", "password": "cli-password-1", "scope": models.ScopeWrite})+ if rec.Code != http.StatusOK {+ t.Fatalf("scoped login = %d %s", rec.Code, rec.Body.String())+ }+ var res struct {+ Token string `json:"token"`+ RefreshToken string `json:"refreshToken"`+ ExpiresIn int `json:"expiresIn"`+ }+ _ = json.Unmarshal(rec.Body.Bytes(), &res)+ claims, err := services.ValidateToken(res.Token)+ if err != nil {+ t.Fatalf("scoped login token: %v", err)+ }+ if claims.Scope != models.ScopeWrite || claims.ClientId != "traceway-cli-write" {+ t.Errorf("claims = scope %q cid %q, want the write scope from traceway-cli-write", claims.Scope, claims.ClientId)+ }+ if !strings.HasPrefix(res.RefreshToken, "twr_") || res.ExpiresIn <= 0 || res.ExpiresIn > 3600 {+ t.Errorf("scoped login must be a short access token plus a refresh token, got refresh %q expiresIn %d", res.RefreshToken, res.ExpiresIn)+ }++ if rec := f.do(t, "", http.MethodPost, "/api/auth/logout", map[string]any{"refresh_token": res.RefreshToken}); rec.Code != http.StatusOK {+ t.Fatalf("logout = %d %s", rec.Code, rec.Body.String())+ }+ if rec := f.do(t, "", http.MethodPost, "/api/auth/token", map[string]any{"grant_type": "refresh_token", "refresh_token": res.RefreshToken}); rec.Code != http.StatusBadRequest {+ t.Errorf("refresh after logout = %d %s, want 400", rec.Code, rec.Body.String())+ }++ rec = f.do(t, "", http.MethodPost, "/api/login", map[string]any{"email": "[email protected]", "password": "cli-password-1"})+ if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "refreshToken") {+ t.Errorf("an unscoped login stays a dashboard session: %d %s", rec.Code, rec.Body.String())+ }+}++func TestNotificationRuleToggle_explicitStateIsIdempotent(t *testing.T) {+ f := setupAgentFixture(t)+ f.setAgentWrites(t, true)+ now := time.Now().UTC()+ ruleId, err := db.ExecuteTransaction(func(tx *sql.Tx) (int, error) {+ channelId, err := transactional.NotificationChannelRepository.Create(tx, &models.NotificationChannel{ProjectId: f.project.Id, Name: "mail", ChannelType: "email", Config: json.RawMessage(`{}`), Enabled: true, CreatedAt: now, UpdatedAt: now})+ if err != nil {+ return 0, err+ }+ return transactional.NotificationRuleRepository.Create(tx, &models.NotificationRule{ProjectId: f.project.Id, ChannelId: channelId, Name: "p95", RuleType: "endpoint_p95_threshold", Config: json.RawMessage(`{}`), Enabled: true, Severity: "warning", CreatedAt: now, UpdatedAt: now})+ })+ if err != nil {+ t.Fatal(err)+ }+ path := "/api/notification-rules/" + itoa(ruleId) + "/toggle?projectId=" + f.project.Id.String()+ write := f.pat(t, models.ScopeWrite)+ session, err := services.GenerateToken(f.userId, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }++ for _, step := range []struct {+ name string+ token string+ body map[string]any+ want string+ }{+ {"enable an enabled rule", write, map[string]any{"enabled": true}, `"enabled":true`},+ {"disable", write, map[string]any{"enabled": false}, `"enabled":false`},+ {"disable again", write, map[string]any{"enabled": false}, `"enabled":false`},+ {"dashboard flip", session, map[string]any{}, `"enabled":true`},+ } {+ rec := f.do(t, step.token, http.MethodPost, path, step.body)+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), step.want) {+ t.Errorf("%s = %d %s, want %s", step.name, rec.Code, rec.Body.String(), step.want)+ }+ }+}++func TestPostMortemUpdate_staleExpectedUpdatedAtConflicts(t *testing.T) {+ f := setupAgentFixture(t)+ session, err := services.GenerateToken(f.userId, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }+ pm := createTestPostMortem(t, f.orgId, f.project.Id, "Outage", "draft", nil, nil)+ path := "/api/post-mortems/" + itoa(pm.Id) + "?projectId=" + f.project.Id.String()++ read := func() time.Time {+ t.Helper()+ var doc struct {+ UpdatedAt time.Time `json:"updatedAt"`+ }+ rec := f.do(t, session, http.MethodGet, path, nil)+ if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil || doc.UpdatedAt.IsZero() {+ t.Fatalf("get post-mortem = %d %s", rec.Code, rec.Body.String())+ }+ return doc.UpdatedAt+ }+ seen := read()++ if rec := f.do(t, session, http.MethodPut, path, map[string]any{"title": "Outage", "contentMd": "edited in the dashboard", "tags": []string{}}); rec.Code != http.StatusOK {+ t.Fatalf("dashboard update = %d %s", rec.Code, rec.Body.String())+ }+ if rec := f.do(t, session, http.MethodPut, path, map[string]any{"title": "Outage", "contentMd": "agent edit", "tags": []string{}, "expectedUpdatedAt": seen}); rec.Code != http.StatusConflict {+ t.Fatalf("update from a stale read = %d %s, want 409", rec.Code, rec.Body.String())+ }+ if rec := f.do(t, session, http.MethodPut, path, map[string]any{"title": "Outage", "contentMd": "agent edit", "tags": []string{}, "expectedUpdatedAt": read()}); rec.Code != http.StatusOK {+ t.Fatalf("update from a fresh read = %d %s", rec.Code, rec.Body.String())+ }+}++func itoa(n int) string {+ b, _ := json.Marshal(n)+ return string(b)+}diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.goindex 12a3c310..280976e8 100644--- a/backend/app/controllers/auth.controller.go+++ b/backend/app/controllers/auth.controller.go@@ -9,6 +9,7 @@ import ("github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services"+ "github.com/tracewayapp/traceway/backend/app/services/authserver""net/http""github.com/gin-gonic/gin"@@ -62,7 +63,22 @@ func (a authController) Login(c *gin.Context) {return}- token, err := services.GenerateToken(user.Id, user.Email)+ response := &models.LoginResponse{User: user.ToResponse()}+ switch request.Scope {+ case "":+ response.Token, err = services.GenerateToken(user.Id, user.Email)+ case models.ScopeRead, models.ScopeWrite:+ // An agent login gets the device flow's short access token and a+ // refresh family, so logout revokes it like any CLI session.+ var set *models.TokenSetResponse+ set, err = authserver.IssueTokenSet(tx, user.Id, user.Email, passwordLoginClientID(request.Scope), request.Scope)+ if err == nil {+ response.Token, response.RefreshToken, response.ExpiresIn = set.AccessToken, set.RefreshToken, set.ExpiresIn+ }+ default:+ c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown scope"})+ return+ }if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -80,12 +96,16 @@ func (a authController) Login(c *gin.Context) {return}- c.JSON(http.StatusOK, &models.LoginResponse{- Token: token,- User: user.ToResponse(),- Projects: projects,- Organizations: organizations,- })+ response.Projects = projects+ response.Organizations = organizations+ c.JSON(http.StatusOK, response)+}++func passwordLoginClientID(scope string) string {+ if scope == models.ScopeWrite {+ return "traceway-cli-write"+ }+ return "traceway-cli"}func (a authController) Register(c *gin.Context) {diff --git a/backend/app/controllers/device_auth.controller.go b/backend/app/controllers/device_auth.controller.goindex 373cac42..9eba3aa2 100644--- a/backend/app/controllers/device_auth.controller.go+++ b/backend/app/controllers/device_auth.controller.go@@ -118,6 +118,7 @@ func (c *deviceAuthController) Lookup(ctx *gin.Context) {UserCode: da.UserCode,Status: da.Status,ClientName: clientDisplayName(da.ClientId),+ Scope: authserver.DeviceClientScope(da.ClientId),RequestedAt: da.CreatedAt,ExpiresAt: da.ExpiresAt,})@@ -202,6 +203,8 @@ func clientDisplayName(clientId string) string {return "Traceway CLI"case "traceway-mcp":return "Traceway MCP"+ case "traceway-cli-write":+ return "Traceway Write CLI"default:return "An unrecognized application"}diff --git a/backend/app/controllers/notification_rule.controller.go b/backend/app/controllers/notification_rule.controller.goindex 5cbfa3e7..862fdd2a 100644--- a/backend/app/controllers/notification_rule.controller.go+++ b/backend/app/controllers/notification_rule.controller.go@@ -2,6 +2,8 @@ package controllersimport ("encoding/json"+ "errors"+ "io""net/http""strconv""strings"@@ -271,6 +273,10 @@ func (ctrl *notificationRuleController) Delete(ctx *gin.Context) {ctx.JSON(http.StatusOK, gin.H{"deleted": true})}+type toggleRequest struct {+ Enabled *bool `json:"enabled"`+}+func (ctrl *notificationRuleController) Toggle(ctx *gin.Context) {projectId, err := middleware.GetProjectId(ctx)if err != nil {@@ -296,7 +302,17 @@ func (ctrl *notificationRuleController) Toggle(ctx *gin.Context) {return}+ // An explicit enabled makes the call idempotent (agents set a state);+ // the dashboard sends an empty body and flips the rule.+ var req toggleRequest+ if err := ctx.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {+ middleware.RejectBindError(ctx, err, "Invalid request body")+ return+ }newEnabled := !existing.Enabled+ if req.Enabled != nil {+ newEnabled = *req.Enabled+ }if err := transactional.NotificationRuleRepository.UpdateEnabled(tx, id, newEnabled); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle notification rule: %w", err))returndiff --git a/backend/app/controllers/organization.controller.go b/backend/app/controllers/organization.controller.goindex 8cc8fcf5..c60920fb 100644--- a/backend/app/controllers/organization.controller.go+++ b/backend/app/controllers/organization.controller.go@@ -28,6 +28,7 @@ func (c *organizationController) GetSettings(ctx *gin.Context) {Organization *models.OrganizationMembers []*models.OrganizationMemberInvitations []*models.InvitationWithInviter+ AgentWrite bool}data, err := db.ExecuteTransaction(func(tx *sql.Tx) (*settingsData, error) {@@ -46,10 +47,16 @@ func (c *organizationController) GetSettings(ctx *gin.Context) {return nil, err}+ agentWrite, err := transactional.OrganizationRepository.GetAgentWriteEnabled(tx, organizationId)+ if err != nil {+ return nil, err+ }+return &settingsData{Organization: org,Members: members,Invitations: invitations,+ AgentWrite: agentWrite,}, nil})@@ -64,10 +71,50 @@ func (c *organizationController) GetSettings(ctx *gin.Context) {}ctx.JSON(http.StatusOK, &models.OrganizationSettingsResponse{- Organization: data.Organization,- Members: data.Members,- Invitations: data.Invitations,- UserRole: userRole,+ Organization: data.Organization,+ Members: data.Members,+ Invitations: data.Invitations,+ UserRole: userRole,+ AgentWriteEnabled: data.AgentWrite,+ })+}++func (c *organizationController) UpdateAgentAccess(ctx *gin.Context) {+ organizationId := middleware.GetOrganizationId(ctx)+ tx := db.GetTx(ctx)++ var req models.UpdateAgentAccessRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ middleware.RejectBindError(ctx, err, "Invalid request")+ return+ }+ if req.AgentWriteEnabled == nil {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "agentWriteEnabled is required"})+ return+ }++ if err := transactional.OrganizationRepository.SetAgentWriteEnabled(tx, organizationId, *req.AgentWriteEnabled); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update agent access: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"agentWriteEnabled": *req.AgentWriteEnabled})+}++func (c *organizationController) AgentActivity(ctx *gin.Context) {+ organizationId := middleware.GetOrganizationId(ctx)+ tx := db.GetTx(ctx)+ page, pageSize := paginationFromQuery(ctx)++ events, total, err := transactional.AgentWriteEventRepository.ListByOrganization(tx, organizationId, page, pageSize)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load agent activity: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, PaginatedResponse[*models.AgentWriteEvent]{+ Data: events,+ Pagination: buildPagination(page, pageSize, total),})}diff --git a/backend/app/controllers/pat.controller.go b/backend/app/controllers/pat.controller.goindex 1a305588..25663f07 100644--- a/backend/app/controllers/pat.controller.go+++ b/backend/app/controllers/pat.controller.go@@ -42,7 +42,17 @@ func (c *patController) Create(ctx *gin.Context) {return}- token := authserver.NewPATToken()+ scope, ok := parsePATScope(req.Scope)+ if !ok {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Access must be read or write"})+ return+ }+ if scope == models.ScopeWrite && (req.ExpiresInDays == nil || *req.ExpiresInDays < 1 || *req.ExpiresInDays > maxWritePATDays) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Write tokens must expire within 90 days"})+ return+ }++ token := authserver.NewPATToken(scope)id := uuid.New().String()prefix := patPrefix(token)@@ -52,7 +62,7 @@ func (c *patController) Create(ctx *gin.Context) {expiresAt = &t}- if err := transactional.PersonalAccessTokenRepository.Create(tx, id, token, prefix, userId, name, expiresAt); err != nil {+ if err := transactional.PersonalAccessTokenRepository.Create(tx, id, token, prefix, userId, name, scope, expiresAt); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("create pat: %w", err))return}@@ -62,6 +72,7 @@ func (c *patController) Create(ctx *gin.Context) {Name: name,Prefix: prefix,Token: token,+ Scope: scope,CreatedAt: time.Now().UTC(),ExpiresAt: expiresAt,})@@ -95,6 +106,18 @@ func (c *patController) Revoke(ctx *gin.Context) {ctx.JSON(http.StatusOK, gin.H{"status": "revoked"})}+const maxWritePATDays = 90++func parsePATScope(raw string) (string, bool) {+ switch strings.TrimSpace(raw) {+ case "", "read", models.ScopeRead:+ return models.ScopeRead, true+ case "write", models.ScopeWrite:+ return models.ScopeWrite, true+ }+ return "", false+}+func patPrefix(token string) string {if len(token) <= 12 {return tokendiff --git a/backend/app/controllers/post_mortem.controller.go b/backend/app/controllers/post_mortem.controller.goindex 6261a168..8897be63 100644--- a/backend/app/controllers/post_mortem.controller.go+++ b/backend/app/controllers/post_mortem.controller.go@@ -34,6 +34,10 @@ type postMortemRequest struct {ContentMd string `json:"contentMd"`Tags []string `json:"tags"`IncidentId *int `json:"incidentId"`+ // ExpectedUpdatedAt, on update, is the updatedAt the caller read: a+ // document changed since then answers 409 instead of being overwritten.+ // The CLI and MCP send it because they merge into a document they read.+ ExpectedUpdatedAt *time.Time `json:"expectedUpdatedAt"`}func normalizePostMortemTags(tags []string) (models.StringSlice, string) {@@ -283,6 +287,10 @@ func (ctrl *postMortemController) Update(ctx *gin.Context) {return}tx := db.GetTx(ctx)+ if err := transactional.PostMortemRepository.LockForUpdate(tx, id, projectId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to lock post-mortem: %w", err))+ return+ }postMortem, err := transactional.PostMortemRepository.FindByIdForProject(tx, id, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load post-mortem: %w", err))@@ -292,6 +300,10 @@ func (ctrl *postMortemController) Update(ctx *gin.Context) {ctx.JSON(http.StatusNotFound, gin.H{"error": "Post-mortem not found"})return}+ if req.ExpectedUpdatedAt != nil && !postMortem.UpdatedAt.Equal(*req.ExpectedUpdatedAt) {+ ctx.JSON(http.StatusConflict, gin.H{"error": "The post-mortem was changed since it was read. Read it again and reapply the change."})+ return+ }tags, message := validatePostMortemRequest(&req)if message != "" {ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": message})diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 0c91f539..c0d2933d 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -235,6 +235,8 @@ func RegisterControllers(router *gin.RouterGroup) {router.GET("/organizations/:organizationId/settings", middleware.UseAppAuth, middleware.RequireAdminAccess, OrganizationController.GetSettings)router.PUT("/organizations/:organizationId/settings", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, OrganizationController.UpdateSettings)router.GET("/organizations/:organizationId/members", middleware.UseAppAuth, middleware.RequireAdminAccess, OrganizationController.GetMembers)+ router.PUT("/organizations/:organizationId/agent-access", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, OrganizationController.UpdateAgentAccess)+ router.GET("/organizations/:organizationId/agent-activity", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, OrganizationController.AgentActivity)router.PUT("/organizations/:organizationId/members/:userId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, MemberController.UpdateRole)router.DELETE("/organizations/:organizationId/members/:userId", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, MemberController.RemoveMember)diff --git a/backend/app/controllers/routes_test.go b/backend/app/controllers/routes_test.goindex 3fa55613..2eabdabe 100644--- a/backend/app/controllers/routes_test.go+++ b/backend/app/controllers/routes_test.go@@ -6,6 +6,7 @@ import ("github.com/gin-gonic/gin""github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/middleware")// Gin panics at registration when a new path conflicts with an existing@@ -30,3 +31,27 @@ func TestRouteTreeRegistersWithoutConflict(t *testing.T) {t.Error("POST /api/organizations was not registered")}}++// A renamed route would silently drop out of the agent allowlist, so every+// entry must still name a registered route.+func TestAgentRoutesAreRegistered(t *testing.T) {+ gin.SetMode(gin.TestMode)++ if config.Config == nil {+ config.Init(&config.Cfg{})+ t.Cleanup(func() { config.Init(nil) })+ }++ engine := gin.New()+ RegisterControllers(engine.Group("/api"))++ registered := map[string]bool{}+ for _, r := range engine.Routes() {+ registered[r.Method+" "+r.Path] = true+ }+ for _, key := range middleware.AgentRouteKeys() {+ if !registered[key] {+ t.Errorf("agent allowlist names %q, which is not a registered route", key)+ }+ }+}diff --git a/backend/app/controllers/wellknown.controller.go b/backend/app/controllers/wellknown.controller.goindex 89fa52e6..c799b2d7 100644--- a/backend/app/controllers/wellknown.controller.go+++ b/backend/app/controllers/wellknown.controller.go@@ -5,6 +5,7 @@ import ("github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/services/authserver""github.com/tracewayapp/traceway/backend/app/services/mcpmount")@@ -23,6 +24,7 @@ func (c *wellKnownController) AuthorizationServer(ctx *gin.Context) {"response_types_supported": []string{"code"},"code_challenge_methods_supported": []string{"S256"},"token_endpoint_auth_methods_supported": []string{"none"},+ "scopes_supported": []string{models.ScopeRead, models.ScopeWrite},})}@@ -31,6 +33,7 @@ func (c *wellKnownController) ProtectedResource(ctx *gin.Context) {ctx.JSON(http.StatusOK, gin.H{"resource": issuer,"authorization_servers": []string{issuer},+ "scopes_supported": []string{models.ScopeRead, models.ScopeWrite},})}@@ -39,6 +42,16 @@ func (c *wellKnownController) ProtectedResourceMCP(ctx *gin.Context) {ctx.JSON(http.StatusOK, gin.H{"resource": issuer + mcpmount.Path,"authorization_servers": []string{issuer},+ "scopes_supported": []string{models.ScopeRead},+ })+}++func (c *wellKnownController) ProtectedResourceMCPWrite(ctx *gin.Context) {+ issuer := authserver.IssuerBaseURLFromRequest(ctx)+ ctx.JSON(http.StatusOK, gin.H{+ "resource": issuer + mcpmount.WritePath,+ "authorization_servers": []string{issuer},+ "scopes_supported": []string{models.ScopeWrite},})}diff --git a/backend/app/middleware/agent_gate.go b/backend/app/middleware/agent_gate.gonew file mode 100644index 00000000..b908ae06--- /dev/null+++ b/backend/app/middleware/agent_gate.go@@ -0,0 +1,94 @@+package middleware++import (+ "database/sql"+ "fmt"+ "net/http"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ traceway "go.tracewayapp.com"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+)++const (+ agentRouteForbiddenMessage = "This endpoint is not available to personal access tokens, the CLI, or MCP clients. Use the Traceway dashboard."+ agentWriteScopeMessage = "This credential is read-only. Writes need a write token: create one in the dashboard, or log in with traceway-write."+ agentWriteDisabledMessage = "Agent write access is turned off for this organization. An organization admin can turn it on in Settings > Agent Access."+)++func authorizeAgentRequest(c *gin.Context, identity *BearerIdentity) {+ access, ok := agentRouteAccess(c.Request.Method, c.FullPath())+ if !ok {+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": agentRouteForbiddenMessage})+ return+ }+ if access == agentRead {+ c.Next()+ return+ }++ if identity.Scope != models.ScopeWrite {+ c.Header("WWW-Authenticate", fmt.Sprintf(`Bearer error="insufficient_scope", scope=%q`, models.ScopeWrite))+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": agentWriteScopeMessage})+ return+ }++ projectId := extractProjectId(c)+ if projectId == uuid.Nil {+ c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "projectId is required"})+ return+ }++ type policy struct {+ organizationId int+ enabled bool+ found bool+ }+ p, err := db.ExecuteTransaction(func(tx *sql.Tx) (policy, error) {+ orgId, enabled, found, err := transactional.OrganizationRepository.AgentWritePolicyForProject(tx, projectId, identity.UserId)+ return policy{orgId, enabled, found}, err+ })+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("resolve agent write policy: %w", err))+ return+ }+ if !p.found {+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "You do not have access to this project"})+ return+ }+ if !p.enabled {+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": agentWriteDisabledMessage})+ recordAgentWrite(c, identity, p.organizationId, projectId)+ return+ }++ c.Next()+ recordAgentWrite(c, identity, p.organizationId, projectId)+}++func recordAgentWrite(c *gin.Context, identity *BearerIdentity, organizationId int, projectId uuid.UUID) {+ event := &models.AgentWriteEvent{+ Id: uuid.New().String(),+ OrganizationId: organizationId,+ ProjectId: projectId.String(),+ UserId: identity.UserId,+ CredentialKind: identity.CredentialKind,+ CredentialRef: identity.CredentialRef,+ Method: c.Request.Method,+ Route: c.FullPath(),+ Path: c.Request.URL.Path,+ StatusCode: c.Writer.Status(),+ CreatedAt: time.Now().UTC(),+ }+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {+ return struct{}{}, transactional.AgentWriteEventRepository.Insert(tx, event)+ })+ if err != nil {+ traceway.CaptureException(fmt.Errorf("record agent write event (route=%s): %w", event.Route, err))+ }+}diff --git a/backend/app/middleware/agent_routes.go b/backend/app/middleware/agent_routes.gonew file mode 100644index 00000000..f8e5f95c--- /dev/null+++ b/backend/app/middleware/agent_routes.go@@ -0,0 +1,143 @@+package middleware++type agentAccess int++const (+ agentRead agentAccess = iota + 1+ agentWrite+)++// agentRoutes is the complete surface reachable with an agent credential+// (personal access tokens and CLI/MCP OAuth tokens). Anything missing is+// denied, so a new dashboard route is never exposed to agents by accident.+// Every write here is project-scoped, which is what lets the gate resolve the+// owning organization's opt-in from the projectId query parameter.+var agentRoutes = map[string]agentAccess{+ "GET /api/projects": agentRead,++ "GET /api/dashboard": agentRead,+ "GET /api/dashboard/overview": agentRead,+ "GET /api/metrics/application": agentRead,+ "GET /api/metrics/stats": agentRead,+ "GET /api/metrics/server": agentRead,+ "POST /api/metrics/query": agentRead,+ "GET /api/metrics/discover": agentRead,+ "GET /api/metrics/discover/tags": agentRead,+ "GET /api/metrics/discover/instances": agentRead,+ "GET /api/metrics/discover/org": agentRead,++ "GET /api/dashboards": agentRead,+ "GET /api/dashboards/library": agentRead,+ "GET /api/dashboards/starred": agentRead,+ "GET /api/dashboards/:id": agentRead,+ "GET /api/dashboards/:id/export": agentRead,+ "GET /api/dashboard-templates": agentRead,++ "POST /api/endpoints": agentRead,+ "POST /api/endpoints/grouped": agentRead,+ "POST /api/endpoints/endpoint": agentRead,+ "POST /api/endpoints/chart": agentRead,+ "GET /api/endpoints/slow": agentRead,+ "POST /api/endpoints/:endpointId": agentRead,+ "POST /api/endpoints/slow": agentWrite,++ "POST /api/tasks": agentRead,+ "POST /api/tasks/grouped": agentRead,+ "POST /api/tasks/task": agentRead,+ "POST /api/tasks/:taskId": agentRead,++ "POST /api/sessions": agentRead,+ "POST /api/sessions/:sessionId": agentRead,++ "POST /api/profiles/grouped": agentRead,+ "POST /api/profiles/series": agentRead,+ "POST /api/profiles/series/breakdown": agentRead,+ "POST /api/profiles/dimensions": agentRead,+ "POST /api/profiles/types": agentRead,+ "POST /api/profiles/flamegraph": agentRead,+ "POST /api/profiles/top": agentRead,+ "POST /api/profiles/labels": agentRead,++ "POST /api/ai-traces/grouped": agentRead,+ "POST /api/ai-traces/trace": agentRead,+ "POST /api/ai-traces/:traceId": agentRead,+ "POST /api/ai-conversations/grouped": agentRead,+ "POST /api/ai-conversations/conversation": agentRead,+ "POST /api/ai-users/grouped": agentRead,++ "POST /api/distributed-traces/:traceId": agentRead,+ "GET /api/otel/spans/:traceId/:spanId": agentRead,+ "POST /api/spans/search": agentRead,+ "GET /api/spans/traces/:traceId": agentRead,+ "GET /api/spans/traces/:traceId/spans/:spanId/attributes": agentRead,++ "POST /api/logs": agentRead,++ "POST /api/exception-stack-traces": agentRead,+ "POST /api/exception-stack-traces/by-id/:exceptionId": agentRead,+ "POST /api/exception-stack-traces/:hash": agentRead,+ "POST /api/exception-stack-traces/archive": agentWrite,+ "POST /api/exception-stack-traces/unarchive": agentWrite,++ "GET /api/notification-rules": agentRead,+ "POST /api/notification-history": agentRead,+ "POST /api/notification-rules/:id/toggle": agentWrite,+ "POST /api/notification-rules/:id/snooze": agentWrite,++ "GET /api/synthetics/checks": agentRead,+ "POST /api/synthetics/overview": agentRead,+ "GET /api/synthetics/checks/:id": agentRead,+ "POST /api/synthetics/checks/:id/results": agentRead,+ "POST /api/synthetics/checks/:id/series": agentRead,+ "GET /api/synthetics/open-count": agentRead,+ "POST /api/synthetics/checks/:id/run": agentWrite,++ "GET /api/organizations/:organizationId/overview/servers": agentRead,+ "POST /api/organizations/:organizationId/overview/issues": agentRead,+ "POST /api/organizations/:organizationId/overview/pages": agentRead,+ "GET /api/organizations/:organizationId/overview/counts": agentRead,+ "POST /api/organizations/:organizationId/overview/incidents": agentRead,+ "GET /api/organizations/:organizationId/overview/monitors": agentRead,++ "GET /api/organizations/:organizationId/status-pages": agentRead,+ "GET /api/organizations/:organizationId/incidents": agentRead,+ "GET /api/organizations/:organizationId/incidents/:incidentId/updates": agentRead,+ "GET /api/organizations/:organizationId/status-pages/:id/incidents": agentRead,++ "GET /api/post-mortems": agentRead,+ "GET /api/post-mortems/:id": agentRead,+ "GET /api/post-mortems/:id/activity": agentRead,+ "POST /api/post-mortems": agentWrite,+ "PUT /api/post-mortems/:id": agentWrite,++ "GET /api/organizations/:organizationId/teams": agentRead,+ "GET /api/organizations/:organizationId/schedules": agentRead,+ "GET /api/organizations/:organizationId/schedules/:scheduleId": agentRead,+ "GET /api/organizations/:organizationId/schedules/:scheduleId/timeline": agentRead,+ "GET /api/organizations/:organizationId/oncall/now": agentRead,+ "GET /api/oncall/current": agentRead,+ "GET /api/escalation-policies": agentRead,+ "GET /api/organizations/:organizationId/escalation-policies": agentRead,++ "POST /api/pages": agentRead,+ "POST /api/pages/for-issues": agentRead,+ "GET /api/pages/open-count": agentRead,+ "GET /api/pages/:id": agentRead,+ "POST /api/pages/:id/acknowledge": agentWrite,+ "POST /api/pages/:id/resolve": agentWrite,+}++func agentRouteAccess(method, fullPath string) (agentAccess, bool) {+ access, ok := agentRoutes[method+" "+fullPath]+ return access, ok+}++// AgentRouteKeys lists the allowlist as "METHOD /path" keys, so the route+// tree test can prove every entry names a registered route.+func AgentRouteKeys() []string {+ keys := make([]string, 0, len(agentRoutes))+ for k := range agentRoutes {+ keys = append(keys, k)+ }+ return keys+}diff --git a/backend/app/middleware/use_app_auth.middleware.go b/backend/app/middleware/use_app_auth.middleware.goindex 0649f208..321d9002 100644--- a/backend/app/middleware/use_app_auth.middleware.go+++ b/backend/app/middleware/use_app_auth.middleware.go@@ -8,6 +8,7 @@ import ("time""github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services"traceway "go.tracewayapp.com"@@ -46,6 +47,12 @@ func InitUseAppAuth() {c.Set(UserIdContextKey, identity.UserId)c.Set(UserEmailContextKey, identity.Email)+ c.Set(BearerIdentityContextKey, identity)++ if identity.IsAgent() {+ authorizeAgentRequest(c, identity)+ return+ }c.Next()}@@ -53,14 +60,43 @@ func InitUseAppAuth() {var ErrInvalidBearer = errors.New("invalid bearer token")+const BearerIdentityContextKey = "bearerIdentity"++const (+ CredentialSession = "session"+ CredentialPAT = "pat"+ CredentialOAuth = "oauth"+)++// legacyAgentTokenLifetime separates the access tokens minted before scopes+// existed (15 minutes, device and OAuth grants) from dashboard sessions (7+// days): an unscoped JWT this short-lived came from the CLI or an MCP client+// and is held to read access instead of being trusted as a session.+const legacyAgentTokenLifetime = time.Hour+type BearerIdentity struct {- UserId int- Email string- Expires time.Time+ UserId int+ Email string+ Expires time.Time+ Scope string+ CredentialKind string+ CredentialRef string+}++func (b *BearerIdentity) IsAgent() bool {+ return b.CredentialKind != CredentialSession+}++// HasAgentWriteScope reports whether this is an agent credential carrying the+// write scope. A dashboard session never qualifies: MCP is an agent surface,+// and a session behind /mcp/write would skip the agent gate's organization+// opt-in and audit log, since sessions bypass the gate.+func (b *BearerIdentity) HasAgentWriteScope() bool {+ return b.IsAgent() && b.Scope == models.ScopeWrite}func AuthenticateBearer(tokenString string) (*BearerIdentity, error) {- if strings.HasPrefix(tokenString, "twp_") {+ if strings.HasPrefix(tokenString, "twp_") || strings.HasPrefix(tokenString, "tww_") {pat, err := transactional.PersonalAccessTokenRepository.FindActiveByToken(db.DB, tokenString)if err != nil {return nil, err@@ -69,20 +105,38 @@ func AuthenticateBearer(tokenString string) (*BearerIdentity, error) {return nil, ErrInvalidBearer}touchPersonalAccessToken(pat)- return &BearerIdentity{UserId: pat.UserId, Email: pat.Email}, nil+ return &BearerIdentity{UserId: pat.UserId, Email: pat.Email, Scope: pat.Scope, CredentialKind: CredentialPAT, CredentialRef: pat.Id}, nil}claims, err := services.ValidateToken(tokenString)if err != nil {return nil, ErrInvalidBearer}- identity := &BearerIdentity{UserId: claims.UserId, Email: claims.Email}+ identity := &BearerIdentity{UserId: claims.UserId, Email: claims.Email, CredentialKind: CredentialSession}if claims.ExpiresAt != nil {identity.Expires = claims.ExpiresAt.Time}+ switch {+ case claims.Scope != "":+ identity.Scope = claims.Scope+ identity.CredentialKind = CredentialOAuth+ identity.CredentialRef = claims.ClientId+ case claims.ExpiresAt != nil && claims.IssuedAt != nil && claims.ExpiresAt.Sub(claims.IssuedAt.Time) <= legacyAgentTokenLifetime:+ identity.Scope = models.ScopeRead+ identity.CredentialKind = CredentialOAuth+ }return identity, nil}+func GetBearerIdentity(c *gin.Context) *BearerIdentity {+ if v, ok := c.Get(BearerIdentityContextKey); ok {+ if identity, ok := v.(*BearerIdentity); ok {+ return identity+ }+ }+ return nil+}+func touchPersonalAccessToken(pat *transactional.ActivePAT) {now := time.Now()if pat.LastUsedAt != nil && now.Sub(*pat.LastUsedAt) < patTouchInterval {diff --git a/backend/app/migrations/pg/0144_add_scope_to_personal_access_tokens.up.sql b/backend/app/migrations/pg/0144_add_scope_to_personal_access_tokens.up.sqlnew file mode 100644index 00000000..d0c996f4--- /dev/null+++ b/backend/app/migrations/pg/0144_add_scope_to_personal_access_tokens.up.sql@@ -0,0 +1 @@+ALTER TABLE personal_access_tokens ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'traceway:read'diff --git a/backend/app/migrations/pg/0145_add_scope_to_refresh_tokens.up.sql b/backend/app/migrations/pg/0145_add_scope_to_refresh_tokens.up.sqlnew file mode 100644index 00000000..ff2156ec--- /dev/null+++ b/backend/app/migrations/pg/0145_add_scope_to_refresh_tokens.up.sql@@ -0,0 +1 @@+ALTER TABLE refresh_tokens ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'traceway:read'diff --git a/backend/app/migrations/pg/0146_add_scope_to_authorization_codes.up.sql b/backend/app/migrations/pg/0146_add_scope_to_authorization_codes.up.sqlnew file mode 100644index 00000000..507d730e--- /dev/null+++ b/backend/app/migrations/pg/0146_add_scope_to_authorization_codes.up.sql@@ -0,0 +1 @@+ALTER TABLE authorization_codes ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'traceway:read'diff --git a/backend/app/migrations/pg/0147_add_agent_write_enabled_to_organizations.up.sql b/backend/app/migrations/pg/0147_add_agent_write_enabled_to_organizations.up.sqlnew file mode 100644index 00000000..af4d34b3--- /dev/null+++ b/backend/app/migrations/pg/0147_add_agent_write_enabled_to_organizations.up.sql@@ -0,0 +1 @@+ALTER TABLE organizations ADD COLUMN IF NOT EXISTS agent_write_enabled BOOLEAN NOT NULL DEFAULT FALSEdiff --git a/backend/app/migrations/pg/0148_create_agent_write_events.up.sql b/backend/app/migrations/pg/0148_create_agent_write_events.up.sqlnew file mode 100644index 00000000..7ecec3f5--- /dev/null+++ b/backend/app/migrations/pg/0148_create_agent_write_events.up.sql@@ -0,0 +1,13 @@+CREATE TABLE IF NOT EXISTS agent_write_events (+ id TEXT PRIMARY KEY,+ organization_id INTEGER NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ project_id TEXT NOT NULL,+ user_id INTEGER NOT NULL,+ credential_kind TEXT NOT NULL,+ credential_ref TEXT NOT NULL,+ method TEXT NOT NULL,+ route TEXT NOT NULL,+ path TEXT NOT NULL,+ status_code INTEGER NOT NULL,+ created_at TIMESTAMPTZ NOT NULL+)diff --git a/backend/app/migrations/pg/0149_create_agent_write_events_org_idx.up.sql b/backend/app/migrations/pg/0149_create_agent_write_events_org_idx.up.sqlnew file mode 100644index 00000000..36aff5db--- /dev/null+++ b/backend/app/migrations/pg/0149_create_agent_write_events_org_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS idx_agent_write_events_org_created ON agent_write_events(organization_id, created_at)diff --git a/backend/app/migrations/sqlite/0078_add_scope_to_auth_tokens.up.sql b/backend/app/migrations/sqlite/0078_add_scope_to_auth_tokens.up.sqlnew file mode 100644index 00000000..beda481a--- /dev/null+++ b/backend/app/migrations/sqlite/0078_add_scope_to_auth_tokens.up.sql@@ -0,0 +1,3 @@+ALTER TABLE personal_access_tokens ADD COLUMN scope TEXT NOT NULL DEFAULT 'traceway:read';+ALTER TABLE refresh_tokens ADD COLUMN scope TEXT NOT NULL DEFAULT 'traceway:read';+ALTER TABLE authorization_codes ADD COLUMN scope TEXT NOT NULL DEFAULT 'traceway:read';diff --git a/backend/app/migrations/sqlite/0079_add_agent_write_enabled_to_organizations.up.sql b/backend/app/migrations/sqlite/0079_add_agent_write_enabled_to_organizations.up.sqlnew file mode 100644index 00000000..a21d9ad1--- /dev/null+++ b/backend/app/migrations/sqlite/0079_add_agent_write_enabled_to_organizations.up.sql@@ -0,0 +1 @@+ALTER TABLE organizations ADD COLUMN agent_write_enabled INTEGER NOT NULL DEFAULT 0;diff --git a/backend/app/migrations/sqlite/0080_create_agent_write_events.up.sql b/backend/app/migrations/sqlite/0080_create_agent_write_events.up.sqlnew file mode 100644index 00000000..bae9579d--- /dev/null+++ b/backend/app/migrations/sqlite/0080_create_agent_write_events.up.sql@@ -0,0 +1,15 @@+CREATE TABLE IF NOT EXISTS agent_write_events (+ id TEXT PRIMARY KEY,+ organization_id INTEGER NOT NULL,+ project_id TEXT NOT NULL,+ user_id INTEGER NOT NULL,+ credential_kind TEXT NOT NULL,+ credential_ref TEXT NOT NULL,+ method TEXT NOT NULL,+ route TEXT NOT NULL,+ path TEXT NOT NULL,+ status_code INTEGER NOT NULL,+ created_at DATETIME NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_agent_write_events_org_created ON agent_write_events(organization_id, created_at);diff --git a/backend/app/models/agent_write_event.model.go b/backend/app/models/agent_write_event.model.gonew file mode 100644index 00000000..b51174d8--- /dev/null+++ b/backend/app/models/agent_write_event.model.go@@ -0,0 +1,24 @@+package models++import "time"++type AgentWriteEvent struct {+ Id string `json:"id"`+ OrganizationId int `json:"organizationId"`+ ProjectId string `json:"projectId"`+ ProjectName string `json:"projectName"`+ UserId int `json:"userId"`+ UserEmail string `json:"userEmail"`+ CredentialKind string `json:"credentialKind"`+ CredentialRef string `json:"credentialRef"`+ CredentialName string `json:"credentialName"`+ Method string `json:"method"`+ Route string `json:"route"`+ Path string `json:"path"`+ StatusCode int `json:"statusCode"`+ CreatedAt time.Time `json:"createdAt"`+}++type UpdateAgentAccessRequest struct {+ AgentWriteEnabled *bool `json:"agentWriteEnabled"`+}diff --git a/backend/app/models/auth.model.go b/backend/app/models/auth.model.goindex a7c68011..2917a9b0 100644--- a/backend/app/models/auth.model.go+++ b/backend/app/models/auth.model.go@@ -3,6 +3,9 @@ package modelstype LoginRequest struct {Email string `json:"email" binding:"required,email"`Password string `json:"password" binding:"required"`+ // Scope turns the login into an agent credential (the CLI's password+ // login) instead of a dashboard session.+ Scope string `json:"scope"`}type UserOrganizationResponse struct {@@ -13,7 +16,11 @@ type UserOrganizationResponse struct {}type LoginResponse struct {- Token string `json:"token"`+ Token string `json:"token"`+ // RefreshToken and ExpiresIn are set only on a scoped login, whose Token+ // is then a short-lived access token in a revocable refresh family.+ RefreshToken string `json:"refreshToken,omitempty"`+ ExpiresIn int `json:"expiresIn,omitempty"`User UserResponse `json:"user"`Projects []*ProjectWithBackendUrl `json:"projects"`Organizations []*UserOrganizationResponse `json:"organizations"`diff --git a/backend/app/models/auth_token.model.go b/backend/app/models/auth_token.model.goindex 516f2d3b..2c56493f 100644--- a/backend/app/models/auth_token.model.go+++ b/backend/app/models/auth_token.model.go@@ -1,6 +1,23 @@package models-import "time"+import (+ "strings"+ "time"+)++const (+ ScopeRead = "traceway:read"+ ScopeWrite = "traceway:write"+)++func ParseRequestedScope(raw string) string {+ for _, s := range strings.Fields(raw) {+ if s == ScopeWrite {+ return ScopeWrite+ }+ }+ return ScopeRead+}type DeviceAuthorization struct {DeviceCodeHash string@@ -19,6 +36,7 @@ type RefreshToken struct {FamilyId stringUserId intClientId string+ Scope stringRevoked boolUsed boolUsedAt *time.Time@@ -30,6 +48,7 @@ type PersonalAccessToken struct {Id string `json:"id"`Prefix string `json:"prefix"`Name string `json:"name"`+ Scope string `json:"scope"`LastUsedAt *time.Time `json:"lastUsedAt"`ExpiresAt *time.Time `json:"expiresAt"`CreatedAt time.Time `json:"createdAt"`@@ -65,6 +84,7 @@ type TokenSetResponse struct {TokenType string `json:"token_type"`ExpiresIn int `json:"expires_in"`Email string `json:"email,omitempty"`+ Scope string `json:"scope,omitempty"`}type DeviceApproveRequest struct {@@ -75,6 +95,7 @@ type DeviceLookupResponse struct {UserCode string `json:"user_code"`Status string `json:"status"`ClientName string `json:"clientName"`+ Scope string `json:"scope"`RequestedAt time.Time `json:"requestedAt"`ExpiresAt time.Time `json:"expiresAt"`}@@ -92,6 +113,7 @@ type AuthorizationCode struct {UserId intRedirectUri stringCodeChallenge string+ Scope stringExpiresAt time.TimeCreatedAt time.Time}@@ -118,6 +140,7 @@ type AuthorizeApproveRequest struct {CodeChallenge string `json:"code_challenge"`CodeChallengeMethod string `json:"code_challenge_method"`Resource string `json:"resource"`+ Scope string `json:"scope"`}type AuthorizeDenyRequest struct {@@ -137,6 +160,7 @@ type OauthClientLookupResponse struct {type CreatePATRequest struct {Name string `json:"name"`ExpiresInDays *int `json:"expiresInDays"`+ Scope string `json:"scope"`}type CreatePATResponse struct {@@ -144,6 +168,7 @@ type CreatePATResponse struct {Name string `json:"name"`Prefix string `json:"prefix"`Token string `json:"token"`+ Scope string `json:"scope"`CreatedAt time.Time `json:"createdAt"`ExpiresAt *time.Time `json:"expiresAt"`}diff --git a/backend/app/models/organization.model.go b/backend/app/models/organization.model.goindex 724c9ad2..5f3fa6d8 100644--- a/backend/app/models/organization.model.go+++ b/backend/app/models/organization.model.go@@ -30,10 +30,11 @@ type OrganizationMember struct {// OrganizationSettingsResponse is returned for the settings pagetype OrganizationSettingsResponse struct {- Organization *Organization `json:"organization"`- Members []*OrganizationMember `json:"members"`- Invitations []*InvitationWithInviter `json:"invitations"`- UserRole string `json:"userRole"`+ Organization *Organization `json:"organization"`+ Members []*OrganizationMember `json:"members"`+ Invitations []*InvitationWithInviter `json:"invitations"`+ UserRole string `json:"userRole"`+ AgentWriteEnabled bool `json:"agentWriteEnabled"`}// UpdateMemberRoleRequest is the request body for updating a member's rolediff --git a/backend/app/repositories/transactional/pg/agent_write_event.repository.go b/backend/app/repositories/transactional/pg/agent_write_event.repository.gonew file mode 100644index 00000000..828ed364--- /dev/null+++ b/backend/app/repositories/transactional/pg/agent_write_event.repository.go@@ -0,0 +1,113 @@+//go:build transactional_pg++package pg++import (+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+)++type agentWriteEventRepository struct{}++func (r *agentWriteEventRepository) Insert(ex lit.Executor, e *models.AgentWriteEvent) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO agent_write_events (id, organization_id, project_id, user_id, credential_kind, credential_ref, method, route, path, status_code, created_at)+ VALUES (:id, :organization_id, :project_id, :user_id, :credential_kind, :credential_ref, :method, :route, :path, :status_code, :created_at)`,+ lit.P{+ "id": e.Id,+ "organization_id": e.OrganizationId,+ "project_id": e.ProjectId,+ "user_id": e.UserId,+ "credential_kind": e.CredentialKind,+ "credential_ref": e.CredentialRef,+ "method": e.Method,+ "route": e.Route,+ "path": e.Path,+ "status_code": e.StatusCode,+ "created_at": shared.FormatAuthTime(e.CreatedAt),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *agentWriteEventRepository) ListByOrganization(ex lit.Executor, organizationId, page, pageSize int) ([]*models.AgentWriteEvent, int, error) {+ countQuery, countArgs, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT COUNT(*) FROM agent_write_events WHERE organization_id = :org_id",+ lit.P{"org_id": organizationId},+ )+ if err != nil {+ return nil, 0, err+ }+ var total int+ if err := ex.QueryRow(countQuery, countArgs...).Scan(&total); err != nil {+ return nil, 0, err+ }++ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT e.id, e.organization_id, e.project_id, COALESCE(p.name, ''), e.user_id, COALESCE(u.email, ''),+ e.credential_kind, e.credential_ref, COALESCE(t.name, c.name, ''), e.method, e.route, e.path, e.status_code, e.created_at+ FROM agent_write_events e+ LEFT JOIN projects p ON CAST(p.id AS TEXT) = e.project_id+ LEFT JOIN users u ON u.id = e.user_id+ LEFT JOIN personal_access_tokens t ON t.id = e.credential_ref AND e.credential_kind = 'pat'+ LEFT JOIN oauth_clients c ON c.id = e.credential_ref AND e.credential_kind = 'oauth'+ WHERE e.organization_id = :org_id+ ORDER BY e.created_at DESC+ LIMIT :limit OFFSET :offset`,+ lit.P{"org_id": organizationId, "limit": pageSize, "offset": (page - 1) * pageSize},+ )+ if err != nil {+ return nil, 0, err+ }+ rows, err := ex.Query(query, args...)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ events := []*models.AgentWriteEvent{}+ for rows.Next() {+ var (+ e models.AgentWriteEvent+ createdAt string+ )+ if err := rows.Scan(&e.Id, &e.OrganizationId, &e.ProjectId, &e.ProjectName, &e.UserId, &e.UserEmail,+ &e.CredentialKind, &e.CredentialRef, &e.CredentialName, &e.Method, &e.Route, &e.Path, &e.StatusCode, &createdAt); err != nil {+ return nil, 0, err+ }+ if e.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, 0, err+ }+ events = append(events, &e)+ }+ return events, total, rows.Err()+}++func (r *agentWriteEventRepository) PruneOlderThan(ex lit.Executor, cutoff time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM agent_write_events WHERE created_at < :cutoff",+ lit.P{"cutoff": shared.FormatAuthTime(cutoff)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var AgentWriteEventRepository = agentWriteEventRepository{}diff --git a/backend/app/repositories/transactional/pg/authorization_code.repository.go b/backend/app/repositories/transactional/pg/authorization_code.repository.goindex ccab2524..aa358abd 100644--- a/backend/app/repositories/transactional/pg/authorization_code.repository.go+++ b/backend/app/repositories/transactional/pg/authorization_code.repository.go@@ -15,17 +15,18 @@ import (type authorizationCodeRepository struct{}-func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId string, userId int, redirectUri, codeChallenge string, expiresAt time.Time) error {+func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId string, userId int, redirectUri, codeChallenge, scope string, expiresAt time.Time) error {query, args, err := lit.ParseNamedQuery(db.Driver,- `INSERT INTO authorization_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at)- VALUES (:hash, :client_id, :user_id, :redirect_uri, :code_challenge, :expires_at, :created_at)`,+ `INSERT INTO authorization_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, scope, expires_at, created_at)+ VALUES (:hash, :client_id, :user_id, :redirect_uri, :code_challenge, :scope, :expires_at, :created_at)`,lit.P{"hash": shared.HashAuthToken(code),"client_id": clientId,"user_id": userId,"redirect_uri": redirectUri,"code_challenge": codeChallenge,+ "scope": scope,"expires_at": shared.FormatAuthTime(expiresAt),"created_at": shared.FormatAuthTime(time.Now()),},@@ -40,7 +41,7 @@ func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId strfunc (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (*models.AuthorizationCode, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- "SELECT code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at FROM authorization_codes WHERE code_hash = :hash",+ "SELECT code_hash, client_id, user_id, redirect_uri, code_challenge, scope, expires_at, created_at FROM authorization_codes WHERE code_hash = :hash",lit.P{"hash": shared.HashAuthToken(code)},)if err != nil {@@ -52,7 +53,7 @@ func (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (expiresAt stringcreatedAt string)- err = ex.QueryRow(query, args...).Scan(&c.CodeHash, &c.ClientId, &c.UserId, &c.RedirectUri, &c.CodeChallenge, &expiresAt, &createdAt)+ err = ex.QueryRow(query, args...).Scan(&c.CodeHash, &c.ClientId, &c.UserId, &c.RedirectUri, &c.CodeChallenge, &c.Scope, &expiresAt, &createdAt)if errors.Is(err, sql.ErrNoRows) {return nil, nil}diff --git a/backend/app/repositories/transactional/pg/organization.repository.go b/backend/app/repositories/transactional/pg/organization.repository.goindex 4306bb5a..e2e6b26c 100644--- a/backend/app/repositories/transactional/pg/organization.repository.go+++ b/backend/app/repositories/transactional/pg/organization.repository.go@@ -4,8 +4,11 @@ package pgimport ("database/sql"+ "errors""time"+ "github.com/google/uuid"+"github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"@@ -207,3 +210,50 @@ func (r *organizationRepository) UpdateTimezone(tx *sql.Tx, organizationId int,}var OrganizationRepository = organizationRepository{}++func (r *organizationRepository) GetAgentWriteEnabled(ex lit.Executor, organizationId int) (bool, error) {+ q, a, err := lit.ParseNamedQuery(db.Driver, "SELECT agent_write_enabled FROM organizations WHERE id = :id", lit.P{"id": organizationId})+ if err != nil {+ return false, err+ }+ var enabled bool+ err = ex.QueryRow(q, a...).Scan(&enabled)+ if errors.Is(err, sql.ErrNoRows) {+ return false, nil+ }+ return enabled, err+}++func (r *organizationRepository) SetAgentWriteEnabled(tx *sql.Tx, organizationId int, enabled bool) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE organizations SET agent_write_enabled = :enabled WHERE id = :id", lit.P{"enabled": enabled, "id": organizationId})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++// AgentWritePolicyForProject returns the organization owning the project and+// whether that organization lets agent credentials write. found is false when+// the project does not exist or the user is not a member of its organization.+func (r *organizationRepository) AgentWritePolicyForProject(ex lit.Executor, projectId uuid.UUID, userId int) (organizationId int, enabled bool, found bool, err error) {+ q, a, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT o.id, o.agent_write_enabled+ FROM projects p+ JOIN organizations o ON o.id = p.organization_id+ JOIN organization_users ou ON ou.organization_id = o.id AND ou.user_id = :user_id+ WHERE p.id = :project_id`,+ lit.P{"project_id": projectId, "user_id": userId},+ )+ if err != nil {+ return 0, false, false, err+ }+ err = ex.QueryRow(q, a...).Scan(&organizationId, &enabled)+ if errors.Is(err, sql.ErrNoRows) {+ return 0, false, false, nil+ }+ if err != nil {+ return 0, false, false, err+ }+ return organizationId, enabled, true, nil+}diff --git a/backend/app/repositories/transactional/pg/personal_access_token.repository.go b/backend/app/repositories/transactional/pg/personal_access_token.repository.goindex b0a71996..c32fd8f9 100644--- a/backend/app/repositories/transactional/pg/personal_access_token.repository.go+++ b/backend/app/repositories/transactional/pg/personal_access_token.repository.go@@ -15,21 +15,22 @@ import (type personalAccessTokenRepository struct{}-func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name string, expiresAt *time.Time) error {+func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name, scope string, expiresAt *time.Time) error {var expires anyif expiresAt != nil {expires = shared.FormatAuthTime(*expiresAt)}query, args, err := lit.ParseNamedQuery(db.Driver,- `INSERT INTO personal_access_tokens (id, token_hash, prefix, user_id, name, revoked, expires_at, created_at)- VALUES (:id, :hash, :prefix, :user_id, :name, :revoked, :expires_at, :created_at)`,+ `INSERT INTO personal_access_tokens (id, token_hash, prefix, user_id, name, scope, revoked, expires_at, created_at)+ VALUES (:id, :hash, :prefix, :user_id, :name, :scope, :revoked, :expires_at, :created_at)`,lit.P{"id": id,"hash": shared.HashAuthToken(token),"prefix": prefix,"user_id": userId,"name": name,+ "scope": scope,"revoked": false,"expires_at": expires,"created_at": shared.FormatAuthTime(time.Now()),@@ -45,7 +46,7 @@ func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefifunc (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*shared.ActivePAT, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- `SELECT p.id, p.user_id, p.revoked, p.expires_at, p.last_used_at, u.email+ `SELECT p.id, p.user_id, p.scope, p.revoked, p.expires_at, p.last_used_at, u.emailFROM personal_access_tokens pJOIN users u ON u.id = p.user_idWHERE p.token_hash = :hash`,@@ -61,7 +62,7 @@ func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, tokenexpiresAt sql.NullStringlastUsed sql.NullString)- err = ex.QueryRow(query, args...).Scan(&pat.Id, &pat.UserId, &revoked, &expiresAt, &lastUsed, &pat.Email)+ err = ex.QueryRow(query, args...).Scan(&pat.Id, &pat.UserId, &pat.Scope, &revoked, &expiresAt, &lastUsed, &pat.Email)if errors.Is(err, sql.ErrNoRows) {return nil, nil}@@ -88,7 +89,7 @@ func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, tokenfunc (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int) ([]*models.PersonalAccessToken, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- `SELECT id, prefix, name, last_used_at, expires_at, created_at+ `SELECT id, prefix, name, scope, last_used_at, expires_at, created_atFROM personal_access_tokensWHERE user_id = :user_id AND revoked = :revokedORDER BY created_at DESC`,@@ -112,7 +113,7 @@ func (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int)expiresAt sql.NullStringcreatedAt string)- if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &lastUsed, &expiresAt, &createdAt); err != nil {+ if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &pat.Scope, &lastUsed, &expiresAt, &createdAt); err != nil {return nil, err}if pat.LastUsedAt, err = shared.ParseNullableAuthTime(lastUsed); err != nil {diff --git a/backend/app/repositories/transactional/pg/post_mortem.repository.go b/backend/app/repositories/transactional/pg/post_mortem.repository.goindex a7161fe9..e687c42b 100644--- a/backend/app/repositories/transactional/pg/post_mortem.repository.go+++ b/backend/app/repositories/transactional/pg/post_mortem.repository.go@@ -49,6 +49,18 @@ func (r *postMortemRepository) Update(tx *sql.Tx, postMortem *models.PostMortem)return lit.UpdateNamed(tx, postMortem, "id = :id AND project_id = :project_id", lit.P{"id": postMortem.Id, "project_id": postMortem.ProjectId})}+// LockForUpdate takes the row lock before a read-check-write, so on Postgres+// a concurrent update of the same document waits for this transaction and+// then sees its result. SQLite serializes writers already, where this is a+// no-op.+func (r *postMortemRepository) LockForUpdate(tx *sql.Tx, id int, projectId uuid.UUID) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE post_mortems SET id = id WHERE id = :id AND project_id = :project_id", lit.P{"id": id, "project_id": projectId})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}+func (r *postMortemRepository) Delete(tx *sql.Tx, id int, projectId uuid.UUID) error {return lit.DeleteNamed(db.Driver, tx, "DELETE FROM post_mortems WHERE id = :id AND project_id = :project_id", lit.P{"id": id, "project_id": projectId})}diff --git a/backend/app/repositories/transactional/pg/refresh_token.repository.go b/backend/app/repositories/transactional/pg/refresh_token.repository.goindex 61bdd5ad..e37abc0d 100644--- a/backend/app/repositories/transactional/pg/refresh_token.repository.go+++ b/backend/app/repositories/transactional/pg/refresh_token.repository.go@@ -15,16 +15,17 @@ import (type refreshTokenRepository struct{}-func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string, userId int, clientId string, expiresAt time.Time) error {+func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string, userId int, clientId, scope string, expiresAt time.Time) error {query, args, err := lit.ParseNamedQuery(db.Driver,- `INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, revoked, used, expires_at, created_at)- VALUES (:hash, :family, :user_id, :client_id, :revoked, :used, :expires_at, :created_at)`,+ `INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, scope, revoked, used, expires_at, created_at)+ VALUES (:hash, :family, :user_id, :client_id, :scope, :revoked, :used, :expires_at, :created_at)`,lit.P{"hash": shared.HashAuthToken(token),"family": familyId,"user_id": userId,"client_id": clientId,+ "scope": scope,"revoked": false,"used": false,"expires_at": shared.FormatAuthTime(expiresAt),@@ -41,7 +42,7 @@ func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string,func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*models.RefreshToken, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- "SELECT token_hash, family_id, user_id, client_id, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",+ "SELECT token_hash, family_id, user_id, client_id, scope, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",lit.P{"hash": shared.HashAuthToken(token)},)if err != nil {@@ -54,7 +55,7 @@ func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*moexpiresAt stringcreatedAt string)- err = ex.QueryRow(query, args...).Scan(&t.TokenHash, &t.FamilyId, &t.UserId, &t.ClientId, &t.Revoked, &t.Used, &usedAt, &expiresAt, &createdAt)+ err = ex.QueryRow(query, args...).Scan(&t.TokenHash, &t.FamilyId, &t.UserId, &t.ClientId, &t.Scope, &t.Revoked, &t.Used, &usedAt, &expiresAt, &createdAt)if errors.Is(err, sql.ErrNoRows) {return nil, nil}diff --git a/backend/app/repositories/transactional/shared/types.go b/backend/app/repositories/transactional/shared/types.goindex 3ff4ad13..31396187 100644--- a/backend/app/repositories/transactional/shared/types.go+++ b/backend/app/repositories/transactional/shared/types.go@@ -15,6 +15,7 @@ type ActivePAT struct {Id stringUserId intEmail string+ Scope stringLastUsedAt *time.Time}diff --git a/backend/app/repositories/transactional/sqlite/agent_write_event.repository.go b/backend/app/repositories/transactional/sqlite/agent_write_event.repository.gonew file mode 100644index 00000000..a07b465f--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/agent_write_event.repository.go@@ -0,0 +1,113 @@+//go:build !transactional_pg++package sqlite++import (+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+)++type agentWriteEventRepository struct{}++func (r *agentWriteEventRepository) Insert(ex lit.Executor, e *models.AgentWriteEvent) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO agent_write_events (id, organization_id, project_id, user_id, credential_kind, credential_ref, method, route, path, status_code, created_at)+ VALUES (:id, :organization_id, :project_id, :user_id, :credential_kind, :credential_ref, :method, :route, :path, :status_code, :created_at)`,+ lit.P{+ "id": e.Id,+ "organization_id": e.OrganizationId,+ "project_id": e.ProjectId,+ "user_id": e.UserId,+ "credential_kind": e.CredentialKind,+ "credential_ref": e.CredentialRef,+ "method": e.Method,+ "route": e.Route,+ "path": e.Path,+ "status_code": e.StatusCode,+ "created_at": shared.FormatAuthTime(e.CreatedAt),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *agentWriteEventRepository) ListByOrganization(ex lit.Executor, organizationId, page, pageSize int) ([]*models.AgentWriteEvent, int, error) {+ countQuery, countArgs, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT COUNT(*) FROM agent_write_events WHERE organization_id = :org_id",+ lit.P{"org_id": organizationId},+ )+ if err != nil {+ return nil, 0, err+ }+ var total int+ if err := ex.QueryRow(countQuery, countArgs...).Scan(&total); err != nil {+ return nil, 0, err+ }++ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT e.id, e.organization_id, e.project_id, COALESCE(p.name, ''), e.user_id, COALESCE(u.email, ''),+ e.credential_kind, e.credential_ref, COALESCE(t.name, c.name, ''), e.method, e.route, e.path, e.status_code, e.created_at+ FROM agent_write_events e+ LEFT JOIN projects p ON CAST(p.id AS TEXT) = e.project_id+ LEFT JOIN users u ON u.id = e.user_id+ LEFT JOIN personal_access_tokens t ON t.id = e.credential_ref AND e.credential_kind = 'pat'+ LEFT JOIN oauth_clients c ON c.id = e.credential_ref AND e.credential_kind = 'oauth'+ WHERE e.organization_id = :org_id+ ORDER BY e.created_at DESC+ LIMIT :limit OFFSET :offset`,+ lit.P{"org_id": organizationId, "limit": pageSize, "offset": (page - 1) * pageSize},+ )+ if err != nil {+ return nil, 0, err+ }+ rows, err := ex.Query(query, args...)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ events := []*models.AgentWriteEvent{}+ for rows.Next() {+ var (+ e models.AgentWriteEvent+ createdAt string+ )+ if err := rows.Scan(&e.Id, &e.OrganizationId, &e.ProjectId, &e.ProjectName, &e.UserId, &e.UserEmail,+ &e.CredentialKind, &e.CredentialRef, &e.CredentialName, &e.Method, &e.Route, &e.Path, &e.StatusCode, &createdAt); err != nil {+ return nil, 0, err+ }+ if e.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, 0, err+ }+ events = append(events, &e)+ }+ return events, total, rows.Err()+}++func (r *agentWriteEventRepository) PruneOlderThan(ex lit.Executor, cutoff time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM agent_write_events WHERE created_at < :cutoff",+ lit.P{"cutoff": shared.FormatAuthTime(cutoff)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var AgentWriteEventRepository = agentWriteEventRepository{}diff --git a/backend/app/repositories/transactional/sqlite/authorization_code.repository.go b/backend/app/repositories/transactional/sqlite/authorization_code.repository.goindex 34ee22d0..324fc174 100644--- a/backend/app/repositories/transactional/sqlite/authorization_code.repository.go+++ b/backend/app/repositories/transactional/sqlite/authorization_code.repository.go@@ -15,17 +15,18 @@ import (type authorizationCodeRepository struct{}-func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId string, userId int, redirectUri, codeChallenge string, expiresAt time.Time) error {+func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId string, userId int, redirectUri, codeChallenge, scope string, expiresAt time.Time) error {query, args, err := lit.ParseNamedQuery(db.Driver,- `INSERT INTO authorization_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at)- VALUES (:hash, :client_id, :user_id, :redirect_uri, :code_challenge, :expires_at, :created_at)`,+ `INSERT INTO authorization_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, scope, expires_at, created_at)+ VALUES (:hash, :client_id, :user_id, :redirect_uri, :code_challenge, :scope, :expires_at, :created_at)`,lit.P{"hash": shared.HashAuthToken(code),"client_id": clientId,"user_id": userId,"redirect_uri": redirectUri,"code_challenge": codeChallenge,+ "scope": scope,"expires_at": shared.FormatAuthTime(expiresAt),"created_at": shared.FormatAuthTime(time.Now()),},@@ -40,7 +41,7 @@ func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId strfunc (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (*models.AuthorizationCode, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- "SELECT code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at FROM authorization_codes WHERE code_hash = :hash",+ "SELECT code_hash, client_id, user_id, redirect_uri, code_challenge, scope, expires_at, created_at FROM authorization_codes WHERE code_hash = :hash",lit.P{"hash": shared.HashAuthToken(code)},)if err != nil {@@ -52,7 +53,7 @@ func (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (expiresAt stringcreatedAt string)- err = ex.QueryRow(query, args...).Scan(&c.CodeHash, &c.ClientId, &c.UserId, &c.RedirectUri, &c.CodeChallenge, &expiresAt, &createdAt)+ err = ex.QueryRow(query, args...).Scan(&c.CodeHash, &c.ClientId, &c.UserId, &c.RedirectUri, &c.CodeChallenge, &c.Scope, &expiresAt, &createdAt)if errors.Is(err, sql.ErrNoRows) {return nil, nil}diff --git a/backend/app/repositories/transactional/sqlite/organization.repository.go b/backend/app/repositories/transactional/sqlite/organization.repository.goindex a8527f42..4ca96517 100644--- a/backend/app/repositories/transactional/sqlite/organization.repository.go+++ b/backend/app/repositories/transactional/sqlite/organization.repository.go@@ -4,8 +4,11 @@ package sqliteimport ("database/sql"+ "errors""time"+ "github.com/google/uuid"+"github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"@@ -207,3 +210,50 @@ func (r *organizationRepository) UpdateTimezone(tx *sql.Tx, organizationId int,}var OrganizationRepository = organizationRepository{}++func (r *organizationRepository) GetAgentWriteEnabled(ex lit.Executor, organizationId int) (bool, error) {+ q, a, err := lit.ParseNamedQuery(db.Driver, "SELECT agent_write_enabled FROM organizations WHERE id = :id", lit.P{"id": organizationId})+ if err != nil {+ return false, err+ }+ var enabled bool+ err = ex.QueryRow(q, a...).Scan(&enabled)+ if errors.Is(err, sql.ErrNoRows) {+ return false, nil+ }+ return enabled, err+}++func (r *organizationRepository) SetAgentWriteEnabled(tx *sql.Tx, organizationId int, enabled bool) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE organizations SET agent_write_enabled = :enabled WHERE id = :id", lit.P{"enabled": enabled, "id": organizationId})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++// AgentWritePolicyForProject returns the organization owning the project and+// whether that organization lets agent credentials write. found is false when+// the project does not exist or the user is not a member of its organization.+func (r *organizationRepository) AgentWritePolicyForProject(ex lit.Executor, projectId uuid.UUID, userId int) (organizationId int, enabled bool, found bool, err error) {+ q, a, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT o.id, o.agent_write_enabled+ FROM projects p+ JOIN organizations o ON o.id = p.organization_id+ JOIN organization_users ou ON ou.organization_id = o.id AND ou.user_id = :user_id+ WHERE p.id = :project_id`,+ lit.P{"project_id": projectId, "user_id": userId},+ )+ if err != nil {+ return 0, false, false, err+ }+ err = ex.QueryRow(q, a...).Scan(&organizationId, &enabled)+ if errors.Is(err, sql.ErrNoRows) {+ return 0, false, false, nil+ }+ if err != nil {+ return 0, false, false, err+ }+ return organizationId, enabled, true, nil+}diff --git a/backend/app/repositories/transactional/sqlite/personal_access_token.repository.go b/backend/app/repositories/transactional/sqlite/personal_access_token.repository.goindex d839deac..0c4b5cab 100644--- a/backend/app/repositories/transactional/sqlite/personal_access_token.repository.go+++ b/backend/app/repositories/transactional/sqlite/personal_access_token.repository.go@@ -15,21 +15,22 @@ import (type personalAccessTokenRepository struct{}-func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name string, expiresAt *time.Time) error {+func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name, scope string, expiresAt *time.Time) error {var expires anyif expiresAt != nil {expires = shared.FormatAuthTime(*expiresAt)}query, args, err := lit.ParseNamedQuery(db.Driver,- `INSERT INTO personal_access_tokens (id, token_hash, prefix, user_id, name, revoked, expires_at, created_at)- VALUES (:id, :hash, :prefix, :user_id, :name, :revoked, :expires_at, :created_at)`,+ `INSERT INTO personal_access_tokens (id, token_hash, prefix, user_id, name, scope, revoked, expires_at, created_at)+ VALUES (:id, :hash, :prefix, :user_id, :name, :scope, :revoked, :expires_at, :created_at)`,lit.P{"id": id,"hash": shared.HashAuthToken(token),"prefix": prefix,"user_id": userId,"name": name,+ "scope": scope,"revoked": false,"expires_at": expires,"created_at": shared.FormatAuthTime(time.Now()),@@ -45,7 +46,7 @@ func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefifunc (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*shared.ActivePAT, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- `SELECT p.id, p.user_id, p.revoked, p.expires_at, p.last_used_at, u.email+ `SELECT p.id, p.user_id, p.scope, p.revoked, p.expires_at, p.last_used_at, u.emailFROM personal_access_tokens pJOIN users u ON u.id = p.user_idWHERE p.token_hash = :hash`,@@ -61,7 +62,7 @@ func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, tokenexpiresAt sql.NullStringlastUsed sql.NullString)- err = ex.QueryRow(query, args...).Scan(&pat.Id, &pat.UserId, &revoked, &expiresAt, &lastUsed, &pat.Email)+ err = ex.QueryRow(query, args...).Scan(&pat.Id, &pat.UserId, &pat.Scope, &revoked, &expiresAt, &lastUsed, &pat.Email)if errors.Is(err, sql.ErrNoRows) {return nil, nil}@@ -88,7 +89,7 @@ func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, tokenfunc (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int) ([]*models.PersonalAccessToken, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- `SELECT id, prefix, name, last_used_at, expires_at, created_at+ `SELECT id, prefix, name, scope, last_used_at, expires_at, created_atFROM personal_access_tokensWHERE user_id = :user_id AND revoked = :revokedORDER BY created_at DESC`,@@ -112,7 +113,7 @@ func (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int)expiresAt sql.NullStringcreatedAt string)- if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &lastUsed, &expiresAt, &createdAt); err != nil {+ if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &pat.Scope, &lastUsed, &expiresAt, &createdAt); err != nil {return nil, err}if pat.LastUsedAt, err = shared.ParseNullableAuthTime(lastUsed); err != nil {diff --git a/backend/app/repositories/transactional/sqlite/post_mortem.repository.go b/backend/app/repositories/transactional/sqlite/post_mortem.repository.goindex f617db55..bba2e6e6 100644--- a/backend/app/repositories/transactional/sqlite/post_mortem.repository.go+++ b/backend/app/repositories/transactional/sqlite/post_mortem.repository.go@@ -49,6 +49,18 @@ func (r *postMortemRepository) Update(tx *sql.Tx, postMortem *models.PostMortem)return lit.UpdateNamed(tx, postMortem, "id = :id AND project_id = :project_id", lit.P{"id": postMortem.Id, "project_id": postMortem.ProjectId})}+// LockForUpdate takes the row lock before a read-check-write, so on Postgres+// a concurrent update of the same document waits for this transaction and+// then sees its result. SQLite serializes writers already, where this is a+// no-op.+func (r *postMortemRepository) LockForUpdate(tx *sql.Tx, id int, projectId uuid.UUID) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE post_mortems SET id = id WHERE id = :id AND project_id = :project_id", lit.P{"id": id, "project_id": projectId})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}+func (r *postMortemRepository) Delete(tx *sql.Tx, id int, projectId uuid.UUID) error {return lit.DeleteNamed(db.Driver, tx, "DELETE FROM post_mortems WHERE id = :id AND project_id = :project_id", lit.P{"id": id, "project_id": projectId})}diff --git a/backend/app/repositories/transactional/sqlite/refresh_token.repository.go b/backend/app/repositories/transactional/sqlite/refresh_token.repository.goindex 65473339..e4e6f49b 100644--- a/backend/app/repositories/transactional/sqlite/refresh_token.repository.go+++ b/backend/app/repositories/transactional/sqlite/refresh_token.repository.go@@ -15,16 +15,17 @@ import (type refreshTokenRepository struct{}-func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string, userId int, clientId string, expiresAt time.Time) error {+func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string, userId int, clientId, scope string, expiresAt time.Time) error {query, args, err := lit.ParseNamedQuery(db.Driver,- `INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, revoked, used, expires_at, created_at)- VALUES (:hash, :family, :user_id, :client_id, :revoked, :used, :expires_at, :created_at)`,+ `INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, scope, revoked, used, expires_at, created_at)+ VALUES (:hash, :family, :user_id, :client_id, :scope, :revoked, :used, :expires_at, :created_at)`,lit.P{"hash": shared.HashAuthToken(token),"family": familyId,"user_id": userId,"client_id": clientId,+ "scope": scope,"revoked": false,"used": false,"expires_at": shared.FormatAuthTime(expiresAt),@@ -41,7 +42,7 @@ func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string,func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*models.RefreshToken, error) {query, args, err := lit.ParseNamedQuery(db.Driver,- "SELECT token_hash, family_id, user_id, client_id, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",+ "SELECT token_hash, family_id, user_id, client_id, scope, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",lit.P{"hash": shared.HashAuthToken(token)},)if err != nil {@@ -54,7 +55,7 @@ func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*moexpiresAt stringcreatedAt string)- err = ex.QueryRow(query, args...).Scan(&t.TokenHash, &t.FamilyId, &t.UserId, &t.ClientId, &t.Revoked, &t.Used, &usedAt, &expiresAt, &createdAt)+ err = ex.QueryRow(query, args...).Scan(&t.TokenHash, &t.FamilyId, &t.UserId, &t.ClientId, &t.Scope, &t.Revoked, &t.Used, &usedAt, &expiresAt, &createdAt)if errors.Is(err, sql.ErrNoRows) {return nil, nil}diff --git a/backend/app/repositories/transactional/transactional_pg.go b/backend/app/repositories/transactional/transactional_pg.goindex bc5ad3a9..b950e9ec 100644--- a/backend/app/repositories/transactional/transactional_pg.go+++ b/backend/app/repositories/transactional/transactional_pg.go@@ -5,6 +5,7 @@ package transactionalimport pgrepo "github.com/tracewayapp/traceway/backend/app/repositories/transactional/pg"var (+ AgentWriteEventRepository = pgrepo.AgentWriteEventRepositoryAuthorizationCodeRepository = pgrepo.AuthorizationCodeRepositoryCheckIncidentRepository = pgrepo.CheckIncidentRepositoryCheckRunRepository = pgrepo.CheckRunRepositorydiff --git a/backend/app/repositories/transactional/transactional_sqlite.go b/backend/app/repositories/transactional/transactional_sqlite.goindex 6787fa7d..bfa5d597 100644--- a/backend/app/repositories/transactional/transactional_sqlite.go+++ b/backend/app/repositories/transactional/transactional_sqlite.go@@ -5,6 +5,7 @@ package transactionalimport sqliterepo "github.com/tracewayapp/traceway/backend/app/repositories/transactional/sqlite"var (+ AgentWriteEventRepository = sqliterepo.AgentWriteEventRepositoryAuthorizationCodeRepository = sqliterepo.AuthorizationCodeRepositoryCheckIncidentRepository = sqliterepo.CheckIncidentRepositoryCheckRunRepository = sqliterepo.CheckRunRepositorydiff --git a/backend/app/retention/auth_tokens.go b/backend/app/retention/auth_tokens.goindex 19523492..d86ffb0b 100644--- a/backend/app/retention/auth_tokens.go+++ b/backend/app/retention/auth_tokens.go@@ -10,6 +10,8 @@ import (const authTokensPruneInterval = 24 * time.Hour+const agentWriteEventRetention = 90 * 24 * time.Hour+func startAuthTokensPrune(ctx context.Context) {startDBPruneWorker(ctx, "auth_tokens", authTokensPruneInterval, func(tx *sql.Tx) (int64, error) {now := time.Now().UTC()@@ -57,6 +59,12 @@ func startAuthTokensPrune(ctx context.Context) {}total += n+ n, err = transactional.AgentWriteEventRepository.PruneOlderThan(tx, now.Add(-agentWriteEventRetention))+ if err != nil {+ return total, err+ }+ total += n+return total, nil})}diff --git a/backend/app/services/authserver/authcode.go b/backend/app/services/authserver/authcode.goindex bf757c3c..77a36ce8 100644--- a/backend/app/services/authserver/authcode.go+++ b/backend/app/services/authserver/authcode.go@@ -174,7 +174,7 @@ func ApproveAuthorization(tx *sql.Tx, userId int, req models.AuthorizeApproveReqreturn "", err}code := newOpaqueToken("twa_")- if err := transactional.AuthorizationCodeRepository.Create(tx, code, client.Id, userId, req.RedirectUri, req.CodeChallenge, time.Now().Add(authCodeTTL)); err != nil {+ if err := transactional.AuthorizationCodeRepository.Create(tx, code, client.Id, userId, req.RedirectUri, req.CodeChallenge, models.ParseRequestedScope(req.Scope), time.Now().Add(authCodeTTL)); err != nil {return "", err}return appendRedirectParams(req.RedirectUri, url.Values{"code": {code}}, req.State), nil@@ -252,7 +252,7 @@ func RedeemAuthorizationCode(clientId, code, verifier, redirectUri, resource, isif user == nil {return redeemOutcome{grantErr: ErrInvalidGrant}, nil}- tokens, err := IssueTokenSet(tx, ac.UserId, user.Email, clientId)+ tokens, err := IssueTokenSet(tx, ac.UserId, user.Email, clientId, ac.Scope)if err != nil {return redeemOutcome{}, err}diff --git a/backend/app/services/authserver/authcode_test.go b/backend/app/services/authserver/authcode_test.goindex 45d1ef1d..0a865216 100644--- a/backend/app/services/authserver/authcode_test.go+++ b/backend/app/services/authserver/authcode_test.go@@ -212,7 +212,7 @@ func TestAuthCode_expiredCodeRejected(t *testing.T) {_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {return struct{}{}, transactional.AuthorizationCodeRepository.Create(- tx, "twa_expired", client.Id, 1, "http://127.0.0.1:8123/callback", testChallenge(testVerifier), time.Now().Add(-time.Minute))+ tx, "twa_expired", client.Id, 1, "http://127.0.0.1:8123/callback", testChallenge(testVerifier), models.ScopeRead, time.Now().Add(-time.Minute))})if err != nil {t.Fatalf("insert expired code: %v", err)@@ -305,10 +305,10 @@ func TestAuthorizationCodeRepository_PruneExpired(t *testing.T) {client := registerTestClient(t)_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- if err := transactional.AuthorizationCodeRepository.Create(tx, "twa_live", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), time.Now().Add(time.Minute)); err != nil {+ if err := transactional.AuthorizationCodeRepository.Create(tx, "twa_live", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), models.ScopeRead, time.Now().Add(time.Minute)); err != nil {return struct{}{}, err}- return struct{}{}, transactional.AuthorizationCodeRepository.Create(tx, "twa_dead", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), time.Now().Add(-time.Minute))+ return struct{}{}, transactional.AuthorizationCodeRepository.Create(tx, "twa_dead", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), models.ScopeRead, time.Now().Add(-time.Minute))})if err != nil {t.Fatalf("seed codes: %v", err)diff --git a/backend/app/services/authserver/authserver_test.go b/backend/app/services/authserver/authserver_test.goindex 3db448e3..587eac42 100644--- a/backend/app/services/authserver/authserver_test.go+++ b/backend/app/services/authserver/authserver_test.go@@ -60,7 +60,7 @@ func setupAuthDB(t *testing.T) {func insertRefresh(t *testing.T, token, family string) {t.Helper()- if err := transactional.RefreshTokenRepository.Insert(db.DB, token, family, 1, cliClientID, time.Now().Add(time.Hour)); err != nil {+ if err := transactional.RefreshTokenRepository.Insert(db.DB, token, family, 1, cliClientID, models.ScopeRead, time.Now().Add(time.Hour)); err != nil {t.Fatalf("insert refresh token: %v", err)}}@@ -217,7 +217,7 @@ func TestRefreshTokenRepository_PruneExpired(t *testing.T) {insertRefresh(t, "twr_recent_used", "fam-prune")insertRefresh(t, "twr_old_used", "fam-prune")insertRefresh(t, "twr_revoked", "fam-dead")- if err := transactional.RefreshTokenRepository.Insert(db.DB, "twr_expired", "fam-prune", 1, cliClientID, time.Now().Add(-time.Hour)); err != nil {+ if err := transactional.RefreshTokenRepository.Insert(db.DB, "twr_expired", "fam-prune", 1, cliClientID, models.ScopeRead, time.Now().Add(-time.Hour)); err != nil {t.Fatalf("insert expired: %v", err)}@@ -315,9 +315,9 @@ func TestPersonalAccessTokenRepository_PruneExpired(t *testing.T) {t.Fatalf("pat create: %v", err)}}- must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-active", "twp_active", "twp_active12", 1, "active", nil))- must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-expired", "twp_expired", "twp_expired1", 1, "expired", &expired))- must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-revoked", "twp_revoked", "twp_revoked1", 1, "revoked", nil))+ must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-active", "twp_active", "twp_active12", 1, "active", models.ScopeRead, nil))+ must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-expired", "twp_expired", "twp_expired1", 1, "expired", models.ScopeRead, &expired))+ must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-revoked", "twp_revoked", "twp_revoked1", 1, "revoked", models.ScopeRead, nil))if _, err := transactional.PersonalAccessTokenRepository.Revoke(db.DB, "id-revoked", 1); err != nil {t.Fatalf("revoke: %v", err)}diff --git a/backend/app/services/authserver/config.go b/backend/app/services/authserver/config.goindex 5ce38faf..939a13a1 100644--- a/backend/app/services/authserver/config.go+++ b/backend/app/services/authserver/config.go@@ -18,6 +18,7 @@ const (authCodeTTL = 5 * time.MinutecliClientID = "traceway-cli"mcpClientID = "traceway-mcp"+ cliWriteClientID = "traceway-cli-write"// reuseGrace is the window during which re-presenting a just-used refresh// token is treated as a benign concurrent retry (two CLI processes racing,diff --git a/backend/app/services/authserver/device.go b/backend/app/services/authserver/device.goindex 09f3530f..b9d04cb0 100644--- a/backend/app/services/authserver/device.go+++ b/backend/app/services/authserver/device.go@@ -24,16 +24,29 @@ var (// Only first-party clients may start the device flow: the approval screen// renders the client's display name as a trusted party, so an arbitrary// attacker-chosen client_id would make phishing prompts look first-party.-var knownDeviceClients = map[string]bool{- cliClientID: true,- mcpClientID: true,+// The scope a device login receives is fixed by its client: only the separate+// write CLI can ask for write access, so a read install can never be upgraded.+var knownDeviceClients = map[string]string{+ cliClientID: models.ScopeRead,+ mcpClientID: models.ScopeRead,+ cliWriteClientID: models.ScopeWrite,+}++func DeviceClientScope(clientId string) string {+ if clientId == "" {+ clientId = cliClientID+ }+ if scope, ok := knownDeviceClients[clientId]; ok {+ return scope+ }+ return models.ScopeRead}func CreateDeviceAuth(clientId, baseURL string) (*models.DeviceAuthorizeResponse, error) {if clientId == "" {clientId = cliClientID}- if !knownDeviceClients[clientId] {+ if _, ok := knownDeviceClients[clientId]; !ok {return nil, ErrUnknownClient}@@ -103,7 +116,7 @@ func PollDeviceToken(deviceCode string) (*models.TokenSetResponse, error) {if user == nil {return nil, ErrAccessDenied}- return IssueTokenSet(tx, *da.UserId, user.Email, da.ClientId)+ return IssueTokenSet(tx, *da.UserId, user.Email, da.ClientId, DeviceClientScope(da.ClientId))})default:now := time.Now()diff --git a/backend/app/services/authserver/refresh.go b/backend/app/services/authserver/refresh.goindex 1f82ad03..b08dafea 100644--- a/backend/app/services/authserver/refresh.go+++ b/backend/app/services/authserver/refresh.go@@ -132,7 +132,7 @@ func RotateRefresh(presented string) (*models.TokenSetResponse, error) {if user == nil {return nil, ErrInvalidGrant}- return issueTokenSetWithFamily(tx, rt.UserId, user.Email, rt.ClientId, rt.FamilyId)+ return issueTokenSetWithFamily(tx, rt.UserId, user.Email, rt.ClientId, rt.Scope, rt.FamilyId)})if err != nil {if errors.Is(err, errReplay) {diff --git a/backend/app/services/authserver/scope_test.go b/backend/app/services/authserver/scope_test.gonew file mode 100644index 00000000..cd580137--- /dev/null+++ b/backend/app/services/authserver/scope_test.go@@ -0,0 +1,98 @@+//go:build !telemetry_ch && !telemetry_duckdb++package authserver++import (+ "testing"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ "github.com/tracewayapp/traceway/backend/app/services"+)++func accessScope(t *testing.T, access string) string {+ t.Helper()+ claims, err := services.ValidateToken(access)+ if err != nil {+ t.Fatalf("validate access token: %v", err)+ }+ return claims.Scope+}++func approvedDeviceToken(t *testing.T, clientId, userCode string) *models.TokenSetResponse {+ t.Helper()+ deviceCode := "dev-" + clientId+ if err := transactional.DeviceAuthorizationRepository.Create(db.DB, deviceCode, userCode, clientId, 5, time.Now().Add(deviceCodeTTL)); err != nil {+ t.Fatalf("create device auth: %v", err)+ }+ if _, err := transactional.DeviceAuthorizationRepository.Approve(db.DB, userCode, 1); err != nil {+ t.Fatalf("approve: %v", err)+ }+ ts, err := PollDeviceToken(deviceCode)+ if err != nil {+ t.Fatalf("poll: %v", err)+ }+ return ts+}++func TestDeviceFlow_scopeFollowsClient(t *testing.T) {+ setupAuthDB(t)++ read := approvedDeviceToken(t, cliClientID, "READ-AAAA")+ if read.Scope != models.ScopeRead || accessScope(t, read.AccessToken) != models.ScopeRead {+ t.Errorf("traceway-cli login scope = %q / %q, want read", read.Scope, accessScope(t, read.AccessToken))+ }++ write := approvedDeviceToken(t, cliWriteClientID, "WRIT-BBBB")+ if write.Scope != models.ScopeWrite || accessScope(t, write.AccessToken) != models.ScopeWrite {+ t.Errorf("traceway-cli-write login scope = %q, want write", write.Scope)+ }++ rotated, err := RotateRefresh(write.RefreshToken)+ if err != nil {+ t.Fatalf("rotate: %v", err)+ }+ if rotated.Scope != models.ScopeWrite || accessScope(t, rotated.AccessToken) != models.ScopeWrite {+ t.Errorf("refresh must keep the write scope, got %q", rotated.Scope)+ }++ rotatedRead, err := RotateRefresh(read.RefreshToken)+ if err != nil {+ t.Fatalf("rotate read: %v", err)+ }+ if rotatedRead.Scope != models.ScopeRead {+ t.Errorf("refresh must never upgrade a read token, got %q", rotatedRead.Scope)+ }+}++func TestAuthCode_scopeComesFromTheRequest(t *testing.T) {+ setupAuthDB(t)+ client := registerTestClient(t)++ for _, tc := range []struct {+ requested, want string+ }{+ {"", models.ScopeRead},+ {"traceway:read", models.ScopeRead},+ {"openid traceway:write", models.ScopeWrite},+ {"traceway:admin", models.ScopeRead},+ } {+ redirectTo := approve(t, models.AuthorizeApproveRequest{+ ClientId: client.Id,+ RedirectUri: "http://127.0.0.1:8123/callback",+ CodeChallenge: testChallenge(testVerifier),+ CodeChallengeMethod: "S256",+ Scope: tc.requested,+ })+ code, _ := codeFromRedirect(t, redirectTo)+ ts, err := RedeemAuthorizationCode(client.Id, code, testVerifier, "http://127.0.0.1:8123/callback", "", "")+ if err != nil {+ t.Fatalf("redeem (%q): %v", tc.requested, err)+ }+ if ts.Scope != tc.want || accessScope(t, ts.AccessToken) != tc.want {+ t.Errorf("requested %q got scope %q, want %q", tc.requested, ts.Scope, tc.want)+ }+ }+}diff --git a/backend/app/services/authserver/tokens.go b/backend/app/services/authserver/tokens.goindex 5fb3ed55..c440a547 100644--- a/backend/app/services/authserver/tokens.go+++ b/backend/app/services/authserver/tokens.go@@ -39,7 +39,10 @@ func newUserCode() string {return sb.String()}-func NewPATToken() string {+func NewPATToken(scope string) string {+ if scope == models.ScopeWrite {+ return newOpaqueToken("tww_")+ }return newOpaqueToken("twp_")}@@ -47,19 +50,22 @@ func NewSetupToken() string {return newOpaqueToken("tws_")}-func IssueTokenSet(tx *sql.Tx, userId int, email, clientId string) (*models.TokenSetResponse, error) {- return issueTokenSetWithFamily(tx, userId, email, clientId, uuid.New().String())+func IssueTokenSet(tx *sql.Tx, userId int, email, clientId, scope string) (*models.TokenSetResponse, error) {+ return issueTokenSetWithFamily(tx, userId, email, clientId, scope, uuid.New().String())}-func issueTokenSetWithFamily(tx *sql.Tx, userId int, email, clientId, familyId string) (*models.TokenSetResponse, error) {+func issueTokenSetWithFamily(tx *sql.Tx, userId int, email, clientId, scope, familyId string) (*models.TokenSetResponse, error) {+ if scope != models.ScopeWrite {+ scope = models.ScopeRead+ }ttl := accessTokenTTL- access, err := services.GenerateAccessToken(userId, email, ttl)+ access, err := services.GenerateAccessToken(userId, email, scope, clientId, ttl)if err != nil {return nil, err}refresh := newOpaqueToken("twr_")- if err := transactional.RefreshTokenRepository.Insert(tx, refresh, familyId, userId, clientId, time.Now().Add(refreshTokenTTL)); err != nil {+ if err := transactional.RefreshTokenRepository.Insert(tx, refresh, familyId, userId, clientId, scope, time.Now().Add(refreshTokenTTL)); err != nil {return nil, err}@@ -69,5 +75,6 @@ func issueTokenSetWithFamily(tx *sql.Tx, userId int, email, clientId, familyId sTokenType: "Bearer",ExpiresIn: int(ttl.Seconds()),Email: email,+ Scope: scope,}, nil}diff --git a/backend/app/services/jwt.service.go b/backend/app/services/jwt.service.goindex 00c55ac1..07afb3e3 100644--- a/backend/app/services/jwt.service.go+++ b/backend/app/services/jwt.service.go@@ -20,9 +20,13 @@ var retiredJWTSecretDigests = map[string]bool{"e7e45a50bcc0f78bf9cf470d4600937c1eeb0bda41d7eba67e3951a536f39221": true,}+// Scope is empty on dashboard sessions; agent access tokens carry+// models.ScopeRead or models.ScopeWrite plus the OAuth client that minted them.type JWTClaims struct {- UserId int `json:"userId"`- Email string `json:"email"`+ UserId int `json:"userId"`+ Email string `json:"email"`+ Scope string `json:"scope,omitempty"`+ ClientId string `json:"cid,omitempty"`jwt.RegisteredClaims}@@ -43,17 +47,19 @@ func InitJWT() error {}func GenerateToken(userId int, email string) (string, error) {- return generateToken(userId, email, 7*24*time.Hour)+ return generateToken(userId, email, "", "", 7*24*time.Hour)}-func GenerateAccessToken(userId int, email string, ttl time.Duration) (string, error) {- return generateToken(userId, email, ttl)+func GenerateAccessToken(userId int, email, scope, clientId string, ttl time.Duration) (string, error) {+ return generateToken(userId, email, scope, clientId, ttl)}-func generateToken(userId int, email string, ttl time.Duration) (string, error) {+func generateToken(userId int, email, scope, clientId string, ttl time.Duration) (string, error) {claims := JWTClaims{- UserId: userId,- Email: email,+ UserId: userId,+ Email: email,+ Scope: scope,+ ClientId: clientId,RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),IssuedAt: jwt.NewNumericDate(time.Now()),diff --git a/backend/app/services/mcpmount/mcpmount.go b/backend/app/services/mcpmount/mcpmount.goindex ee731cac..3f8b2900 100644--- a/backend/app/services/mcpmount/mcpmount.go+++ b/backend/app/services/mcpmount/mcpmount.go@@ -13,16 +13,30 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/services/authserver""github.com/tracewayapp/traceway/cli/pkg/client""github.com/tracewayapp/traceway/cli/pkg/mcpserver")-const Path = "/mcp"+const (+ Path = "/mcp"+ WritePath = "/mcp/write"+)const patExpiryHorizon = time.Hour-func GinHandler(engine *gin.Engine, version string) gin.HandlerFunc {+// GinHandler serves the read-only server at Path, or with write set the server+// at WritePath that also registers the mutating tools and refuses tokens+// without the write scope.+func GinHandler(engine *gin.Engine, version string, write bool) gin.HandlerFunc {+ path := Path+ var requiredScopes []string+ if write {+ path = WritePath+ requiredScopes = []string{models.ScopeWrite}+ }+loopback := client.New("http://traceway-mcp.internal",client.WithHTTPClient(&http.Client{Transport: engineTransport{engine}, Timeout: 60 * time.Second}),@@ -34,6 +48,7 @@ func GinHandler(engine *gin.Engine, version string) gin.HandlerFunc {InstanceURL: authserver.IssuerBaseURLFromHTTPRequest(r),Version: version,PerRequestBearer: true,+ AllowWrite: write,AuthHint: "the access token was rejected; re-authenticate this MCP connection from your client (OAuth clients refresh automatically; PAT setups need a new token)",})}, nil)@@ -41,7 +56,8 @@ func GinHandler(engine *gin.Engine, version string) gin.HandlerFunc {return func(c *gin.Context) {issuer := authserver.IssuerBaseURLFromRequest(c)requireBearer := auth.RequireBearerToken(verifyBearer, &auth.RequireBearerTokenOptions{- ResourceMetadataURL: issuer + "/.well-known/oauth-protected-resource" + Path,+ ResourceMetadataURL: issuer + "/.well-known/oauth-protected-resource" + path,+ Scopes: requiredScopes,})requireBearer(streamable).ServeHTTP(c.Writer, c.Request)c.Abort()@@ -60,8 +76,13 @@ func verifyBearer(_ context.Context, token string, _ *http.Request) (*auth.Tokenif expires.IsZero() {expires = time.Now().Add(patExpiryHorizon)}+ scopes := []string{models.ScopeRead}+ if identity.HasAgentWriteScope() {+ scopes = append(scopes, models.ScopeWrite)+ }return &auth.TokenInfo{UserID: strconv.Itoa(identity.UserId),+ Scopes: scopes,Expiration: expires,Extra: map[string]any{"email": identity.Email},}, nildiff --git a/backend/app/services/mcpmount/mcpmount_test.go b/backend/app/services/mcpmount/mcpmount_test.gonew file mode 100644index 00000000..c14f916f--- /dev/null+++ b/backend/app/services/mcpmount/mcpmount_test.go@@ -0,0 +1,54 @@+package mcpmount++import (+ "slices"+ "testing"+ "time"++ "github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/services"+)++func TestVerifyBearer_writeScopeOnlyForAgentWriteCredentials(t *testing.T) {+ previous := config.Config+ config.Config = &config.Cfg{JWTSecret: "mcpmount-test-secret-0123456789abcdefgh"}+ t.Cleanup(func() { config.Config = previous })+ if err := services.InitJWT(); err != nil {+ t.Fatal(err)+ }++ session, err := services.GenerateToken(1, "[email protected]")+ if err != nil {+ t.Fatal(err)+ }+ read, err := services.GenerateAccessToken(1, "[email protected]", models.ScopeRead, "traceway-cli", 15*time.Minute)+ if err != nil {+ t.Fatal(err)+ }+ write, err := services.GenerateAccessToken(1, "[email protected]", models.ScopeWrite, "traceway-cli-write", 15*time.Minute)+ if err != nil {+ t.Fatal(err)+ }++ for _, tc := range []struct {+ name string+ token string+ wantWrite bool+ }{+ {"dashboard session", session, false},+ {"read agent token", read, false},+ {"write agent token", write, true},+ } {+ info, err := verifyBearer(t.Context(), tc.token, nil)+ if err != nil {+ t.Fatalf("%s: %v", tc.name, err)+ }+ if !slices.Contains(info.Scopes, models.ScopeRead) {+ t.Errorf("%s: scopes %v must include read", tc.name, info.Scopes)+ }+ if got := slices.Contains(info.Scopes, models.ScopeWrite); got != tc.wantWrite {+ t.Errorf("%s: write scope = %v, want %v", tc.name, got, tc.wantWrite)+ }+ }+}diff --git a/backend/cmd/run.go b/backend/cmd/run.goindex 3649b7d9..130b5cda 100644--- a/backend/cmd/run.go+++ b/backend/cmd/run.go@@ -259,11 +259,15 @@ func Run(opts ...Option) {router.Match(wellKnown, "/.well-known/oauth-authorization-server", middleware.WellKnownCors, controllers.WellKnownController.AuthorizationServer)router.Match(wellKnown, "/.well-known/oauth-protected-resource", middleware.WellKnownCors, controllers.WellKnownController.ProtectedResource)router.Match(wellKnown, "/.well-known/oauth-protected-resource"+mcpmount.Path, middleware.WellKnownCors, controllers.WellKnownController.ProtectedResourceMCP)+ router.Match(wellKnown, "/.well-known/oauth-protected-resource"+mcpmount.WritePath, middleware.WellKnownCors, controllers.WellKnownController.ProtectedResourceMCPWrite)- mcpHandler := mcpmount.GinHandler(router, "0.0.1")+ mcpHandler := mcpmount.GinHandler(router, "0.0.1", false)+ mcpWriteHandler := mcpmount.GinHandler(router, "0.0.1", true)mcpMethods := []string{http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodOptions}router.Match(mcpMethods, mcpmount.Path, middleware.MCPCors, mcpHandler)router.Match(mcpMethods, mcpmount.Path+"/", middleware.MCPCors, mcpHandler)+ router.Match(mcpMethods, mcpmount.WritePath, middleware.MCPCors, mcpWriteHandler)+ router.Match(mcpMethods, mcpmount.WritePath+"/", middleware.MCPCors, mcpWriteHandler)apiOnly := cfg.APIOnly == "true"diff --git a/cli/.golangci.yml b/cli/.golangci.ymlindex d7dcac65..39e039ae 100644--- a/cli/.golangci.yml+++ b/cli/.golangci.yml@@ -9,6 +9,11 @@ version: "2"run:# cli/test/smoke sits behind //go:build smoke, so the default package load# cannot see it. It is the module's largest end-to-end surface; lint it too.+ #+ # This lints the read build (traceway). The write build (traceway-write,+ # -tags write) is a second pass: `just lint` and CI run it again with+ # --build-tags write, which golangci-lint adds to the tags listed here, so+ # each edition's own files (edition_read.go, edition_write.go) get linted.build-tags:- smokediff --git a/cli/README.md b/cli/README.mdindex 089e5b74..7654d7d7 100644--- a/cli/README.md+++ b/cli/README.md@@ -4,6 +4,8 @@ A Go CLI for the [Traceway](https://github.com/tracewayapp/traceway) observabili## Install+Add `-s -- --write` to the install command below for `traceway-write`, the separate build that can change data.+One-line install for macOS and Linux (runs [`install.sh`](install.sh): detects OS/arch, downloads the latest release, verifies its sha256, installs to `/usr/local/bin` or `~/.local/bin` — no sudo; `TRACEWAY_CLI_VERSION` pins a version, `TRACEWAY_INSTALL_DIR` overrides the target):```bash@@ -61,8 +63,6 @@ traceway metrics query --name http.server.duration --aggregation avg --since 1h| `traceway exceptions list` | Recent grouped exceptions || `traceway exceptions show <hash>` | A single exception group + occurrences || `traceway exceptions occurrence <id> --recorded-at <t>` | A single occurrence by id (+ `sessionId` and recording) |-| `traceway exceptions archive <hash>...` | Archive one or more groups (mutating; needs `--yes` non-interactively) |-| `traceway exceptions unarchive <hash>...` | Unarchive (mutating; needs `--yes` non-interactively) || `traceway logs query` | Query logs with severity / service / search filters || `traceway endpoints list` | Per-endpoint p50/p95/p99 stats || `traceway endpoints show <id> --recorded-at <t>` | A single request (transaction) by id: spans + linked errors |@@ -71,6 +71,10 @@ traceway metrics query --name http.server.duration --aggregation avg --since 1h| `traceway sessions show <id> --started-at <t>` | A single session by id + the exceptions that fired in it || `traceway traces show <id> --recorded-at <t>` | A distributed trace: every service node sharing the id || `traceway metrics query` | Time-series metric queries |+| `traceway pages {list,show}` | On-call pages and their delivery log |+| `traceway alerts list` | Alert rules with enabled and snoozed state |+| `traceway monitors {list,show}` | Uptime monitors and their incidents |+| `traceway post-mortems {list,show}` | Post-mortem documents || `traceway mcp` | Serve the MCP server over stdio (see "MCP server" below) |Run `traceway <command> --help` for full per-command flags.@@ -135,9 +139,30 @@ Envelope shape:The `error` field is a stable snake_case identifier. LLMs/scripts can branch on it.-## Mutations + confirmation+## traceway-write++`traceway` is read only. Write commands live in a second build of the same+source, `traceway-write` (`go build -tags write`, or `just build`), with its own+config and state directory (`traceway-write`), its own OAuth client id+(`traceway-cli-write`) and therefore its own login. The edition is chosen by+`cmd/traceway/edition_read.go` / `edition_write.go`; the write-only commands are+in `edition_write.go` and `exceptions_write.go`, and the read build answers them+with a `write_required` error.++| Command | Purpose |+|---|---|+| `traceway-write exceptions archive\|unarchive <hash>...` | Archive or unarchive issues |+| `traceway-write pages ack\|resolve <id>` | Acknowledge or resolve an on-call page (`--archive-issue`) |+| `traceway-write alerts enable\|disable\|snooze <id>` | Toggle an alert rule (idempotent) or snooze it (`--minutes`, 0 clears) |+| `traceway-write monitors run <id>` | Queue an immediate monitor run |+| `traceway-write post-mortems create\|update` | Write post-mortems (`--title`, `--content-file`, `--tag`, `--incident`; update only changes the flags passed) |+| `traceway-write endpoints mark-slow <endpoint>` | Accepted latency for an endpoint (`--offset-ms`, `--reason`) |++The server decides whether a write goes through: the credential needs the+`traceway:write` scope and the organization must have Agent Access turned on.+See the [Agent Write Access docs](https://docs.tracewayapp.com/learn/agent-write-access).-`exceptions archive` and `exceptions unarchive` require explicit consent because they change server state:+Every write requires explicit consent:- Pass `--yes` to skip the prompt.- Or set `TRACEWAY_ASSUME_YES=1` in the environment.@@ -161,10 +186,11 @@ headless use set `TRACEWAY_URL` + `TRACEWAY_TOKEN` (a `twp_` personal accesstoken), plus optional `TRACEWAY_PROJECT`, and no CLI session is needed.Each CLI query command maps 1:1 to a tool (`exceptions list` becomes-`list_exceptions`, and so on); only `archive_exceptions`/`unarchive_exceptions`-mutate, and they are annotated accordingly. The server also exposes the-Traceway debugging playbooks as MCP resources (`traceway://knowledge/*`) and-prompts (`debug_issue`, `investigate_performance`, `whats_broken`,+`list_exceptions`, and so on). `traceway mcp` has no mutating tools; the ten+write tools exist only in `traceway-write mcp` and on `/mcp/write`. The server+also exposes the Traceway playbooks and the product guide as MCP resources+(`traceway://knowledge/*`, `traceway://knowledge/learn/*`) and prompts+(`debug_issue`, `investigate_performance`, `whats_broken`,`resolve_notification`).Every tool declares an output schema, so results come back as validated@@ -175,10 +201,16 @@ as the bearer token) - `claude mcp add --transport http tracewayhttps://<instance>/mcp` needs no local install at all.The implementation lives in `pkg/mcpserver` (importable, transport-agnostic;-the stdio command is a thin wrapper). The playbook markdown in+the stdio command is a thin wrapper). `Config.AllowWrite` registers the write+tools and the write playbook; `traceway-write mcp` and the backend's+`/mcp/write` set it, `traceway mcp` and `/mcp` never do. The playbook markdown in`pkg/mcpserver/knowledge/` is the canonical source for the published-`skills/traceway` Claude Code skill: edit the chunks, then run-`just gen-skills` (drift is CI-checked).+`skills/traceway` skill, the `skills/traceway-learn` product guide (from+`knowledge/learn/`, one file per area) and the+`plugins/tw-write/skills/traceway-write` skill: edit the chunks, then run+`just gen-skills` (drift is CI-checked). A new `learn/` file also needs an+entry in `knowledgeResources` and in skillgen's `learnTopics`; tests fail+otherwise.## Smoke testingdiff --git a/cli/cmd/traceway/credentials.go b/cli/cmd/traceway/credentials.goindex cfba711c..abf51863 100644--- a/cli/cmd/traceway/credentials.go+++ b/cli/cmd/traceway/credentials.go@@ -71,16 +71,17 @@ func updateProfileTokens(profileName string, ts *client.TokenSet) error {return st.Save()}-// loadProfileJWT reads just the stored access token for a profile from disk,-// returning "" if state can't be read. The refresher uses it to adopt a token-// another concurrent process may have already rotated, avoiding a redundant-// refresh that would trip server-side reuse detection.-func loadProfileJWT(profileName string) string {+// loadProfileTokens reads the stored access and refresh tokens for a profile+// from disk, returning empty strings if state can't be read. The refresher uses+// them to adopt a rotation another concurrent process already made, avoiding a+// redundant refresh that would trip server-side reuse detection.+func loadProfileTokens(profileName string) (jwt, refreshToken string) {st, err := state.Load()if err != nil {- return ""+ return "", ""}- return st.Profiles[profileName].JWT+ sp := st.Profiles[profileName]+ return sp.JWT, sp.RefreshToken}func expiresAtUnix(expiresInSeconds int) int64 {diff --git a/cli/cmd/traceway/edition_read.go b/cli/cmd/traceway/edition_read.gonew file mode 100644index 00000000..f0e7f3ed--- /dev/null+++ b/cli/cmd/traceway/edition_read.go@@ -0,0 +1,52 @@+//go:build !write++package main++import (+ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++const (+ editionWrite = false+ editionShort = "CLI for the Traceway observability platform (read-only)"+ deviceClientID = "traceway-cli"+ loginScope = client.ScopeRead+)++// writeOnlyCommands are the write build's subcommands. The read build answers+// them with a pointer to traceway-write instead of printing the parent's help,+// which would read as if the command half-worked.+var writeOnlyCommands = map[string][]string{+ "exceptions": {"archive", "unarchive"},+ "pages": {"ack", "resolve"},+ "alerts": {"enable", "disable", "snooze"},+ "monitors": {"run"},+ "post-mortems": {"create", "update"},+ "endpoints": {"mark-slow"},+}++func addWriteCommands(root *cobra.Command) {+ for _, sub := range root.Commands() {+ for _, name := range writeOnlyCommands[sub.Name()] {+ sub.AddCommand(&cobra.Command{+ Use: name,+ Hidden: true,+ DisableFlagParsing: true,+ RunE: func(cmd *cobra.Command, _ []string) error {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "write_required",+ Message: "'" + cmd.Parent().Name() + " " + name + "' changes data, and this traceway CLI is read-only",+ Hint: "install the separate traceway-write CLI (install.sh --write), log in with it, and ask an organization admin to turn on Settings > Agent Access",+ ExitCode: exitcode.Usage,+ })+ return newCLIError(exitcode.Usage, "write_required")+ },+ })+ }+ }+}diff --git a/cli/cmd/traceway/edition_read_test.go b/cli/cmd/traceway/edition_read_test.gonew file mode 100644index 00000000..e6993e8b--- /dev/null+++ b/cli/cmd/traceway/edition_read_test.go@@ -0,0 +1,70 @@+//go:build !write++package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestReadEdition_hasNoWriteCommands(t *testing.T) {+ seedSessionFor(t, "http://127.0.0.1:1")+ for _, args := range [][]string{+ {"exceptions", "archive", "--yes", "abc"},+ {"pages", "ack", "1"},+ {"alerts", "snooze", "1"},+ {"monitors", "run", "1"},+ {"post-mortems", "create", "--title", "x"},+ {"endpoints", "mark-slow", "GET /"},+ } {+ _, stderr, err := runCmd(t, "", append(args, "--output", "json")...)+ if err == nil || !strings.Contains(stderr.String(), "write_required") || !strings.Contains(stderr.String(), "traceway-write") {+ t.Errorf("%v in the read-only build: err=%v stderr=%s", args, err, stderr.String())+ }+ }+}++func TestReadEdition_passwordLoginAsksForReadScope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = json.NewDecoder(r.Body).Decode(&body)+ _, _ = w.Write([]byte(`{"token":"jwt"}`))+ }))+ defer srv.Close()++ if _, stderr, err := runCmd(t, "pw\n", "login", "--url", srv.URL, "--username", "[email protected]", "--password-stdin"); err != nil {+ t.Fatalf("login: %v %s", err, stderr.String())+ }+ if body["scope"] != "traceway:read" {+ t.Errorf("password login must ask for a read-scoped token, body = %v", body)+ }+ if !strings.HasPrefix(newRootCmd().Use, "traceway") || newRootCmd().Use != "traceway" {+ t.Errorf("read build binary name = %q", newRootCmd().Use)+ }+}++func TestReadEdition_refusesWriteTokens(t *testing.T) {+ called := false+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ called = true+ _, _ = w.Write([]byte(`[]`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "login", "--url", srv.URL, "--token", "tww_abc", "--output", "json")+ if err == nil || !strings.Contains(stderr.String(), "write token") || called {+ t.Errorf("login --token with a tww_ token must be refused before any request, got err=%v called=%v stderr=%s", err, called, stderr.String())+ }++ t.Setenv("TRACEWAY_URL", srv.URL)+ t.Setenv("TRACEWAY_TOKEN", "tww_abc")+ if _, err := resolveMcpConfig(&strings.Builder{}); err == nil || !strings.Contains(err.Error(), "write token") {+ t.Errorf("mcp with a tww_ TRACEWAY_TOKEN must be refused, got %v", err)+ }+}diff --git a/cli/cmd/traceway/edition_write.go b/cli/cmd/traceway/edition_write.gonew file mode 100644index 00000000..1bd260cb--- /dev/null+++ b/cli/cmd/traceway/edition_write.go@@ -0,0 +1,329 @@+//go:build write++package main++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "os"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/appdir"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++const (+ editionWrite = true+ editionShort = "CLI for the Traceway observability platform, with write access"+ deviceClientID = "traceway-cli-write"+ loginScope = client.ScopeWrite+)++func init() {+ appdir.Name = "traceway-write"+ appdir.Binary = "traceway-write"+}++func addWriteCommands(root *cobra.Command) {+ for _, sub := range root.Commands() {+ switch sub.Name() {+ case "exceptions":+ sub.AddCommand(newExceptionsArchiveCmd(), newExceptionsUnarchiveCmd())+ case "pages":+ sub.AddCommand(newPagesAckCmd(), newPagesResolveCmd())+ case "alerts":+ sub.AddCommand(newAlertsEnableCmd(true), newAlertsEnableCmd(false), newAlertsSnoozeCmd())+ case "monitors":+ sub.AddCommand(newMonitorsRunCmd())+ case "post-mortems":+ sub.AddCommand(newPostMortemsCreateCmd(), newPostMortemsUpdateCmd())+ case "endpoints":+ sub.AddCommand(newEndpointsMarkSlowCmd())+ }+ }+}++func runWrite(cmd *cobra.Command, summary []string, result map[string]any, call func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error)) error {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ if err := confirmMutation(cmd, summary); err != nil {+ return err+ }+ raw, err := call(cmd.Context(), sess.Client(), sess.ProjectID)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }+ if len(raw) == 0 {+ raw, _ = json.Marshal(result)+ }+ return renderRaw(cmd, mode, raw, func(w io.Writer, _ any) error {+ _, err := fmt.Fprintln(w, result["message"])+ return err+ })+}++func newPagesAckCmd() *cobra.Command {+ return &cobra.Command{+ Use: "ack <id>",+ Short: "Acknowledge an open page so it stops escalating",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "page id")+ if err != nil {+ return err+ }+ return runWrite(cmd, []string{fmt.Sprintf("About to acknowledge page %d. Escalation stops for everyone.", id)},+ map[string]any{"action": "acknowledge", "id": id, "message": fmt.Sprintf("Acknowledged page %d.", id)},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return nil, c.AcknowledgePage(ctx, projectID, id)+ })+ },+ }+}++func newPagesResolveCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "resolve <id>",+ Short: "Resolve a page",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "page id")+ if err != nil {+ return err+ }+ archive, _ := cmd.Flags().GetBool("archive-issue")+ summary := fmt.Sprintf("About to resolve page %d.", id)+ if archive {+ summary = fmt.Sprintf("About to resolve page %d and archive the issue it was opened for.", id)+ }+ return runWrite(cmd, []string{summary},+ map[string]any{"action": "resolve", "id": id, "archivedIssue": archive, "message": fmt.Sprintf("Resolved page %d.", id)},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return nil, c.ResolvePage(ctx, projectID, id, archive)+ })+ },+ }+ cmd.Flags().Bool("archive-issue", false, "Also archive the issue the page was opened for")+ return cmd+}++func newAlertsEnableCmd(enabled bool) *cobra.Command {+ verb, use := "disable", "disable <id>"+ if enabled {+ verb, use = "enable", "enable <id>"+ }+ return &cobra.Command{+ Use: use,+ Short: fmt.Sprintf("%s an alert rule", map[bool]string{true: "Enable", false: "Disable"}[enabled]),+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "rule id")+ if err != nil {+ return err+ }+ return runWrite(cmd, []string{fmt.Sprintf("About to %s alert rule %d.", verb, id)},+ map[string]any{"action": verb, "id": id, "message": fmt.Sprintf("Alert rule %d is %sd.", id, verb)},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.SetNotificationRuleEnabled(ctx, projectID, id, enabled)+ })+ },+ }+}++func newAlertsSnoozeCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "snooze <id>",+ Short: "Snooze an alert rule (muted for N minutes, then back on its own)",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "rule id")+ if err != nil {+ return err+ }+ minutes, _ := cmd.Flags().GetInt("minutes")+ if minutes < 0 {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ return renderUsageError(cmd.ErrOrStderr(), mode, "--minutes must be 0 or greater", appdir.Binary+" alerts snooze <id> --minutes 60")+ }+ summary := fmt.Sprintf("About to snooze alert rule %d for %d minutes.", id, minutes)+ message := fmt.Sprintf("Snoozed alert rule %d for %d minutes.", id, minutes)+ if minutes == 0 {+ summary = fmt.Sprintf("About to clear the snooze on alert rule %d.", id)+ message = fmt.Sprintf("Cleared the snooze on alert rule %d.", id)+ }+ return runWrite(cmd, []string{summary},+ map[string]any{"action": "snooze", "id": id, "minutes": minutes, "message": message},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.SnoozeNotificationRule(ctx, projectID, id, minutes)+ })+ },+ }+ cmd.Flags().Int("minutes", 60, "Snooze duration in minutes; 0 clears the snooze")+ return cmd+}++func newMonitorsRunCmd() *cobra.Command {+ return &cobra.Command{+ Use: "run <id>",+ Short: "Queue an immediate run of a monitor",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "monitor id")+ if err != nil {+ return err+ }+ return runWrite(cmd, []string{fmt.Sprintf("About to queue a run of monitor %d.", id)},+ map[string]any{"action": "run", "id": id, "message": fmt.Sprintf("Queued a run of monitor %d.", id)},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.RunCheck(ctx, projectID, id)+ })+ },+ }+}++func readContentFlag(cmd *cobra.Command) (*string, error) {+ path, _ := cmd.Flags().GetString("content-file")+ if path == "" {+ return nil, nil+ }+ var b []byte+ var err error+ if path == "-" {+ b, err = io.ReadAll(cmd.InOrStdin())+ } else {+ b, err = os.ReadFile(path)+ }+ if err != nil {+ return nil, err+ }+ content := string(b)+ return &content, nil+}++func newPostMortemsCreateCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "create",+ Short: "Create a post-mortem",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ title, _ := cmd.Flags().GetString("title")+ if title == "" {+ return renderUsageError(cmd.ErrOrStderr(), mode, "--title is required", appdir.Binary+" post-mortems create --title <title> --content-file notes.md")+ }+ content, err := readContentFlag(cmd)+ if err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, "reading --content-file: "+err.Error(), "")+ }+ tags, _ := cmd.Flags().GetStringSlice("tag")+ incident, _ := cmd.Flags().GetInt("incident")+ in := client.PostMortemInput{Title: title, Tags: tags}+ if content != nil {+ in.ContentMd = *content+ }+ if incident > 0 {+ in.IncidentId = &incident+ }+ return runWrite(cmd, []string{fmt.Sprintf("About to create post-mortem %q.", title)},+ map[string]any{"action": "create", "message": "Created the post-mortem."},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.CreatePostMortem(ctx, projectID, in)+ })+ },+ }+ cmd.Flags().String("title", "", "Post-mortem title")+ cmd.Flags().String("content-file", "", "Markdown file with the body, or - for stdin")+ cmd.Flags().StringSlice("tag", nil, "Tag (repeatable)")+ cmd.Flags().Int("incident", 0, "Incident id to link")+ return cmd+}++func newPostMortemsUpdateCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "update <id>",+ Short: "Update a post-mortem; only the flags you pass change",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ id, err := intArg(cmd, args[0], "post-mortem id")+ if err != nil {+ return err+ }+ var patch client.PostMortemPatch+ if cmd.Flags().Changed("title") {+ title, _ := cmd.Flags().GetString("title")+ patch.Title = &title+ }+ if patch.ContentMd, err = readContentFlag(cmd); err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, "reading --content-file: "+err.Error(), "")+ }+ if cmd.Flags().Changed("tag") {+ tags, _ := cmd.Flags().GetStringSlice("tag")+ patch.Tags = &tags+ }+ if incident, _ := cmd.Flags().GetInt("incident"); incident > 0 {+ patch.IncidentId = &incident+ }+ patch.UnlinkIncident, _ = cmd.Flags().GetBool("unlink-incident")+ patch.ExpectedUpdatedAt, _ = cmd.Flags().GetString("expected-updated-at")+ if patch.IncidentId != nil && patch.UnlinkIncident {+ return renderUsageError(cmd.ErrOrStderr(), mode, "pass --incident or --unlink-incident, not both", "")+ }+ if patch.ContentMd != nil && patch.ExpectedUpdatedAt == "" {+ return renderUsageError(cmd.ErrOrStderr(), mode, "--content-file replaces the whole body, so --expected-updated-at is required",+ "pass the updatedAt from the '"+appdir.Binary+" post-mortems show <id>' your revision is based on")+ }+ if patch.Title == nil && patch.ContentMd == nil && patch.Tags == nil && patch.IncidentId == nil && !patch.UnlinkIncident {+ return renderUsageError(cmd.ErrOrStderr(), mode, "nothing to update", appdir.Binary+" post-mortems update <id> --title <title> | --content-file <file> --expected-updated-at <t> | --tag <tag> | --incident <id> | --unlink-incident")+ }+ return runWrite(cmd, []string{fmt.Sprintf("About to update post-mortem %d.", id)},+ map[string]any{"action": "update", "id": id, "message": fmt.Sprintf("Updated post-mortem %d.", id)},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.UpdatePostMortem(ctx, projectID, id, patch)+ })+ },+ }+ cmd.Flags().String("title", "", "New title")+ cmd.Flags().String("content-file", "", "Markdown file replacing the body, or - for stdin")+ cmd.Flags().StringSlice("tag", nil, "Replace the tags (repeatable)")+ cmd.Flags().Int("incident", 0, "Incident id to link")+ cmd.Flags().Bool("unlink-incident", false, "Remove the incident link")+ cmd.Flags().String("expected-updated-at", "", "updatedAt of the version the edit is based on (from post-mortems show); a newer document fails with a conflict instead of being overwritten")+ return cmd+}++func newEndpointsMarkSlowCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "mark-slow <endpoint>",+ Short: "Mark an endpoint as expected-slow (--offset-ms 0 removes the mark)",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ offset, _ := cmd.Flags().GetUint32("offset-ms")+ reason, _ := cmd.Flags().GetString("reason")+ endpoint := args[0]+ prompt := fmt.Sprintf("About to set the accepted latency of %q to %dms.", endpoint, offset)+ message := fmt.Sprintf("Set the accepted latency of %s to %dms.", endpoint, offset)+ if offset == 0 {+ prompt = fmt.Sprintf("About to remove the expected-slow mark from %q.", endpoint)+ message = fmt.Sprintf("Removed the expected-slow mark from %s.", endpoint)+ }+ return runWrite(cmd, []string{prompt},+ map[string]any{"action": "mark-slow", "endpoint": endpoint, "offsetMs": offset, "message": message},+ func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return nil, c.SetSlowEndpoint(ctx, projectID, client.SetSlowEndpointRequest{Endpoint: endpoint, OffsetMs: offset, Reason: reason})+ })+ },+ }+ cmd.Flags().Uint32("offset-ms", 0, "Accepted extra latency in milliseconds; 0 removes the mark (required)")+ cmd.Flags().String("reason", "", "Why this latency is acceptable")+ // Required because 0 removes the mark: a forgotten flag must not.+ _ = cmd.MarkFlagRequired("offset-ms")+ return cmd+}diff --git a/cli/cmd/traceway/edition_write_test.go b/cli/cmd/traceway/edition_write_test.gonew file mode 100644index 00000000..05ce7570--- /dev/null+++ b/cli/cmd/traceway/edition_write_test.go@@ -0,0 +1,291 @@+//go:build write++package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/appdir"+)++func TestWriteEdition_identity(t *testing.T) {+ if appdir.Name != "traceway-write" || appdir.Binary != "traceway-write" || newRootCmd().Use != "traceway-write" {+ t.Errorf("write build identity = dir %q, binary %q, use %q", appdir.Name, appdir.Binary, newRootCmd().Use)+ }+ if deviceClientID != "traceway-cli-write" {+ t.Errorf("device client = %q", deviceClientID)+ }+}++func TestWriteEdition_passwordLoginAsksForWriteScope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _ = json.NewDecoder(r.Body).Decode(&body)+ _, _ = w.Write([]byte(`{"token":"jwt"}`))+ }))+ defer srv.Close()++ if _, stderr, err := runCmd(t, "pw\n", "login", "--url", srv.URL, "--username", "[email protected]", "--password-stdin"); err != nil {+ t.Fatalf("login: %v %s", err, stderr.String())+ }+ if body["scope"] != "traceway:write" {+ t.Errorf("write login must ask for a write-scoped token, body = %v", body)+ }+}++type recorded struct {+ mu sync.Mutex+ calls []string+ body map[string]any+}++func (r *recorded) add(req *http.Request) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.calls = append(r.calls, req.Method+" "+req.URL.Path)+ if req.Method != http.MethodGet {+ r.body = nil+ _ = json.NewDecoder(req.Body).Decode(&r.body)+ }+}++func TestPagesAck_requiresConfirmationThenAcknowledges(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ _, _ = w.Write([]byte(`{"message":"Page acknowledged"}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ if _, _, err := runCmd(t, "", "pages", "ack", "7", "--output", "json"); err == nil || len(rec.calls) != 0 {+ t.Fatalf("a non-TTY write without --yes must be refused before any request, calls = %v", rec.calls)+ }+ stdout, stderr, err := runCmd(t, "", "pages", "ack", "7", "--yes", "--output", "json")+ if err != nil {+ t.Fatalf("ack: %v %s", err, stderr.String())+ }+ if len(rec.calls) != 1 || rec.calls[0] != "POST /api/pages/7/acknowledge" {+ t.Errorf("calls = %v", rec.calls)+ }+ if !strings.Contains(stdout.String(), "acknowledge") {+ t.Errorf("stdout = %s", stdout.String())+ }+}++func TestPagesResolve_archiveIssueFlag(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ if _, stderr, err := runCmd(t, "", "pages", "resolve", "9", "--archive-issue", "--yes", "--output", "json"); err != nil {+ t.Fatalf("resolve: %v %s", err, stderr.String())+ }+ if rec.calls[0] != "POST /api/pages/9/resolve" || rec.body["archiveIssue"] != true {+ t.Errorf("calls = %v body = %v", rec.calls, rec.body)+ }+}++func TestAlertsEnableDisable_setsAnExplicitState(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ if strings.Contains(r.URL.Path, "/99/") {+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write([]byte(`{"error":"rule not found"}`))+ return+ }+ rec.mu.Lock()+ enabled, _ := rec.body["enabled"].(bool)+ rec.mu.Unlock()+ _, _ = fmt.Fprintf(w, `{"id":4,"enabled":%t}`, enabled)+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ for _, tc := range []struct {+ command string+ want bool+ }{{"enable", true}, {"disable", false}} {+ rec.calls = nil+ if _, stderr, err := runCmd(t, "", "alerts", tc.command, "4", "--yes", "--output", "json"); err != nil {+ t.Fatalf("%s: %v %s", tc.command, err, stderr.String())+ }+ if len(rec.calls) != 1 || rec.calls[0] != "POST /api/notification-rules/4/toggle" || rec.body["enabled"] != tc.want {+ t.Errorf("%s must send one toggle with enabled=%v, calls = %v body = %v", tc.command, tc.want, rec.calls, rec.body)+ }+ }++ if _, _, err := runCmd(t, "", "alerts", "disable", "99", "--yes", "--output", "json"); err == nil {+ t.Error("an unknown rule id should fail")+ }+}++// A server older than the toggle route's enabled field ignores it and flips the+// rule. The CLI must notice from the response and undo the flip, so disabling+// an already-disabled rule leaves it disabled instead of turning it on.+func TestAlertsEnableDisable_undoesAnOlderServersFlip(t *testing.T) {+ var mu sync.Mutex+ ruleEnabled := false+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ mu.Lock()+ defer mu.Unlock()+ ruleEnabled = !ruleEnabled+ _, _ = fmt.Fprintf(w, `{"id":4,"enabled":%t}`, ruleEnabled)+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ for _, tc := range []struct {+ command string+ startedOn bool+ wantCalls int+ }{+ {"disable", false, 2}, // already off: flipped on, then back off+ {"disable", true, 1}, // the flip happens to match+ {"enable", true, 2},+ {"enable", false, 1},+ } {+ mu.Lock()+ ruleEnabled = tc.startedOn+ mu.Unlock()+ rec.calls = nil+ if _, stderr, err := runCmd(t, "", "alerts", tc.command, "4", "--yes", "--output", "json"); err != nil {+ t.Fatalf("%s from enabled=%v: %v %s", tc.command, tc.startedOn, err, stderr.String())+ }+ mu.Lock()+ if want := tc.command == "enable"; ruleEnabled != want || len(rec.calls) != tc.wantCalls {+ t.Errorf("%s from enabled=%v: rule enabled=%v after %d calls, want %v after %d", tc.command, tc.startedOn, ruleEnabled, len(rec.calls), want, tc.wantCalls)+ }+ mu.Unlock()+ }+}++func TestAlertsSnooze_sendsMinutes(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ _, _ = w.Write([]byte(`{"id":4}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ if _, stderr, err := runCmd(t, "", "alerts", "snooze", "4", "--minutes", "30", "--yes", "--output", "json"); err != nil {+ t.Fatalf("snooze: %v %s", err, stderr.String())+ }+ if rec.calls[0] != "POST /api/notification-rules/4/snooze" || rec.body["durationMinutes"] != float64(30) {+ t.Errorf("calls = %v body = %v", rec.calls, rec.body)+ }+}++func TestPostMortemsUpdate_keepsFieldsItWasNotGiven(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ if r.Method == http.MethodGet {+ _, _ = w.Write([]byte(`{"id":5,"title":"Redis outage","contentMd":"old","tags":["redis"],"incidentId":11,"updatedAt":"2026-10-15T10:05:00Z"}`))+ return+ }+ _, _ = w.Write([]byte(`{"id":5}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ if _, stderr, err := runCmd(t, "new body", "post-mortems", "update", "5", "--content-file", "-", "--expected-updated-at", "2026-10-15T10:00:00Z", "--yes", "--output", "json"); err != nil {+ t.Fatalf("update: %v %s", err, stderr.String())+ }+ if rec.calls[1] != "PUT /api/post-mortems/5" {+ t.Fatalf("calls = %v", rec.calls)+ }+ if rec.body["title"] != "Redis outage" || rec.body["contentMd"] != "new body" || rec.body["incidentId"] != float64(11) {+ t.Errorf("update body = %v", rec.body)+ }+ if rec.body["expectedUpdatedAt"] != "2026-10-15T10:00:00Z" {+ t.Errorf("the revision the edit is based on must be sent, not the one re-read before the PUT: expectedUpdatedAt = %v", rec.body["expectedUpdatedAt"])+ }+ tags, _ := rec.body["tags"].([]any)+ if len(tags) != 1 || tags[0] != "redis" {+ t.Errorf("tags = %v", rec.body["tags"])+ }+}++func TestPostMortemsUpdate_contentNeedsExpectedUpdatedAt(t *testing.T) {+ seedSessionFor(t, "http://127.0.0.1:1")+ _, stderr, err := runCmd(t, "new body", "post-mortems", "update", "5", "--content-file", "-", "--yes", "--output", "json")+ if err == nil || !strings.Contains(stderr.String(), "--expected-updated-at is required") {+ t.Fatalf("want a usage error, got %v %s", err, stderr.String())+ }+}++func TestPostMortemsUpdate_unlinkIncident(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ if r.Method == http.MethodGet {+ _, _ = w.Write([]byte(`{"id":5,"title":"Redis outage","contentMd":"old","tags":[],"incidentId":11,"updatedAt":"2026-10-15T10:05:00Z"}`))+ return+ }+ _, _ = w.Write([]byte(`{"id":5}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ if _, stderr, err := runCmd(t, "", "post-mortems", "update", "5", "--unlink-incident", "--yes", "--output", "json"); err != nil {+ t.Fatalf("update: %v %s", err, stderr.String())+ }+ if v, ok := rec.body["incidentId"]; !ok || v != nil {+ t.Errorf("incidentId = %v (present %v), want null", v, ok)+ }+}++func TestPostMortemsUpdate_nothingToUpdate(t *testing.T) {+ seedSessionFor(t, "http://127.0.0.1:1")+ _, stderr, err := runCmd(t, "", "post-mortems", "update", "5", "--yes", "--output", "json")+ if err == nil || !strings.Contains(stderr.String(), "nothing to update") {+ t.Fatalf("want nothing to update, got %v %s", err, stderr.String())+ }+}++func TestEndpointsMarkSlow(t *testing.T) {+ rec := &recorded{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ rec.add(r)+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ if _, stderr, err := runCmd(t, "", "endpoints", "mark-slow", "GET /export", "--offset-ms", "2000", "--reason", "batch", "--yes", "--output", "json"); err != nil {+ t.Fatalf("mark-slow: %v %s", err, stderr.String())+ }+ if rec.calls[0] != "POST /api/endpoints/slow" || rec.body["endpoint"] != "GET /export" || rec.body["offsetMs"] != float64(2000) {+ t.Errorf("calls = %v body = %v", rec.calls, rec.body)+ }++ rec.calls = nil+ if _, _, err := runCmd(t, "", "endpoints", "mark-slow", "GET /export", "--yes", "--output", "json"); err == nil || len(rec.calls) != 0 {+ t.Errorf("mark-slow without --offset-ms must fail before any request (0 would remove the mark), calls = %v", rec.calls)+ }+}diff --git a/cli/cmd/traceway/endpoints.go b/cli/cmd/traceway/endpoints.goindex d641b6d7..229e670d 100644--- a/cli/cmd/traceway/endpoints.go+++ b/cli/cmd/traceway/endpoints.go@@ -7,6 +7,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/pkg/client")@@ -55,19 +56,19 @@ func runEndpointsList(cmd *cobra.Command, _ []string) error {}if err := validatePaginationFlags(cmd); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- paginationHint("traceway endpoints list"))+ paginationHint(appdir.Binary+" endpoints list"))}page := resolvePagination(cmd)search, _ := cmd.Flags().GetString("search")orderBy, _ := cmd.Flags().GetString("order-by")if err := validateEnumFlag("--order-by", orderBy, endpointsOrderBy); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway endpoints list", "--order-by", endpointsOrderBy))+ enumFlagHint(appdir.Binary+" endpoints list", "--order-by", endpointsOrderBy))}sortDir, _ := cmd.Flags().GetString("sort-direction")if err := validateEnumFlag("--sort-direction", sortDir, sortDirections); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway endpoints list", "--sort-direction", sortDirections))+ enumFlagHint(appdir.Binary+" endpoints list", "--sort-direction", sortDirections))}c := sess.Client()@@ -141,7 +142,7 @@ func runEndpointsChart(cmd *cobra.Command, _ []string) error {metricType, _ := cmd.Flags().GetString("metric-type")if err := validateEnumFlag("--metric-type", metricType, endpointChartMetricTypes); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway endpoints chart", "--metric-type", endpointChartMetricTypes))+ enumFlagHint(appdir.Binary+" endpoints chart", "--metric-type", endpointChartMetricTypes))}intervalMin, _ := cmd.Flags().GetInt("interval-minutes")diff --git a/cli/cmd/traceway/errors.go b/cli/cmd/traceway/errors.goindex 92ef5b60..e86b40cd 100644--- a/cli/cmd/traceway/errors.go+++ b/cli/cmd/traceway/errors.go@@ -4,6 +4,7 @@ import ("errors""io"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/errclass""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/internal/output"@@ -50,7 +51,7 @@ func classifyError(err error, loginContext bool) output.ErrorEnvelope {}c := errclass.Classify(err)if c.Code == "token_expired" && flagProfile != "" {- c.Hint = "traceway login --profile " + flagProfile+ c.Hint = appdir.Binary + " login --profile " + flagProfile}return output.ErrorEnvelope{Code: c.Code,diff --git a/cli/cmd/traceway/exceptions.go b/cli/cmd/traceway/exceptions.goindex bb616235..943f20da 100644--- a/cli/cmd/traceway/exceptions.go+++ b/cli/cmd/traceway/exceptions.go@@ -1,12 +1,12 @@package mainimport (- "context""fmt""time""github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/pkg/client")@@ -24,8 +24,6 @@ func newExceptionsCmd() *cobra.Command {cmd.AddCommand(newExceptionsListCmd())cmd.AddCommand(newExceptionsShowCmd())cmd.AddCommand(newExceptionsOccurrenceCmd())- cmd.AddCommand(newExceptionsArchiveCmd())- cmd.AddCommand(newExceptionsUnarchiveCmd())return cmd}@@ -59,20 +57,20 @@ func runExceptionsList(cmd *cobra.Command, _ []string) error {}if err := validatePaginationFlags(cmd); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- paginationHint("traceway exceptions list"))+ paginationHint(appdir.Binary+" exceptions list"))}page := resolvePagination(cmd)search, _ := cmd.Flags().GetString("search")searchType, _ := cmd.Flags().GetString("search-type")if err := validateEnumFlag("--search-type", searchType, exceptionsSearchTypes); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway exceptions list", "--search-type", exceptionsSearchTypes))+ enumFlagHint(appdir.Binary+" exceptions list", "--search-type", exceptionsSearchTypes))}includeArchived, _ := cmd.Flags().GetBool("include-archived")orderBy, _ := cmd.Flags().GetString("order-by")if err := validateEnumFlag("--order-by", orderBy, exceptionsOrderBy); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway exceptions list", "--order-by", exceptionsOrderBy))+ enumFlagHint(appdir.Binary+" exceptions list", "--order-by", exceptionsOrderBy))}c := sess.Client()@@ -133,7 +131,7 @@ func runExceptionsShow(cmd *cobra.Command, args []string) error {}if err := validatePaginationFlags(cmd); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- paginationHint("traceway exceptions show"))+ paginationHint(appdir.Binary+" exceptions show"))}page := resolvePagination(cmd)page.PageSize = pickDefault(page.PageSize, 20) // detail uses 20 by default@@ -269,82 +267,6 @@ func runExceptionsOccurrence(cmd *cobra.Command, args []string) error {}}-func newExceptionsArchiveCmd() *cobra.Command {- return &cobra.Command{- Use: "archive <hash> [<hash>...]",- Short: "Archive one or more exception groups",- Args: cobra.MinimumNArgs(1),- RunE: func(cmd *cobra.Command, args []string) error {- return runExceptionsMutation(cmd, args, "archive",- func(c *client.Client, ctx context.Context, projectID string, hashes []string) error {- return c.ArchiveExceptions(ctx, projectID, hashes)- })- },- }-}--func newExceptionsUnarchiveCmd() *cobra.Command {- return &cobra.Command{- Use: "unarchive <hash> [<hash>...]",- Short: "Unarchive one or more exception groups",- Args: cobra.MinimumNArgs(1),- RunE: func(cmd *cobra.Command, args []string) error {- return runExceptionsMutation(cmd, args, "unarchive",- func(c *client.Client, ctx context.Context, projectID string, hashes []string) error {- return c.UnarchiveExceptions(ctx, projectID, hashes)- })- },- }-}--// runExceptionsMutation is the shared body for archive and unarchive. The-// 'verb' parameter controls the prompt wording and the rendered action label;-// 'doIt' is the client method to call after confirmation passes.-func runExceptionsMutation(- cmd *cobra.Command,- hashes []string,- verb string,- doIt func(c *client.Client, ctx context.Context, projectID string, hashes []string) error,-) error {- ctx := cmd.Context()- mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())-- sess, err := loadSession()- if err != nil {- return renderSessionError(cmd.ErrOrStderr(), mode, err)- }-- summary := []string{- fmt.Sprintf("About to %s %d exception group(s):", verb, len(hashes)),- }- for _, h := range hashes {- summary = append(summary, " - "+truncateHash(h, 12))- }- if err := confirmMutation(cmd, summary); err != nil {- return err- }-- c := sess.Client()- if err := doIt(c, ctx, sess.ProjectID, hashes); err != nil {- return renderAPIError(cmd.ErrOrStderr(), mode, err, false)- }-- result := map[string]any{- "action": verb,- "count": len(hashes),- "hashes": hashes,- }- switch mode {- case output.ModeJSON:- return output.RenderJSON(cmd.OutOrStdout(), result, nil)- case output.ModeYAML:- return output.RenderYAML(cmd.OutOrStdout(), result, nil)- default:- _, err := fmt.Fprintf(cmd.OutOrStdout(), "%sd %d exception group(s).\n", verb, len(hashes))- return err- }-}-// truncateHash returns hash, or its first n chars if longer. Used for// human-readable summaries; the full hash always goes to the API.func truncateHash(hash string, n int) string {diff --git a/cli/cmd/traceway/exceptions_test.go b/cli/cmd/traceway/exceptions_test.goindex 9ce87502..7a52ef55 100644--- a/cli/cmd/traceway/exceptions_test.go+++ b/cli/cmd/traceway/exceptions_test.go@@ -1,7 +1,6 @@package mainimport (- "encoding/json""errors""net/http""net/http/httptest"@@ -184,109 +183,3 @@ func TestExceptionsShow_404_writesNotFoundEnvelope(t *testing.T) {t.Errorf("expected not_found envelope, got: %s", stderr.String())}}--func TestExceptionsArchive_yes_callsClientAndRendersJSON(t *testing.T) {- var gotHashes []string- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/api/exception-stack-traces/archive" {- t.Errorf("path = %q", r.URL.Path)- }- var body map[string]any- _ = json.NewDecoder(r.Body).Decode(&body)- for _, h := range body["hashes"].([]any) {- gotHashes = append(gotHashes, h.(string))- }- _, _ = w.Write([]byte(`{"success":true}`))- }))- defer srv.Close()-- seedSessionFor(t, srv.URL)- t.Cleanup(func() { flagYes = false })-- stdout, stderr, err := runCmd(t, "", "exceptions", "archive", "--yes", "--output", "json", "h1", "h2")- if err != nil {- t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())- }- if len(gotHashes) != 2 || gotHashes[0] != "h1" || gotHashes[1] != "h2" {- t.Errorf("server got hashes %v", gotHashes)- }-- var resp map[string]any- if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {- t.Fatalf("stdout not JSON: %v\n%s", err, stdout.String())- }- if resp["action"] != "archive" {- t.Errorf("action = %v", resp["action"])- }- if resp["count"].(float64) != 2 {- t.Errorf("count = %v", resp["count"])- }-}--func TestExceptionsArchive_nonTTYWithoutYes_failsWithUsageError(t *testing.T) {- srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {- t.Fatal("server should not be called when confirmation refuses")- }))- defer srv.Close()-- seedSessionFor(t, srv.URL)-- stdout, stderr, err := runCmd(t, "", "exceptions", "archive", "--output", "json", "h1")- if err == nil {- t.Fatalf("expected error, got success: stdout=%s", stdout.String())- }- if !strings.Contains(stderr.String(), "usage_error") {- t.Errorf("stderr should contain usage_error: %s", stderr.String())- }- var ce *cliError- if !errors.As(err, &ce) || ce.code != exitcode.Usage {- t.Errorf("expected cliError(Usage), got %v", err)- }-}--func TestExceptionsArchive_requiresAtLeastOneHash(t *testing.T) {- seedSessionFor(t, "https://unused")- t.Cleanup(func() { flagYes = false })-- _, _, err := runCmd(t, "", "exceptions", "archive", "--yes")- if err == nil {- t.Fatal("expected error from missing args")- }-}--func TestExceptionsUnarchive_yes_callsClientAndRendersJSON(t *testing.T) {- var gotPath string- var gotHashes []string- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- gotPath = r.URL.Path- var body map[string]any- _ = json.NewDecoder(r.Body).Decode(&body)- for _, h := range body["hashes"].([]any) {- gotHashes = append(gotHashes, h.(string))- }- _, _ = w.Write([]byte(`{"success":true}`))- }))- defer srv.Close()-- seedSessionFor(t, srv.URL)- t.Cleanup(func() { flagYes = false })-- stdout, stderr, err := runCmd(t, "", "exceptions", "unarchive", "--yes", "--output", "json", "h1")- if err != nil {- t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())- }- if gotPath != "/api/exception-stack-traces/unarchive" {- t.Errorf("path = %q", gotPath)- }- if len(gotHashes) != 1 || gotHashes[0] != "h1" {- t.Errorf("server got hashes %v", gotHashes)- }-- var resp map[string]any- if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {- t.Fatalf("stdout not JSON: %v\n%s", err, stdout.String())- }- if resp["action"] != "unarchive" {- t.Errorf("action = %v", resp["action"])- }-}diff --git a/cli/cmd/traceway/exceptions_write.go b/cli/cmd/traceway/exceptions_write.gonew file mode 100644index 00000000..51d707c9--- /dev/null+++ b/cli/cmd/traceway/exceptions_write.go@@ -0,0 +1,89 @@+//go:build write++package main++import (+ "context"+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func newExceptionsArchiveCmd() *cobra.Command {+ return &cobra.Command{+ Use: "archive <hash> [<hash>...]",+ Short: "Archive one or more exception groups",+ Args: cobra.MinimumNArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ return runExceptionsMutation(cmd, args, "archive",+ func(c *client.Client, ctx context.Context, projectID string, hashes []string) error {+ return c.ArchiveExceptions(ctx, projectID, hashes)+ })+ },+ }+}++func newExceptionsUnarchiveCmd() *cobra.Command {+ return &cobra.Command{+ Use: "unarchive <hash> [<hash>...]",+ Short: "Unarchive one or more exception groups",+ Args: cobra.MinimumNArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ return runExceptionsMutation(cmd, args, "unarchive",+ func(c *client.Client, ctx context.Context, projectID string, hashes []string) error {+ return c.UnarchiveExceptions(ctx, projectID, hashes)+ })+ },+ }+}++// runExceptionsMutation is the shared body for archive and unarchive. The+// 'verb' parameter controls the prompt wording and the rendered action label;+// 'doIt' is the client method to call after confirmation passes.+func runExceptionsMutation(+ cmd *cobra.Command,+ hashes []string,+ verb string,+ doIt func(c *client.Client, ctx context.Context, projectID string, hashes []string) error,+) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }++ summary := []string{+ fmt.Sprintf("About to %s %d exception group(s):", verb, len(hashes)),+ }+ for _, h := range hashes {+ summary = append(summary, " - "+truncateHash(h, 12))+ }+ if err := confirmMutation(cmd, summary); err != nil {+ return err+ }++ c := sess.Client()+ if err := doIt(c, ctx, sess.ProjectID, hashes); err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ result := map[string]any{+ "action": verb,+ "count": len(hashes),+ "hashes": hashes,+ }+ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), result, nil)+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), result, nil)+ default:+ _, err := fmt.Fprintf(cmd.OutOrStdout(), "%sd %d exception group(s).\n", verb, len(hashes))+ return err+ }+}diff --git a/cli/cmd/traceway/exceptions_write_test.go b/cli/cmd/traceway/exceptions_write_test.gonew file mode 100644index 00000000..10d7cc5f--- /dev/null+++ b/cli/cmd/traceway/exceptions_write_test.go@@ -0,0 +1,120 @@+//go:build write++package main++import (+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++func TestExceptionsArchive_yes_callsClientAndRendersJSON(t *testing.T) {+ var gotHashes []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces/archive" {+ t.Errorf("path = %q", r.URL.Path)+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ for _, h := range body["hashes"].([]any) {+ gotHashes = append(gotHashes, h.(string))+ }+ _, _ = w.Write([]byte(`{"success":true}`))+ }))+ defer srv.Close()++ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ stdout, stderr, err := runCmd(t, "", "exceptions", "archive", "--yes", "--output", "json", "h1", "h2")+ if err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())+ }+ if len(gotHashes) != 2 || gotHashes[0] != "h1" || gotHashes[1] != "h2" {+ t.Errorf("server got hashes %v", gotHashes)+ }++ var resp map[string]any+ if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {+ t.Fatalf("stdout not JSON: %v\n%s", err, stdout.String())+ }+ if resp["action"] != "archive" {+ t.Errorf("action = %v", resp["action"])+ }+ if resp["count"].(float64) != 2 {+ t.Errorf("count = %v", resp["count"])+ }+}++func TestExceptionsArchive_nonTTYWithoutYes_failsWithUsageError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {+ t.Fatal("server should not be called when confirmation refuses")+ }))+ defer srv.Close()++ seedSessionFor(t, srv.URL)++ stdout, stderr, err := runCmd(t, "", "exceptions", "archive", "--output", "json", "h1")+ if err == nil {+ t.Fatalf("expected error, got success: stdout=%s", stdout.String())+ }+ if !strings.Contains(stderr.String(), "usage_error") {+ t.Errorf("stderr should contain usage_error: %s", stderr.String())+ }+ var ce *cliError+ if !errors.As(err, &ce) || ce.code != exitcode.Usage {+ t.Errorf("expected cliError(Usage), got %v", err)+ }+}++func TestExceptionsArchive_requiresAtLeastOneHash(t *testing.T) {+ seedSessionFor(t, "https://unused")+ t.Cleanup(func() { flagYes = false })++ _, _, err := runCmd(t, "", "exceptions", "archive", "--yes")+ if err == nil {+ t.Fatal("expected error from missing args")+ }+}++func TestExceptionsUnarchive_yes_callsClientAndRendersJSON(t *testing.T) {+ var gotPath string+ var gotHashes []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ for _, h := range body["hashes"].([]any) {+ gotHashes = append(gotHashes, h.(string))+ }+ _, _ = w.Write([]byte(`{"success":true}`))+ }))+ defer srv.Close()++ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagYes = false })++ stdout, stderr, err := runCmd(t, "", "exceptions", "unarchive", "--yes", "--output", "json", "h1")+ if err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())+ }+ if gotPath != "/api/exception-stack-traces/unarchive" {+ t.Errorf("path = %q", gotPath)+ }+ if len(gotHashes) != 1 || gotHashes[0] != "h1" {+ t.Errorf("server got hashes %v", gotHashes)+ }++ var resp map[string]any+ if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {+ t.Fatalf("stdout not JSON: %v\n%s", err, stdout.String())+ }+ if resp["action"] != "unarchive" {+ t.Errorf("action = %v", resp["action"])+ }+}diff --git a/cli/cmd/traceway/login.go b/cli/cmd/traceway/login.goindex 45cbc4f5..1bad2365 100644--- a/cli/cmd/traceway/login.go+++ b/cli/cmd/traceway/login.go@@ -12,6 +12,7 @@ import ("github.com/spf13/cobra""golang.org/x/term"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/config""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/internal/state"@@ -61,10 +62,10 @@ func runLogin(cmd *cobra.Command, _ []string) error {passwordMode := loginPassword || loginPasswordFile || loginUsername != ""if tokenMode && passwordMode {- return renderUsageError(cmd.ErrOrStderr(), mode, "choose one of --token or --password/--username, not both", "traceway login --help")+ return renderUsageError(cmd.ErrOrStderr(), mode, "choose one of --token or --password/--username, not both", appdir.Binary+" login --help")}if loginToken != "" && loginTokenStdin {- return renderUsageError(cmd.ErrOrStderr(), mode, "choose one of --token or --token-stdin, not both", "traceway login --help")+ return renderUsageError(cmd.ErrOrStderr(), mode, "choose one of --token or --token-stdin, not both", appdir.Binary+" login --help")}switch {@@ -107,12 +108,16 @@ func runLoginPassword(cmd *cobra.Command) error {return err}- jwt, err := client.New(url).Login(ctx, username, password)+ res, err := client.New(url).LoginScoped(ctx, username, password, loginScope)if err != nil {return renderAPIError(cmd.ErrOrStderr(), mode, err, true)}- if err := saveProfileCredentials(cfg, st, profileName, url, username, credential{Kind: state.KindPassword, AccessToken: jwt}); err != nil {+ cred := credential{Kind: state.KindPassword, AccessToken: res.Token}+ if res.RefreshToken != "" {+ cred = credential{Kind: state.KindDevice, AccessToken: res.Token, RefreshToken: res.RefreshToken, ExpiresAt: expiresAtUnix(res.ExpiresIn)}+ }+ if err := saveProfileCredentials(cfg, st, profileName, url, username, cred); err != nil {return err}diff --git a/cli/cmd/traceway/login_test.go b/cli/cmd/traceway/login_test.goindex 1e813a25..dce6c666 100644--- a/cli/cmd/traceway/login_test.go+++ b/cli/cmd/traceway/login_test.go@@ -72,6 +72,28 @@ func TestLogin_passwordStdin_success(t *testing.T) {}}+func TestLogin_passwordWithRefreshToken_isRefreshableAndRevocable(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`{"token":"access","refreshToken":"twr_refresh","expiresIn":900}`))+ }))+ defer srv.Close()++ if _, stderr, err := runCmd(t, "hunter2\n", "login", "--url", srv.URL, "--username", "[email protected]", "--password-stdin"); err != nil {+ t.Fatalf("login failed: %v %s", err, stderr.String())+ }+ st, err := state.Load()+ if err != nil {+ t.Fatal(err)+ }+ sp := st.Profiles["default"]+ if sp.JWT != "access" || sp.RefreshToken != "twr_refresh" || sp.CredentialKind != state.KindDevice || sp.TokenExpiresAt == 0 {+ t.Errorf("a scoped password login must be stored as a refreshable session, got %+v", sp)+ }+}+func TestLogin_namedProfile_secondLogin_doesNotOverrideCurrent(t *testing.T) {t.Setenv("XDG_CONFIG_HOME", t.TempDir())t.Setenv("XDG_STATE_HOME", t.TempDir())diff --git a/cli/cmd/traceway/login_token.go b/cli/cmd/traceway/login_token.goindex 901ae35f..7908f087 100644--- a/cli/cmd/traceway/login_token.go+++ b/cli/cmd/traceway/login_token.go@@ -10,6 +10,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/internal/state""github.com/tracewayapp/traceway/cli/pkg/client"@@ -35,7 +36,11 @@ func runLoginToken(cmd *cobra.Command) error {}}if token == "" {- return renderUsageError(cmd.ErrOrStderr(), mode, "no token provided", "traceway login --token <token>")+ return renderUsageError(cmd.ErrOrStderr(), mode, "no token provided", appdir.Binary+" login --token <token>")+ }+ if !editionWrite && strings.HasPrefix(token, "tww_") {+ return renderUsageError(cmd.ErrOrStderr(), mode, "this is a write token (tww_), and the read-only traceway CLI does not keep write credentials",+ "use it with 'traceway-write login --token', or create a Read only token (twp_) under Account > Personal Access Tokens")}username := loginUsername@@ -53,6 +58,9 @@ func runLoginToken(cmd *cobra.Command) error {return err}+ if editionWrite && strings.HasPrefix(token, "twp_") {+ _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "warning: this is a read-only token (twp_), so every write will be refused. Create a Read and write token (tww_) under Account > Personal Access Tokens.")+ }_, err = fmt.Fprintf(cmd.OutOrStdout(), "Stored personal access token for %s (profile: %s)\n", url, profileName)return err}diff --git a/cli/cmd/traceway/login_web.go b/cli/cmd/traceway/login_web.goindex 47e30e40..58917a77 100644--- a/cli/cmd/traceway/login_web.go+++ b/cli/cmd/traceway/login_web.go@@ -12,6 +12,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/internal/state"@@ -35,7 +36,7 @@ func runLoginWeb(cmd *cobra.Command) error {if !loginNoBrowser && !output.StdoutIsTerminal() {return renderUsageError(cmd.ErrOrStderr(), mode,"the browser device-login flow requires an interactive terminal",- "use 'traceway login --token <token>' or 'traceway login --password' for non-interactive login")+ "use '"+appdir.Binary+" login --token <token>' or '"+appdir.Binary+" login --password' for non-interactive login")}cfg, st, profileName, url, err := loadLoginContext()@@ -44,7 +45,7 @@ func runLoginWeb(cmd *cobra.Command) error {}c := client.New(url)- da, err := c.DeviceAuthorize(ctx, "")+ da, err := c.DeviceAuthorize(ctx, deviceClientID)if err != nil {// A backend that predates the device flow 404s the authorize endpoint,// or serves the SPA's index.html (a JSON syntax error). Point at the@@ -54,7 +55,7 @@ func runLoginWeb(cmd *cobra.Command) error {_ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{Code: "device_login_unsupported",Message: "this server does not support the browser device-login flow (it may be running an older Traceway version)",- Hint: "traceway login --password",+ Hint: appdir.Binary + " login --password",ExitCode: exitcode.Auth,})return newCLIError(exitcode.Auth, "device_login_unsupported")@@ -139,7 +140,7 @@ func renderDeviceError(errOut io.Writer, mode output.Mode, code, msg string) err_ = output.RenderError(errOut, mode, output.ErrorEnvelope{Code: code,Message: msg,- Hint: "traceway login",+ Hint: appdir.Binary + " login",ExitCode: exitcode.Auth,})return newCLIError(exitcode.Auth, code)diff --git a/cli/cmd/traceway/logs.go b/cli/cmd/traceway/logs.goindex 0f234f0c..a491def8 100644--- a/cli/cmd/traceway/logs.go+++ b/cli/cmd/traceway/logs.go@@ -5,6 +5,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/pkg/client")@@ -55,7 +56,7 @@ func runLogsQuery(cmd *cobra.Command, _ []string) error {}if err := validatePaginationFlags(cmd); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- paginationHint("traceway logs query"))+ paginationHint(appdir.Binary+" logs query"))}page := resolvePagination(cmd)service, _ := cmd.Flags().GetString("service")@@ -65,13 +66,13 @@ func runLogsQuery(cmd *cobra.Command, _ []string) error {searchType, _ := cmd.Flags().GetString("search-type")if err := validateEnumFlag("--search-type", searchType, logsSearchTypes); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway logs query", "--search-type", logsSearchTypes))+ enumFlagHint(appdir.Binary+" logs query", "--search-type", logsSearchTypes))}orderBy, _ := cmd.Flags().GetString("order-by")sortDir, _ := cmd.Flags().GetString("sort-direction")if err := validateEnumFlag("--sort-direction", sortDir, sortDirections); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway logs query", "--sort-direction", sortDirections))+ enumFlagHint(appdir.Binary+" logs query", "--sort-direction", sortDirections))}c := sess.Client()diff --git a/cli/cmd/traceway/mcp.go b/cli/cmd/traceway/mcp.goindex 7844da79..3d12ac18 100644--- a/cli/cmd/traceway/mcp.go+++ b/cli/cmd/traceway/mcp.go@@ -10,6 +10,7 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/pkg/client""github.com/tracewayapp/traceway/cli/pkg/mcpserver"@@ -19,17 +20,17 @@ func newMcpCmd() *cobra.Command {return &cobra.Command{Use: "mcp",Short: "Run the Traceway MCP server on stdio",- Long: `Serve the Traceway MCP server over stdio for MCP clients like Claude Code:+ Long: fmt.Sprintf(`Serve the Traceway MCP server over stdio for MCP clients like Claude Code:- claude mcp add traceway -- traceway mcp+ claude mcp add %[1]s -- %[1]s mcp-Credentials come from the CLI session (run "traceway login" first) and the-default project from "traceway projects use". Both can be overridden per call+Credentials come from the CLI session (run "%[1]s login" first) and the+default project from "%[1]s projects use". Both can be overridden per callvia each tool's project_id parameter.Headless environments can skip the CLI session entirely by settingTRACEWAY_URL and TRACEWAY_TOKEN (a personal access token or JWT), plus an-optional TRACEWAY_PROJECT default project id.`,+optional TRACEWAY_PROJECT default project id.`, appdir.Binary),Args: cobra.NoArgs,RunE: runMcp,}@@ -40,14 +41,14 @@ optional TRACEWAY_PROJECT default project id.`,func runMcp(cmd *cobra.Command, _ []string) error {cfg, err := resolveMcpConfig(cmd.ErrOrStderr())if err != nil {- _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "traceway mcp:", err)+ _, _ = fmt.Fprintln(cmd.ErrOrStderr(), appdir.Binary+" mcp:", err)return newCLIError(exitcode.Auth, "not_authenticated")}srv := mcpserver.New(cfg)err = srv.Run(cmd.Context(), &mcp.StdioTransport{})if err != nil && !errors.Is(err, cmd.Context().Err()) && !isClientDisconnect(err) {- _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "traceway mcp:", err)+ _, _ = fmt.Fprintln(cmd.ErrOrStderr(), appdir.Binary+" mcp:", err)return newCLIError(exitcode.Generic, "mcp_server_failed")}return nil@@ -81,11 +82,14 @@ func resolveMcpConfig(errOut io.Writer) (mcpserver.Config, error) {url, token := os.Getenv("TRACEWAY_URL"), os.Getenv("TRACEWAY_TOKEN")if url != "" || token != "" {if flagProfile != "" {- _, _ = fmt.Fprintln(errOut, "traceway mcp: ignoring TRACEWAY_URL/TRACEWAY_TOKEN because --profile was given")+ _, _ = fmt.Fprintln(errOut, appdir.Binary+" mcp: ignoring TRACEWAY_URL/TRACEWAY_TOKEN because --profile was given")} else {if url == "" || token == "" {return mcpserver.Config{}, errors.New("TRACEWAY_URL and TRACEWAY_TOKEN must be set together")}+ if !editionWrite && strings.HasPrefix(token, "tww_") {+ return mcpserver.Config{}, errors.New("TRACEWAY_TOKEN is a write token (tww_): run 'traceway-write mcp' for write access, or use a Read only token (twp_) here")+ }projectID := flagProjectif projectID == "" {projectID = os.Getenv("TRACEWAY_PROJECT")@@ -95,6 +99,7 @@ func resolveMcpConfig(errOut io.Writer) (mcpserver.Config, error) {DefaultProjectID: projectID,InstanceURL: url,Version: version,+ AllowWrite: editionWrite,AuthHint: "the TRACEWAY_TOKEN this server was started with is expired or revoked; rotate it and restart the MCP server",}, nil}@@ -102,12 +107,13 @@ func resolveMcpConfig(errOut io.Writer) (mcpserver.Config, error) {sess, err := loadSessionOpts(false)if err != nil {- return mcpserver.Config{}, fmt.Errorf("not logged in (%w): run 'traceway login --url https://<instance>' in a terminal, then reconnect this MCP server", err)+ return mcpserver.Config{}, fmt.Errorf("not logged in (%w): run '%s login --url https://<instance>' in a terminal, then reconnect this MCP server", err, appdir.Binary)}return mcpserver.Config{Client: sess.Client(),DefaultProjectID: sess.ProjectID,InstanceURL: sess.URL,Version: version,+ AllowWrite: editionWrite,}, nil}diff --git a/cli/cmd/traceway/metrics.go b/cli/cmd/traceway/metrics.goindex b0e86ab2..d6413127 100644--- a/cli/cmd/traceway/metrics.go+++ b/cli/cmd/traceway/metrics.go@@ -7,6 +7,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/output""github.com/tracewayapp/traceway/cli/pkg/client")@@ -60,7 +61,7 @@ func runMetricsQuery(cmd *cobra.Command, _ []string) error {agg, _ := cmd.Flags().GetString("aggregation")if err := validateEnumFlag("--aggregation", agg, metricAggregations); err != nil {return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),- enumFlagHint("traceway metrics query", "--aggregation", metricAggregations))+ enumFlagHint(appdir.Binary+" metrics query", "--aggregation", metricAggregations))}groupBy, _ := cmd.Flags().GetString("group-by")intervalMin, _ := cmd.Flags().GetInt("interval-minutes")diff --git a/cli/cmd/traceway/operations.go b/cli/cmd/traceway/operations.gonew file mode 100644index 00000000..d5b96241--- /dev/null+++ b/cli/cmd/traceway/operations.go@@ -0,0 +1,245 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "strconv"+ "strings"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/appdir"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func runRaw(cmd *cobra.Command, call func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error), table func(w io.Writer, v any) error) error {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ raw, err := call(cmd.Context(), sess.Client(), sess.ProjectID)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }+ return renderRaw(cmd, mode, raw, table)+}++func renderRaw(cmd *cobra.Command, mode output.Mode, raw json.RawMessage, table func(w io.Writer, v any) error) error {+ var v any+ if len(raw) > 0 {+ if err := json.Unmarshal(raw, &v); err != nil {+ return err+ }+ }+ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), v, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), v, output.ParseFieldsFlag(flagFields))+ }+ if table != nil {+ return table(cmd.OutOrStdout(), v)+ }+ b, err := json.MarshalIndent(v, "", " ")+ if err != nil {+ return err+ }+ _, err = fmt.Fprintln(cmd.OutOrStdout(), string(b))+ return err+}++func intArg(cmd *cobra.Command, value, label string) (int, error) {+ id, err := strconv.Atoi(value)+ if err != nil || id < 1 {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ return 0, renderUsageError(cmd.ErrOrStderr(), mode, fmt.Sprintf("invalid %s %q: must be a positive integer", label, value), "")+ }+ return id, nil+}++func rows(v any, keys ...string) []map[string]any {+ var list []any+ switch t := v.(type) {+ case []any:+ list = t+ case map[string]any:+ for _, k := range append(keys, "data") {+ if l, ok := t[k].([]any); ok {+ list = l+ break+ }+ }+ }+ out := make([]map[string]any, 0, len(list))+ for _, item := range list {+ if m, ok := item.(map[string]any); ok {+ out = append(out, m)+ }+ }+ return out+}++func cell(m map[string]any, key string) string {+ v, ok := m[key]+ if !ok || v == nil {+ return "-"+ }+ switch t := v.(type) {+ case float64:+ return strconv.FormatFloat(t, 'f', -1, 64)+ case string:+ if t == "" {+ return "-"+ }+ return t+ default:+ return fmt.Sprint(t)+ }+}++func listTable(wrapperKey string, columns ...[2]string) func(w io.Writer, v any) error {+ return func(w io.Writer, v any) error {+ tw := output.NewTabWriter(w)+ headers := make([]string, len(columns))+ for i, c := range columns {+ headers[i] = c[1]+ }+ _, _ = fmt.Fprintln(tw, strings.Join(headers, "\t"))+ for _, r := range rows(v, wrapperKey) {+ values := make([]string, len(columns))+ for i, c := range columns {+ values[i] = cell(r, c[0])+ }+ _, _ = fmt.Fprintln(tw, strings.Join(values, "\t"))+ }+ return tw.Flush()+ }+}++func newPagesCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "pages", Short: "On-call pages: alerts that paged a person"}+ list := &cobra.Command{+ Use: "list",+ Short: "List on-call pages (default: open and acknowledged)",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ status, _ := cmd.Flags().GetString("status")+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ if err := validateEnumFlag("--status", status, client.PageStatuses); err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), enumFlagHint(appdir.Binary+" pages list", "--status", client.PageStatuses))+ }+ if err := validatePaginationFlags(cmd); err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), paginationHint(appdir.Binary+" pages list"))+ }+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.ListPages(ctx, projectID, client.ListPagesRequest{Status: status, Pagination: resolvePagination(cmd)})+ }, listTable("data", [2]string{"id", "ID"}, [2]string{"status", "STATUS"}, [2]string{"urgency", "URGENCY"}, [2]string{"subject", "SUBJECT"}, [2]string{"eventCount", "EVENTS"}, [2]string{"createdAt", "OPENED"}))+ },+ }+ list.Flags().String("status", "active", "active, open, acknowledged, or resolved")+ addPaginationFlags(list)+ show := &cobra.Command{+ Use: "show <id>",+ Short: "Show one page and its delivery log",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "page id")+ if err != nil {+ return err+ }+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.GetPage(ctx, projectID, id)+ }, nil)+ },+ }+ cmd.AddCommand(list, show)+ return cmd+}++func newAlertsCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "alerts", Short: "Alert rules that notify channels and page on-call"}+ cmd.AddCommand(&cobra.Command{+ Use: "list",+ Short: "List the project's alert rules",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.ListNotificationRules(ctx, projectID)+ }, listTable("rules", [2]string{"id", "ID"}, [2]string{"name", "NAME"}, [2]string{"ruleType", "TYPE"}, [2]string{"enabled", "ENABLED"}, [2]string{"snoozedUntil", "SNOOZED UNTIL"}))+ },+ })+ return cmd+}++func newMonitorsCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "monitors", Short: "Uptime monitors (synthetic checks)"}+ cmd.AddCommand(&cobra.Command{+ Use: "list",+ Short: "List the project's monitors and their current status",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.ListChecks(ctx, projectID)+ }, listTable("checks", [2]string{"id", "ID"}, [2]string{"name", "NAME"}, [2]string{"checkType", "TYPE"}, [2]string{"currentStatus", "STATUS"}, [2]string{"intervalSeconds", "INTERVAL (S)"}, [2]string{"enabled", "ENABLED"}))+ },+ })+ cmd.AddCommand(&cobra.Command{+ Use: "show <id>",+ Short: "Show one monitor with its recent incidents",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "monitor id")+ if err != nil {+ return err+ }+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.GetCheck(ctx, projectID, id)+ }, nil)+ },+ })+ return cmd+}++func newPostMortemsCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "post-mortems", Short: "Incident post-mortem documents"}+ list := &cobra.Command{+ Use: "list",+ Short: "List post-mortems, newest first",+ Args: cobra.NoArgs,+ RunE: func(cmd *cobra.Command, _ []string) error {+ search, _ := cmd.Flags().GetString("search")+ tags, _ := cmd.Flags().GetStringSlice("tag")+ if err := validatePaginationFlags(cmd); err != nil {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), paginationHint(appdir.Binary+" post-mortems list"))+ }+ page := resolvePagination(cmd)+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.ListPostMortems(ctx, projectID, client.ListPostMortemsRequest{Search: search, Tags: tags, Page: page.Page, PageSize: page.PageSize})+ }, listTable("data", [2]string{"id", "ID"}, [2]string{"title", "TITLE"}, [2]string{"tags", "TAGS"}, [2]string{"incidentId", "INCIDENT"}, [2]string{"updatedAt", "UPDATED"}))+ },+ }+ list.Flags().String("search", "", "Match title, content and tags")+ list.Flags().StringSlice("tag", nil, "Only post-mortems with this tag (repeatable, ANDed)")+ addPaginationFlags(list)+ show := &cobra.Command{+ Use: "show <id>",+ Short: "Show one post-mortem with its markdown content",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ id, err := intArg(cmd, args[0], "post-mortem id")+ if err != nil {+ return err+ }+ return runRaw(cmd, func(ctx context.Context, c *client.Client, projectID string) (json.RawMessage, error) {+ return c.GetPostMortem(ctx, projectID, id)+ }, nil)+ },+ }+ cmd.AddCommand(list, show)+ return cmd+}diff --git a/cli/cmd/traceway/operations_test.go b/cli/cmd/traceway/operations_test.gonew file mode 100644index 00000000..1d6d202e--- /dev/null+++ b/cli/cmd/traceway/operations_test.go@@ -0,0 +1,104 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestPagesList_sendsStatusAndPassesThroughJSON(t *testing.T) {+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/api/pages" || r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("request = %s %s", r.Method, r.URL)+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ _, _ = w.Write([]byte(`{"data":[{"id":7,"status":"open","subject":"DB down"}],"pagination":{"page":1,"pageSize":50,"total":1,"totalPages":1}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, stderr, err := runCmd(t, "", "pages", "list", "--output", "json")+ if err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())+ }+ if body["status"] != "active" {+ t.Errorf("default status should be active, body = %v", body)+ }+ if !strings.Contains(stdout.String(), `"subject":"DB down"`) {+ t.Errorf("stdout = %s", stdout.String())+ }+}++func TestPagesList_rejectsUnknownStatus(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {+ t.Fatal("an invalid status must not reach the server")+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "pages", "list", "--status", "closed", "--output", "json")+ if err == nil || !strings.Contains(stderr.String(), "usage_error") {+ t.Fatalf("want a usage error, got err=%v stderr=%s", err, stderr.String())+ }+}++func TestAlertsList_tableUsesRulesWrapper(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/notification-rules" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _, _ = w.Write([]byte(`{"rules":[{"id":3,"name":"Slow search","ruleType":"endpoint_p95_threshold","enabled":true,"snoozedUntil":null}]}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, stderr, err := runCmd(t, "", "alerts", "list", "--output", "table")+ if err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())+ }+ out := stdout.String()+ if !strings.Contains(out, "NAME") || !strings.Contains(out, "Slow search") || !strings.Contains(out, "endpoint_p95_threshold") {+ t.Errorf("table = %s", out)+ }+}++func TestPostMortemsList_forwardsSearchAndTags(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ q := r.URL.Query()+ if r.URL.Path != "/api/post-mortems" || q.Get("search") != "redis" || strings.Join(q["tag"], ",") != "cache,db" {+ t.Errorf("request = %s", r.URL)+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{"page":1,"pageSize":50,"total":0,"totalPages":0}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ if _, stderr, err := runCmd(t, "", "post-mortems", "list", "--search", "redis", "--tag", "cache", "--tag", "db", "--output", "json"); err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr.String())+ }+}++func TestMonitorsShow_rejectsNonNumericId(t *testing.T) {+ seedSessionFor(t, "http://127.0.0.1:1")+ _, stderr, err := runCmd(t, "", "monitors", "show", "abc", "--output", "json")+ if err == nil || !strings.Contains(stderr.String(), "positive integer") {+ t.Fatalf("want a usage error, got err=%v stderr=%s", err, stderr.String())+ }+}++func TestForbiddenCarriesServerMessage(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"error":"This endpoint is not available to personal access tokens, the CLI, or MCP clients."}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "alerts", "list", "--output", "json")+ if err == nil || !strings.Contains(stderr.String(), "not available to personal access tokens") {+ t.Fatalf("403 should surface the server's message, stderr = %s", stderr.String())+ }+}diff --git a/cli/cmd/traceway/profiles.go b/cli/cmd/traceway/profiles.goindex 15f43846..496b0457 100644--- a/cli/cmd/traceway/profiles.go+++ b/cli/cmd/traceway/profiles.go@@ -6,6 +6,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/config""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/internal/output"@@ -123,7 +124,7 @@ func runProfilesUse(cmd *cobra.Command, args []string) error {_ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{Code: "no_profile",Message: fmt.Sprintf("profile %q does not exist", name),- Hint: "traceway profiles list",+ Hint: appdir.Binary + " profiles list",ExitCode: exitcode.Auth,})return newCLIError(exitcode.Auth, "no_profile")diff --git a/cli/cmd/traceway/projects.go b/cli/cmd/traceway/projects.goindex 52f607f8..c6ae714c 100644--- a/cli/cmd/traceway/projects.go+++ b/cli/cmd/traceway/projects.go@@ -5,6 +5,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/config""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/internal/output"@@ -51,7 +52,7 @@ func runProjectsList(cmd *cobra.Command, _ []string) error {_ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{Code: "not_authenticated",Message: fmt.Sprintf("profile %q not found", profileName),- Hint: "traceway login",+ Hint: appdir.Binary + " login",ExitCode: exitcode.Auth,})return newCLIError(exitcode.Auth, "not_authenticated")@@ -60,7 +61,7 @@ func runProjectsList(cmd *cobra.Command, _ []string) error {_ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{Code: "not_authenticated",Message: fmt.Sprintf("profile %q has no JWT; please login first", profileName),- Hint: "traceway login",+ Hint: appdir.Binary + " login",ExitCode: exitcode.Auth,})return newCLIError(exitcode.Auth, "not_authenticated")diff --git a/cli/cmd/traceway/root.go b/cli/cmd/traceway/root.goindex 0e56c20d..6ce065f4 100644--- a/cli/cmd/traceway/root.go+++ b/cli/cmd/traceway/root.go@@ -2,6 +2,8 @@ package mainimport ("github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/appdir")// Global flag values, populated by Cobra at flag-parse time.@@ -15,8 +17,8 @@ var (func newRootCmd() *cobra.Command {cmd := &cobra.Command{- Use: "traceway",- Short: "CLI for the Traceway observability platform",+ Use: appdir.Binary,+ Short: editionShort,Version: version,SilenceUsage: true, // we render our own error envelopesSilenceErrors: true,@@ -42,8 +44,13 @@ func newRootCmd() *cobra.Command {cmd.AddCommand(newSessionsCmd())cmd.AddCommand(newTracesCmd())cmd.AddCommand(newMetricsCmd())+ cmd.AddCommand(newPagesCmd())+ cmd.AddCommand(newAlertsCmd())+ cmd.AddCommand(newMonitorsCmd())+ cmd.AddCommand(newPostMortemsCmd())cmd.AddCommand(newMcpCmd())cmd.AddCommand(newVersionCmd())+ addWriteCommands(cmd)return cmd}diff --git a/cli/cmd/traceway/session.go b/cli/cmd/traceway/session.goindex 303c096d..a579fe7c 100644--- a/cli/cmd/traceway/session.go+++ b/cli/cmd/traceway/session.go@@ -7,6 +7,7 @@ import ("io""os"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/config""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/internal/output"@@ -103,40 +104,49 @@ func (s *session) Client(opts ...client.Option) *client.Client {// The refresher is lock-free but concurrency-safe: because refresh tokens are// single-use and the server revokes a family on genuine replay, two CLI// processes racing to refresh the same token must not both call the server. So-// before (and after a lost race) it re-reads the on-disk token; if another-// process already rotated it, we adopt that token instead of minting a new one.-// A failed persist is non-fatal for the current command, and a retry within the+// before (and after a lost race) it re-reads the on-disk tokens; if another+// process already rotated them, we adopt that access token instead of minting a+// new one, and its refresh token too: ours was spent by that rotation, so a+// long-running process (traceway mcp) presenting it once the adopted access+// token expires would be a replay. A failed persist is non-fatal for the current command, and a retry within the// server's reuse-grace window is answered with the same rotated token set; a// later command re-presenting the stale token is treated as a replay, revoking// the family, so the warning below tells the user a re-login may be needed.func newRefreshingClient(url, profileName, jwt, refreshToken, kind string, opts ...client.Option) *client.Client {rt := refreshTokencurrent := jwt+ adoptDisk := func() bool {+ diskJWT, diskRT := loadProfileTokens(profileName)+ if diskJWT == "" || diskJWT == current {+ return false+ }+ current = diskJWT+ if diskRT != "" {+ rt = diskRT+ }+ return true+ }refresher := func(ctx context.Context) (string, error) {if kind != state.KindDevice || rt == "" {return "", errNoRefresh}- // Another process may have already refreshed; prefer its token.- if disk := loadProfileJWT(profileName); disk != "" && disk != current {- current = disk- return disk, nil+ // Another process may have already refreshed; prefer its tokens.+ if adoptDisk() {+ return current, nil}ts, err := client.New(url).Refresh(ctx, rt)if err != nil {// Lost a refresh race: the winner may have just persisted a token.- if errors.Is(err, client.ErrInvalidGrant) {- if disk := loadProfileJWT(profileName); disk != "" && disk != current {- current = disk- return disk, nil- }+ if errors.Is(err, client.ErrInvalidGrant) && adoptDisk() {+ return current, nil}return "", err}if perr := updateProfileTokens(profileName, ts); perr != nil {- fmt.Fprintf(os.Stderr, "warning: refreshed access token but could not save it: %v (later commands may require 'traceway login' again)\n", perr)+ fmt.Fprintf(os.Stderr, "warning: refreshed access token but could not save it: %v (later commands may require '%s login' again)\n", perr, appdir.Binary)}if ts.RefreshToken != "" {rt = ts.RefreshToken@@ -155,7 +165,7 @@ func renderSessionError(errOut io.Writer, mode output.Mode, err error) error {_ = output.RenderError(errOut, mode, output.ErrorEnvelope{Code: "not_authenticated",Message: err.Error(),- Hint: "traceway login",+ Hint: appdir.Binary + " login",ExitCode: exitcode.Auth,})return newCLIError(exitcode.Auth, "not_authenticated")@@ -163,7 +173,7 @@ func renderSessionError(errOut io.Writer, mode output.Mode, err error) error {_ = output.RenderError(errOut, mode, output.ErrorEnvelope{Code: "no_project",Message: err.Error(),- Hint: "traceway projects use <project-id> (or pass --project)",+ Hint: appdir.Binary + " projects use <project-id> (or pass --project)",ExitCode: exitcode.Usage,})return newCLIError(exitcode.Usage, "no_project")diff --git a/cli/cmd/traceway/session_refresh_test.go b/cli/cmd/traceway/session_refresh_test.goindex 701010b3..bd839c6c 100644--- a/cli/cmd/traceway/session_refresh_test.go+++ b/cli/cmd/traceway/session_refresh_test.go@@ -1,8 +1,12 @@package mainimport (+ "context"+ "encoding/json""net/http""net/http/httptest"+ "strings"+ "sync""testing""github.com/tracewayapp/traceway/cli/internal/config"@@ -58,3 +62,76 @@ func TestSession_refreshesExpiredDeviceToken(t *testing.T) {t.Errorf("refresh token not rotated in state: %q", sp.RefreshToken)}}++// A long-running process (traceway mcp) that adopts another process's rotated+// access token must adopt its refresh token too. Otherwise, once that access+// token expires, it presents its own already-spent refresh token, which the+// server treats as a replay and answers by revoking the whole login.+func TestSession_adoptedRotationCarriesTheRefreshToken(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ var mu sync.Mutex+ valid := map[string]bool{"jwt2": true}+ var presented []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ defer mu.Unlock()+ switch r.URL.Path {+ case "/api/auth/token":+ var body struct {+ RefreshToken string `json:"refresh_token"`+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ presented = append(presented, body.RefreshToken)+ if body.RefreshToken != "rt2" {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":"invalid_grant"}`))+ return+ }+ valid["jwt3"] = true+ _, _ = w.Write([]byte(`{"access_token":"jwt3","refresh_token":"rt3","expires_in":900}`))+ case "/api/projects":+ if !valid[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ _, _ = w.Write([]byte(`[]`))+ default:+ t.Errorf("unexpected path %q", r.URL.Path)+ }+ }))+ defer srv.Close()++ // This process started with jwt1/rt1; another process has since rotated+ // them to jwt2/rt2 and saved those.+ st := &state.State{CurrentProfile: "default", Profiles: map[string]state.ProfileState{+ "default": {JWT: "jwt2", RefreshToken: "rt2", CredentialKind: state.KindDevice},+ }}+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }+ c := newRefreshingClient(srv.URL, "default", "jwt1", "rt1", state.KindDevice)++ if _, err := c.ListProjects(context.Background()); err != nil {+ t.Fatalf("first call (adopts jwt2): %v", err)+ }+ mu.Lock()+ if len(presented) != 0 {+ t.Fatalf("adopting a saved rotation must not refresh, presented %v", presented)+ }+ delete(valid, "jwt2") // the adopted access token expires+ mu.Unlock()++ if _, err := c.ListProjects(context.Background()); err != nil {+ t.Fatalf("second call (refreshes): %v", err)+ }+ mu.Lock()+ defer mu.Unlock()+ if len(presented) != 1 || presented[0] != "rt2" {+ t.Fatalf("refresh must present the adopted rt2, presented %v", presented)+ }+ if got, _ := state.Load(); got.Profiles["default"].RefreshToken != "rt3" {+ t.Errorf("rotated refresh token not saved: %q", got.Profiles["default"].RefreshToken)+ }+}diff --git a/cli/cmd/traceway/setup_apply.go b/cli/cmd/traceway/setup_apply.goindex e04140d8..1f1296e9 100644--- a/cli/cmd/traceway/setup_apply.go+++ b/cli/cmd/traceway/setup_apply.go@@ -14,6 +14,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/envfile""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/internal/output"@@ -137,22 +138,22 @@ func runSetupApply(cmd *cobra.Command, _ []string) error {mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())if setupApplyPlanPath == "" {- return renderUsageError(cmd.ErrOrStderr(), mode, "no plan file provided", "traceway setup apply --plan <file> --token-stdin")+ return renderUsageError(cmd.ErrOrStderr(), mode, "no plan file provided", appdir.Binary+" setup apply --plan <file> --token-stdin")}plan, err := loadSetupPlan(setupApplyPlanPath)if err != nil {- return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), "traceway setup apply --help")+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), appdir.Binary+" setup apply --help")}if err := validateSetupPlan(plan); err != nil {- return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), "traceway setup apply --help")+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), appdir.Binary+" setup apply --help")}token, err := resolveSetupToken(cmd)if err != nil {- return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), "traceway setup apply --help")+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), appdir.Binary+" setup apply --help")}if token == "" {- return renderUsageError(cmd.ErrOrStderr(), mode, "no setup token provided", "traceway setup apply --plan <file> --token-stdin (or set TRACEWAY_SETUP_TOKEN)")+ return renderUsageError(cmd.ErrOrStderr(), mode, "no setup token provided", appdir.Binary+" setup apply --plan <file> --token-stdin (or set TRACEWAY_SETUP_TOKEN)")}url := strings.TrimSpace(setupApplyURL)diff --git a/cli/cmd/traceway/version.go b/cli/cmd/traceway/version.goindex b527aa6e..3c8b58a3 100644--- a/cli/cmd/traceway/version.go+++ b/cli/cmd/traceway/version.go@@ -5,6 +5,7 @@ import ("github.com/spf13/cobra"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/output")@@ -32,7 +33,7 @@ func runVersion(cmd *cobra.Command, _ []string) error {case output.ModeYAML:return output.RenderYAML(cmd.OutOrStdout(), info, output.ParseFieldsFlag(flagFields))default:- _, err := fmt.Fprintf(cmd.OutOrStdout(), "traceway version %s\n", version)+ _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s version %s\n", appdir.Binary, version)return err}}diff --git a/cli/cmd/traceway/version_test.go b/cli/cmd/traceway/version_test.goindex 951c3833..8ed9391e 100644--- a/cli/cmd/traceway/version_test.go+++ b/cli/cmd/traceway/version_test.go@@ -3,6 +3,8 @@ package mainimport ("strings""testing"++ "github.com/tracewayapp/traceway/cli/internal/appdir")func TestVersion_table(t *testing.T) {@@ -10,7 +12,7 @@ func TestVersion_table(t *testing.T) {if err != nil {t.Fatal(err)}- if !strings.Contains(stdout.String(), "traceway version "+version) {+ if !strings.Contains(stdout.String(), appdir.Binary+" version "+version) {t.Errorf("expected version line, got: %s", stdout.String())}}diff --git a/cli/install.sh b/cli/install.shindex 59fda741..5b655ac7 100644--- a/cli/install.sh+++ b/cli/install.sh@@ -2,6 +2,10 @@# Traceway CLI installer (Linux / macOS).## curl -fsSL https://cli.tracewayapp.com/install.sh | sh+# curl -fsSL https://cli.tracewayapp.com/install.sh | sh -s -- --write+#+# --write installs traceway-write, the separate build that can change data.+# It keeps its own login, so the read-only traceway is never upgraded in place.## Served from cli.tracewayapp.com (Cloudflare, uploaded manually); this file# is the source of truth — re-upload it after changing it. New CLI releases@@ -15,6 +19,14 @@set -eu+NAME="traceway"+for arg in "$@"; do+ case "$arg" in+ --write) NAME="traceway-write" ;;+ *) printf 'traceway-cli-install: error: unknown option %s\n' "$arg" >&2; exit 1 ;;+ esac+done+REPO="tracewayapp/traceway"API="https://api.github.com/repos/${REPO}/releases"@@ -48,12 +60,12 @@ if [ -z "$VERSION" ]; then| head -1 | sed 's|.*cli/v||; s|"$||')"[ -n "$VERSION" ] || err "could not determine the latest CLI release from ${API}"fi-log "installing traceway CLI v${VERSION}"+log "installing ${NAME} CLI v${VERSION}"RELEASE_JSON="$(curl -fsSL "${API}/tags/cli%2Fv${VERSION}")" \|| err "no CLI release found for v${VERSION} (see https://github.com/${REPO}/releases)"-TARBALL="traceway_${VERSION}_${OS}_${ARCH}.tar.gz"+TARBALL="${NAME}_${VERSION}_${OS}_${ARCH}.tar.gz"URL="$(printf '%s' "$RELEASE_JSON" \| grep -o "\"browser_download_url\":[[:space:]]*\"[^\"]*/${TARBALL}\"" \| head -1 | sed 's|.*"\(https://[^"]*\)"|\1|')"@@ -87,7 +99,7 @@ filog "unpacking"tar -xzf "${TMP}/${TARBALL}" -C "$TMP"-[ -f "${TMP}/traceway" ] || err "binary not found in $TARBALL (malformed release archive)"+[ -f "${TMP}/${NAME}" ] || err "binary not found in $TARBALL (malformed release archive)"if [ -n "${TRACEWAY_INSTALL_DIR:-}" ]; thenBIN_DIR="$TRACEWAY_INSTALL_DIR"@@ -99,16 +111,16 @@ elsemkdir -p "$BIN_DIR"fi-log "installing → ${BIN_DIR}/traceway"-install -m 0755 "${TMP}/traceway" "${BIN_DIR}/traceway"+log "installing → ${BIN_DIR}/${NAME}"+install -m 0755 "${TMP}/${NAME}" "${BIN_DIR}/${NAME}"-"${BIN_DIR}/traceway" version >/dev/null 2>&1 \- || err "installed binary failed to run (${BIN_DIR}/traceway version)"+"${BIN_DIR}/${NAME}" version >/dev/null 2>&1 \+ || err "installed binary failed to run (${BIN_DIR}/${NAME} version)"case ":${PATH}:" in*":${BIN_DIR}:"*) ;;*) log "note: ${BIN_DIR} is not on your PATH; add it to your shell profile" ;;esac-log "done — installed $("${BIN_DIR}/traceway" version --output table)"-log "next: traceway login --url https://cloud.tracewayapp.com (or your own instance)"+log "done: installed $("${BIN_DIR}/${NAME}" version --output table)"+log "next: ${NAME} login --url https://cloud.tracewayapp.com (or your own instance)"diff --git a/cli/internal/appdir/appdir.go b/cli/internal/appdir/appdir.gonew file mode 100644index 00000000..3f0e4bda--- /dev/null+++ b/cli/internal/appdir/appdir.go@@ -0,0 +1,9 @@+// Package appdir names the binary and the directory the CLI keeps its config+// and state under. The write build sets both to "traceway-write" so its+// credentials never mix with a read install's and its hints name itself.+package appdir++var (+ Name = "traceway"+ Binary = "traceway"+)diff --git a/cli/internal/config/paths.go b/cli/internal/config/paths.goindex bac9b635..de62f096 100644--- a/cli/internal/config/paths.go+++ b/cli/internal/config/paths.go@@ -4,17 +4,19 @@ import ("errors""os""path/filepath"++ "github.com/tracewayapp/traceway/cli/internal/appdir")// configPath returns the path to the config file, resolving XDG_CONFIG_HOME// or falling back to $HOME/.config. It does not create the file.func configPath() (string, error) {if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" {- return filepath.Join(dir, "traceway", "config.json"), nil+ return filepath.Join(dir, appdir.Name, "config.json"), nil}home := os.Getenv("HOME")if home == "" {return "", errors.New("neither XDG_CONFIG_HOME nor HOME is set")}- return filepath.Join(home, ".config", "traceway", "config.json"), nil+ return filepath.Join(home, ".config", appdir.Name, "config.json"), nil}diff --git a/cli/internal/errclass/errclass.go b/cli/internal/errclass/errclass.goindex b5bc3cd7..b3cfea51 100644--- a/cli/internal/errclass/errclass.go+++ b/cli/internal/errclass/errclass.go@@ -9,6 +9,7 @@ import ("errors""net/url"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/exitcode""github.com/tracewayapp/traceway/cli/pkg/client")@@ -29,12 +30,16 @@ func Classify(err error) Classified {case errors.Is(err, client.ErrUnauthorized):return Classified{Code: "token_expired", Message: "session expired or invalid",- Hint: "traceway login",+ Hint: appdir.Binary + " login",ExitCode: exitcode.Auth,}case errors.Is(err, client.ErrForbidden):+ message := "permission denied"+ if fe, ok := errors.AsType[*client.ForbiddenError](err); ok && fe.Message != "" {+ message = fe.Message+ }return Classified{- Code: "forbidden", Message: "permission denied",+ Code: "forbidden", Message: message,ExitCode: exitcode.Auth,}case errors.Is(err, client.ErrNotFound):diff --git a/cli/internal/state/paths.go b/cli/internal/state/paths.goindex 2495af14..a8cb1d15 100644--- a/cli/internal/state/paths.go+++ b/cli/internal/state/paths.go@@ -4,17 +4,19 @@ import ("errors""os""path/filepath"++ "github.com/tracewayapp/traceway/cli/internal/appdir")// statePath returns the path to the state file, resolving XDG_STATE_HOME// or falling back to $HOME/.local/state. It does not create the file.func statePath() (string, error) {if dir := os.Getenv("XDG_STATE_HOME"); dir != "" {- return filepath.Join(dir, "traceway", "state.json"), nil+ return filepath.Join(dir, appdir.Name, "state.json"), nil}home := os.Getenv("HOME")if home == "" {return "", errors.New("neither XDG_STATE_HOME nor HOME is set")}- return filepath.Join(home, ".local", "state", "traceway", "state.json"), nil+ return filepath.Join(home, ".local", "state", appdir.Name, "state.json"), nil}diff --git a/cli/internal/state/state.go b/cli/internal/state/state.goindex ab09c704..38d075fd 100644--- a/cli/internal/state/state.go+++ b/cli/internal/state/state.go@@ -19,7 +19,9 @@ type State struct {}// Credential kinds stored on ProfileState.CredentialKind. An empty value is-// treated as a legacy password login (non-refreshable).+// treated as a legacy password login (non-refreshable). KindDevice is any+// refreshable token set: a device login, or a password login on a server+// that issues agent scopes.const (KindPassword = "password"KindDevice = "device"diff --git a/cli/justfile b/cli/justfileindex e7be4690..3b2e656d 100644--- a/cli/justfile+++ b/cli/justfile@@ -2,9 +2,11 @@ default: testbuild:go build -o bin/traceway ./cmd/traceway+ go build -tags write -o bin/traceway-write ./cmd/tracewaytest:gotestsum --format pkgname -- ./...+ gotestsum --format pkgname -- -tags write ./cmd/... ./pkg/mcpserver/...smoke-test:gotestsum --format pkgname -- -tags smoke ./test/smoke/...@@ -16,6 +18,7 @@ contract-test *args:lint:golangci-lint run+ golangci-lint run --build-tags writevulncheck:govulncheck ./...@@ -34,8 +37,10 @@ gen-skills-check:tmp=$(mktemp -d)trap 'rm -rf "$tmp"' EXITgo run ./tools/skillgen "$tmp" >/dev/null- diff -u ../skills/traceway/SKILL.md "$tmp/SKILL.md"- diff -u ../skills/traceway/performance.md "$tmp/performance.md"+ diff -u ../skills/traceway/SKILL.md "$tmp/skills/traceway/SKILL.md"+ diff -u ../skills/traceway/performance.md "$tmp/skills/traceway/performance.md"+ diff -ru ../skills/traceway-learn "$tmp/skills/traceway-learn"+ diff -ru ../plugins/tw-write/skills/traceway-write "$tmp/plugins/tw-write/skills/traceway-write"# Run everything that should pass before a commitcheck: lint test vulncheck gen-skills-check contract-testdiff --git a/cli/pkg/client/auth.go b/cli/pkg/client/auth.goindex 3decce2b..f366590a 100644--- a/cli/pkg/client/auth.go+++ b/cli/pkg/client/auth.go@@ -10,24 +10,47 @@ import (type loginRequest struct {Email string `json:"email"`Password string `json:"password"`+ Scope string `json:"scope,omitempty"`}type loginResponse struct {- Token string `json:"token"`+ Token string `json:"token"`+ RefreshToken string `json:"refreshToken"`+ ExpiresIn int `json:"expiresIn"`+}++// LoginResult is a scoped password login. A server that supports agent+// scopes returns a short-lived access token with a refresh token, refreshed+// and revoked like a device-flow session; RefreshToken is empty otherwise.+type LoginResult struct {+ Token string+ RefreshToken string+ ExpiresIn int}// Login exchanges an email + password for a JWT. The returned token should be// stored by the caller and passed to subsequent Client constructions via// WithJWT.func (c *Client) Login(ctx context.Context, email, password string) (string, error) {- var resp loginResponse- if err := c.do(ctx, http.MethodPost, "/api/login", loginRequest{Email: email, Password: password}, &resp); err != nil {+ res, err := c.LoginScoped(ctx, email, password, "")+ if err != nil {return "", err}+ return res.Token, nil+}++// LoginScoped is Login for agent credentials: with a scope the server returns+// a scoped token held to the agent route allowlist instead of a full+// dashboard session.+func (c *Client) LoginScoped(ctx context.Context, email, password, scope string) (*LoginResult, error) {+ var resp loginResponse+ if err := c.do(ctx, http.MethodPost, "/api/login", loginRequest{Email: email, Password: password, Scope: scope}, &resp); err != nil {+ return nil, err+ }if resp.Token == "" {- return "", errors.New("login response did not include a token")+ return nil, errors.New("login response did not include a token")}- return resp.Token, nil+ return &LoginResult{Token: resp.Token, RefreshToken: resp.RefreshToken, ExpiresIn: resp.ExpiresIn}, nil}// DeviceAuth is the response from starting the device authorization flow.@@ -133,3 +156,8 @@ func mapOAuthError(err error) error {}return err}++const (+ ScopeRead = "traceway:read"+ ScopeWrite = "traceway:write"+)diff --git a/cli/pkg/client/client.go b/cli/pkg/client/client.goindex 5167dd9d..7becc9ef 100644--- a/cli/pkg/client/client.go+++ b/cli/pkg/client/client.go@@ -153,7 +153,11 @@ func (c *Client) do(ctx context.Context, method, path string, body, out any) errcase http.StatusUnauthorized:return ErrUnauthorizedcase http.StatusForbidden:- return ErrForbidden+ var body struct {+ Error string `json:"error"`+ }+ _ = json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&body)+ return &ForbiddenError{Message: body.Error}case http.StatusNotFound:return ErrNotFoundcase http.StatusTooManyRequests:diff --git a/cli/pkg/client/errors.go b/cli/pkg/client/errors.goindex 5497c08c..338b1815 100644--- a/cli/pkg/client/errors.go+++ b/cli/pkg/client/errors.go@@ -23,6 +23,23 @@ var (ErrInvalidGrant = errors.New("invalid_grant"))+// ForbiddenError is a 403 carrying the server's explanation, such as a+// read-only credential attempting a write. It matches ErrForbidden.+type ForbiddenError struct {+ Message string+}++func (e *ForbiddenError) Error() string {+ if e.Message == "" {+ return ErrForbidden.Error()+ }+ return e.Message+}++func (e *ForbiddenError) Unwrap() error {+ return ErrForbidden+}+// APIError is returned for any non-2xx response that isn't covered by a sentinel.// Inspect StatusCode and Body for diagnostics.type APIError struct {diff --git a/cli/pkg/client/operations.go b/cli/pkg/client/operations.gonew file mode 100644index 00000000..3a9e20ff--- /dev/null+++ b/cli/pkg/client/operations.go@@ -0,0 +1,263 @@+package client++import (+ "cmp"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"+ "strconv"+)++// The operations below cover on-call pages, alert rules, monitors and+// post-mortems. Their responses are passed through verbatim: they are rendered+// as JSON by the CLI and returned as structured content by the MCP server, so+// a typed copy of every dashboard shape would only add drift.++func projectQuery(projectID string) string {+ return "?projectId=" + url.QueryEscape(projectID)+}++var PageStatuses = []string{"active", "open", "acknowledged", "resolved"}++type ListPagesRequest struct {+ Status string `json:"status,omitempty"`+ Pagination PaginationParams `json:"pagination"`+}++func (c *Client) ListPages(ctx context.Context, projectID string, req ListPagesRequest) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodPost, "/api/pages"+projectQuery(projectID), req, &resp)+ return resp, err+}++func (c *Client) GetPage(ctx context.Context, projectID string, id int) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodGet, "/api/pages/"+strconv.Itoa(id)+projectQuery(projectID), nil, &resp)+ return resp, err+}++func (c *Client) AcknowledgePage(ctx context.Context, projectID string, id int) error {+ return c.do(ctx, http.MethodPost, "/api/pages/"+strconv.Itoa(id)+"/acknowledge"+projectQuery(projectID), struct{}{}, nil)+}++func (c *Client) ResolvePage(ctx context.Context, projectID string, id int, archiveIssue bool) error {+ body := struct {+ ArchiveIssue bool `json:"archiveIssue"`+ }{archiveIssue}+ return c.do(ctx, http.MethodPost, "/api/pages/"+strconv.Itoa(id)+"/resolve"+projectQuery(projectID), body, nil)+}++func (c *Client) ListNotificationRules(ctx context.Context, projectID string) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodGet, "/api/notification-rules"+projectQuery(projectID), nil, &resp)+ return resp, err+}++// SetNotificationRuleEnabled sets the rule's state through the toggle route's+// explicit enabled field, so repeating it, or racing another toggle, still+// leaves the rule in the requested state. A server older than that field+// ignores it and flips the rule, so a rule already in the requested state comes+// back in the other one. The returned state is checked and such a flip undone.+func (c *Client) SetNotificationRuleEnabled(ctx context.Context, projectID string, id int, enabled bool) (json.RawMessage, error) {+ path := "/api/notification-rules/" + strconv.Itoa(id) + "/toggle" + projectQuery(projectID)+ body := struct {+ Enabled bool `json:"enabled"`+ }{enabled}+ var resp json.RawMessage+ if err := c.do(ctx, http.MethodPost, path, body, &resp); err != nil {+ return nil, err+ }+ if ruleEnabled(resp, enabled) == enabled {+ return resp, nil+ }++ resp = nil+ if err := c.do(ctx, http.MethodPost, path, body, &resp); err != nil {+ return nil, fmt.Errorf("the server flipped alert rule %d instead of setting it, and undoing that failed, so it is now %s: %w", id, enabledWord(!enabled), err)+ }+ if ruleEnabled(resp, enabled) != enabled {+ return nil, fmt.Errorf("alert rule %d is still %s after a second toggle; it may have been changed at the same time, so check its state", id, enabledWord(!enabled))+ }+ return resp, nil+}++// ruleEnabled reads a toggle response's enabled field, or returns fallback+// when the response has none to check.+func ruleEnabled(resp json.RawMessage, fallback bool) bool {+ var rule struct {+ Enabled *bool `json:"enabled"`+ }+ if json.Unmarshal(resp, &rule) != nil || rule.Enabled == nil {+ return fallback+ }+ return *rule.Enabled+}++func enabledWord(enabled bool) string {+ if enabled {+ return "enabled"+ }+ return "disabled"+}++// SnoozeNotificationRule silences a rule for durationMinutes; 0 clears the+// snooze.+func (c *Client) SnoozeNotificationRule(ctx context.Context, projectID string, id, durationMinutes int) (json.RawMessage, error) {+ body := struct {+ DurationMinutes int `json:"durationMinutes"`+ }{durationMinutes}+ var resp json.RawMessage+ err := c.do(ctx, http.MethodPost, "/api/notification-rules/"+strconv.Itoa(id)+"/snooze"+projectQuery(projectID), body, &resp)+ return resp, err+}++func (c *Client) ListChecks(ctx context.Context, projectID string) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodGet, "/api/synthetics/checks"+projectQuery(projectID), nil, &resp)+ return resp, err+}++func (c *Client) GetCheck(ctx context.Context, projectID string, id int) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodGet, "/api/synthetics/checks/"+strconv.Itoa(id)+projectQuery(projectID), nil, &resp)+ return resp, err+}++func (c *Client) RunCheck(ctx context.Context, projectID string, id int) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodPost, "/api/synthetics/checks/"+strconv.Itoa(id)+"/run"+projectQuery(projectID), struct{}{}, &resp)+ return resp, err+}++type ListPostMortemsRequest struct {+ Search string+ Tags []string+ Page int+ PageSize int+}++func (c *Client) ListPostMortems(ctx context.Context, projectID string, req ListPostMortemsRequest) (json.RawMessage, error) {+ q := url.Values{"projectId": {projectID}}+ if req.Search != "" {+ q.Set("search", req.Search)+ }+ for _, tag := range req.Tags {+ q.Add("tag", tag)+ }+ if req.Page > 0 {+ q.Set("page", strconv.Itoa(req.Page))+ }+ if req.PageSize > 0 {+ q.Set("pageSize", strconv.Itoa(req.PageSize))+ }+ var resp json.RawMessage+ err := c.do(ctx, http.MethodGet, "/api/post-mortems?"+q.Encode(), nil, &resp)+ return resp, err+}++type PostMortem struct {+ Id int `json:"id"`+ Title string `json:"title"`+ ContentMd string `json:"contentMd"`+ Tags []string `json:"tags"`+ IncidentId *int `json:"incidentId"`+ UpdatedAt string `json:"updatedAt"`+}++type PostMortemInput struct {+ Title string `json:"title"`+ ContentMd string `json:"contentMd"`+ Tags []string `json:"tags"`+ IncidentId *int `json:"incidentId"`+ // ExpectedUpdatedAt makes an update fail with 409 when the document+ // changed after it was read, instead of overwriting that change.+ ExpectedUpdatedAt string `json:"expectedUpdatedAt,omitempty"`+}++func (c *Client) GetPostMortem(ctx context.Context, projectID string, id int) (json.RawMessage, error) {+ var resp json.RawMessage+ err := c.do(ctx, http.MethodGet, "/api/post-mortems/"+strconv.Itoa(id)+projectQuery(projectID), nil, &resp)+ return resp, err+}++func (c *Client) CreatePostMortem(ctx context.Context, projectID string, in PostMortemInput) (json.RawMessage, error) {+ if in.Tags == nil {+ in.Tags = []string{}+ }+ var resp json.RawMessage+ err := c.do(ctx, http.MethodPost, "/api/post-mortems"+projectQuery(projectID), in, &resp)+ return resp, err+}++// PostMortemPatch changes only the fields that are set; the server's update+// replaces the whole document, so the rest is read back first. The update is+// conditional on the document still being at ExpectedUpdatedAt, the revision+// the caller based its edit on, or at the one read here when that is empty+// (409 otherwise).+type PostMortemPatch struct {+ Title *string+ ContentMd *string+ Tags *[]string+ IncidentId *int+ UnlinkIncident bool+ ExpectedUpdatedAt string+}++func (c *Client) UpdatePostMortem(ctx context.Context, projectID string, id int, patch PostMortemPatch) (json.RawMessage, error) {+ raw, err := c.GetPostMortem(ctx, projectID, id)+ if err != nil {+ return nil, err+ }+ current, err := decodePostMortem(raw)+ if err != nil {+ return nil, err+ }+ in := PostMortemInput{Title: current.Title, ContentMd: current.ContentMd, Tags: current.Tags, IncidentId: current.IncidentId, ExpectedUpdatedAt: cmp.Or(patch.ExpectedUpdatedAt, current.UpdatedAt)}+ if patch.Title != nil {+ in.Title = *patch.Title+ }+ if patch.ContentMd != nil {+ in.ContentMd = *patch.ContentMd+ }+ if patch.Tags != nil {+ in.Tags = *patch.Tags+ }+ if patch.IncidentId != nil {+ in.IncidentId = patch.IncidentId+ }+ if patch.UnlinkIncident {+ in.IncidentId = nil+ }+ if in.Tags == nil {+ in.Tags = []string{}+ }+ var resp json.RawMessage+ err = c.do(ctx, http.MethodPut, "/api/post-mortems/"+strconv.Itoa(id)+projectQuery(projectID), in, &resp)+ return resp, err+}++func decodePostMortem(raw json.RawMessage) (*PostMortem, error) {+ var wrapped struct {+ PostMortem *PostMortem `json:"postMortem"`+ }+ if err := json.Unmarshal(raw, &wrapped); err == nil && wrapped.PostMortem != nil {+ return wrapped.PostMortem, nil+ }+ var pm PostMortem+ if err := json.Unmarshal(raw, &pm); err != nil {+ return nil, err+ }+ return &pm, nil+}++type SetSlowEndpointRequest struct {+ Endpoint string `json:"endpoint"`+ OffsetMs uint32 `json:"offsetMs"`+ Reason string `json:"reason"`+}++func (c *Client) SetSlowEndpoint(ctx context.Context, projectID string, req SetSlowEndpointRequest) error {+ return c.do(ctx, http.MethodPost, "/api/endpoints/slow"+projectQuery(projectID), req, nil)+}diff --git a/cli/pkg/mcpserver/common.go b/cli/pkg/mcpserver/common.goindex 956b59dd..8499bef0 100644--- a/cli/pkg/mcpserver/common.go+++ b/cli/pkg/mcpserver/common.go@@ -12,6 +12,7 @@ import ("github.com/google/uuid""github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/tracewayapp/traceway/cli/internal/appdir""github.com/tracewayapp/traceway/cli/internal/errclass""github.com/tracewayapp/traceway/cli/internal/timerange""github.com/tracewayapp/traceway/cli/pkg/client"@@ -36,7 +37,7 @@ func (s *server) apiErr(err error) error {if c.Code == "token_expired" {hint = s.cfg.AuthHintif hint == "" {- hint = "run 'traceway login' in a terminal on the host, then reconnect this MCP server"+ hint = "run '" + appdir.Binary + " login' in a terminal on the host, then reconnect this MCP server"}}if hint != "" {@@ -69,12 +70,12 @@ func (s *server) project(override string) (string, error) {if s.cfg.DefaultProjectID != "" {return s.cfg.DefaultProjectID, nil}- return "", errors.New("error=no_project: no project selected. Hint: pass project_id (find ids with list_projects) or set a default with 'traceway projects use <id>' on the host")+ return "", errors.New("error=no_project: no project selected. Hint: pass project_id (find ids with list_projects) or set a default with '" + appdir.Binary + " projects use <id>' on the host")}// projectIn is embedded in every project-scoped tool input.type projectIn struct {- ProjectID string `json:"project_id,omitempty" jsonschema:"Project to query. Optional when a default project is configured on the host (traceway projects use); find ids with list_projects."`+ ProjectID string `json:"project_id,omitempty" jsonschema:"Project to query. Optional when a default project is configured on the host (the CLI's projects use); find ids with list_projects."`}// timeRangeIn is embedded in every windowed list/query tool input.@@ -161,9 +162,16 @@ func readOnly() *mcp.ToolAnnotations {return &mcp.ToolAnnotations{ReadOnlyHint: true}}-// mutating marks the archive tools: they write, but reversibly (archive and-// unarchive undo each other), and repeating a call changes nothing.+// mutating marks tools that write reversibly (archive and unarchive undo each+// other, a rule can be turned back on) where repeating a call changes nothing.func mutating() *mcp.ToolAnnotations {nonDestructive := falsereturn &mcp.ToolAnnotations{DestructiveHint: &nonDestructive, IdempotentHint: true}}++// mutatingRepeatable is mutating for tools whose repeated call has a further+// effect, such as a snooze restarting from now.+func mutatingRepeatable() *mcp.ToolAnnotations {+ nonDestructive := false+ return &mcp.ToolAnnotations{DestructiveHint: &nonDestructive}+}diff --git a/cli/pkg/mcpserver/knowledge/embed.go b/cli/pkg/mcpserver/knowledge/embed.goindex 249ac655..adaad1b2 100644--- a/cli/pkg/mcpserver/knowledge/embed.go+++ b/cli/pkg/mcpserver/knowledge/embed.go@@ -7,7 +7,7 @@ package knowledgeimport "embed"-//go:embed *.md+//go:embed *.md learn/*.mdvar FS embed.FS// MustRead returns the named chunk or panics: chunk names are compile-timediff --git a/cli/pkg/mcpserver/knowledge/ground-rules.md b/cli/pkg/mcpserver/knowledge/ground-rules.mdindex 090923e8..39984e32 100644--- a/cli/pkg/mcpserver/knowledge/ground-rules.md+++ b/cli/pkg/mcpserver/knowledge/ground-rules.md@@ -1,7 +1,7 @@## Ground Rules (All Flows)- **Reads are safe**: any `list` / `show` / `query` subcommand may run freely; they never mutate server state.-- **Writes require explicit user instruction**: `exceptions archive` / `unarchive` are the only mutating data commands; only run them when the user asks by name, with `--yes` in non-interactive contexts. "Look at this error" means read it, not archive it.+- **This CLI is read only**: `traceway` has no mutating commands, and its login can only read. Changes (archiving issues, acknowledging pages, snoozing alerts, editing post-mortems) need the separate `traceway-write` CLI and the `traceway-write` skill. "Look at this error" means read it, never change it.- **Output**: piped output defaults to JSON (table on a TTY). Prefer JSON + `jq`, and `--fields a,b,c` to trim responses. Keep `--page-size` at 10 to 20 for triage.- **Time windows**: always bound queries, default `--since 1h` for "now" questions, `--since 24h` otherwise. `--since` accepts `s`, `m`, `h`, lowercase `Nd` (no `1w`, no `7d2h`). Absolute windows via `--from` / `--to` (RFC3339).- **Exit codes**: 0 ok, 1 generic/API, 2 usage, 3 connection, 4 auth, 5 not found, 6 rate limited, 7 server 5xx. Errors emit `{"error":"<stable_id>","message":"...","hint":"...","exit_code":N}` on stderr; branch on the `error` field.diff --git a/cli/pkg/mcpserver/knowledge/instructions.md b/cli/pkg/mcpserver/knowledge/instructions.mdindex 3f2a6a22..03cae729 100644--- a/cli/pkg/mcpserver/knowledge/instructions.md+++ b/cli/pkg/mcpserver/knowledge/instructions.md@@ -1,10 +1,10 @@# Traceway MCP server-Query and debug a Traceway observability instance: exceptions, logs, endpoints, background tasks, AI traces, sessions, distributed traces, and metrics.+Query and debug a Traceway observability instance: exceptions, logs, endpoints, background tasks, AI traces, sessions, distributed traces, metrics, monitors, alert rules, on-call pages and post-mortems.Ground rules:-- Reads are safe: every tool except archive_exceptions and unarchive_exceptions is read-only and never mutates server state. Only call the archive tools when the user asks for archiving by name; "look at this error" means read it, not archive it.+- Reads are safe: the read tools never mutate server state. A plain server has no write tools at all. Changes (archiving issues, acknowledging pages, snoozing alerts, editing post-mortems) need the write server, which a user connects separately with a write credential.- Always bound queries in time. Default to since "1h" for "now" questions and "24h" otherwise. since accepts s, m, h and lowercase Nd (no "1w", no "7d2h"); absolute windows use from/to as RFC3339.- The by-id detail tools (get_exception_occurrence, get_endpoint_request, get_task, get_ai_trace, get_session, get_trace) require the record's timestamp. It can be approximate (within a day); recover it from a dashboard URL's ?t= param, an occurrence list, or a notification before guessing. Never pass "now" for an old record.- Log severity is an OTel number, not a name: 1 TRACE, 5 DEBUG, 9 INFO, 13 WARN, 17 ERROR, 21 FATAL. Use min_severity 17 for errors and worse.@@ -12,4 +12,4 @@ Ground rules:- Keep page_size at 10 to 20 for triage; raise it only when you need the full set.- Empty results are not errors: widen the window, check the project (list_projects), and consider that the app may not be connected to Traceway yet.-For deep work, read the knowledge resources first: traceway://knowledge/debug-flow before debugging an issue to root cause, traceway://knowledge/performance before any latency investigation, traceway://knowledge/url-resolution when the user pastes a dashboard URL, and traceway://knowledge/notifications when resolving an alert notification.+For deep work, read the knowledge resources first: traceway://knowledge/debug-flow before debugging an issue to root cause, traceway://knowledge/performance before any latency investigation, traceway://knowledge/url-resolution when the user pastes a dashboard URL, and traceway://knowledge/notifications when resolving an alert notification. traceway://knowledge/learn is the product guide: how every part of Traceway works (issues, endpoints, traces, logs, metrics, monitors, status pages, alerts, on-call schedules and paging, settings), with one traceway://knowledge/learn/<topic> resource per area. Read it when the user asks how something works or where to find it.diff --git a/cli/pkg/mcpserver/knowledge/learn/alerts.md b/cli/pkg/mcpserver/knowledge/learn/alerts.mdnew file mode 100644index 00000000..adca95f4--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/alerts.md@@ -0,0 +1,116 @@+# Alerts++Alerts are how Traceway tells people that something happened. They live under **Alerts** in the project sidebar (`/notifications`), in three tabs kept in `?tab=`:++| Tab | What it holds |+|---|---|+| **Channels** (default) | Where notifications go. Create a channel first, then attach rules to it. |+| **Rules** | When to notify. Each rule watches one condition and sends to exactly one channel. A channel can serve many rules. |+| **History** | Every notification that was sent, with its status |++Rules and channels belong to a project and only see that project's data. Channels have their own On/Off switch, and a rule only runs while its channel is on. Changing them needs write access on the project. Browser and mobile projects only offer the New Issue rule type.++## Channels++| Type | Configuration | What it sends |+|---|---|---|+| **Email** | 1 to 10 recipient addresses | An HTML email per alert |+| **Slack** | Incoming webhook URL, optional channel override and username | An attachment coloured by severity: blue info, orange warning, red critical, green recovery |+| **Webhook** | URL, method (POST or PUT), optional headers, optional HMAC secret | JSON with `subject`, `body`, `severity`, `ruleType`, `ruleName`, `url`, `timestamp`. With a secret, `X-Traceway-Signature: sha256=<hex>` |+| **GitHub** | Fine-grained token with Issues read and write, owner, repo, optional labels | A GitHub issue. These issues can start the Auto-Fix agent in the repository. |+| **Pushover** | User key and app token, optional device, priority (normal, high, or emergency with a retry of 30 s or more, an expiry up to 10800 s and an optional callback URL), sound, HTML formatting, TTL | A push notification with the dashboard link |+| **Telegram** | Bot token and chat id | A message, cut at 4096 characters with the link kept |+| **Escalation policy** | An escalation policy of the same organization | Nothing by itself: it opens an on-call **page** that escalates until someone acknowledges (`on-call.md`) |++SMS is not a channel type. It is a personal on-call contact method.++Every channel has a **Test** button that sends "Traceway Test Notification". On an escalation channel, Test opens a **real page** and notifies whoever is on call. Resolve that page when done. Testing again while it is still open is refused.++Alert subjects look like `[<Project>] New error: TypeError` or `[<Project>] Check "api" is down`. Exception alerts carry the exception id, hash, occurred-at time, app version, server, the endpoint or task, the stack trace, the attributes and a link to `/issues/<hash>`. Those three fields (hash, exception id, occurred at) are what an agent needs to open the occurrence (see the `notifications` knowledge in the read skill).++## Rule settings shared by every type++| Setting | Meaning |+|---|---|+| Name | Up to 200 characters, shown in every notification |+| Channel | Exactly one |+| Cooldown | Minimum time between notifications for the same condition. Default 15 minutes. |+| Severity | **Auto** (derived from how bad the condition is) or a fixed Critical, Warning or Info. Recovery notices are always Info. |+| Enabled | New rules start enabled. A rule runs only while both it and its channel are enabled. |++## Rule types++The numbers in brackets are what the evaluator uses when a setting is missing. The **New Rule** form starts every type at the same values (5%, 5 minutes, 10 requests, 500 ms, `*`), so set each field on purpose.++| Rule | Fires when | Settings | Auto severity |+|---|---|---|---|+| **New Issue** | An exception hash is seen for the first time, or again for the first time after it was archived | Ignore patterns: comma-separated, case-insensitive substrings matched against the error type (the first stack line up to its first `:`). `*` is stripped, not a wildcard. | Critical |+| **Error Regression** | An archived (resolved) issue occurs again | None | Critical |+| **Error Rate** | The 5xx share across all endpoints exceeds a percentage | Threshold 5%, lookback 5 min, min requests 10 | Warning, Critical at 2x |+| **Error Count** | Errors in the window reach a count (captured messages are not counted) | Threshold 100, lookback 60 min | Warning, Critical at 5x |+| **Endpoint Error Rate** | One endpoint's 5xx share exceeds a percentage | A specific endpoint (`*` matches nothing here), threshold 2%, lookback 10 min, min requests 20 | Warning, Critical at 2x |+| **Endpoint P95** / **Endpoint P99** | The percentile exceeds a threshold | Endpoint or `*` for all, threshold 500 ms, lookback 5 min | Warning |+| **Apdex Drop** | Apdex falls below a threshold | Threshold 0.85, lookback 15 min, min requests | Warning, Critical below 0.5 |+| **Throughput Drop** | Requests drop versus the baseline window just before, scaled to the same length. No baseline traffic, no alert. | Drop 50%, lookback 15 min, baseline 60 min | Warning, Critical at 80% or more |+| **Impact Score Critical / High / Medium** | An endpoint newly enters the level (0.75, 0.50, 0.25) over the trailing 24 hours. Fires once on entry, again only after it leaves and comes back. The first run after a restart or edit only records the baseline. | Min requests 50 | Critical / Warning / Info |+| **Task Duration** | A task's P95 duration exceeds a threshold | Task or `*`, threshold 30000 ms, lookback 30 min | Warning |+| **Task Failure Rate** | The share of task runs with an exception on their own span exceeds a percentage | Task or `*`, threshold 10%, lookback 60 min, min executions 5 | Warning, Critical at 2x |+| **Metric Threshold** | An aggregated metric violates a comparison. No data in the window, no alert. | Metric, aggregation (avg, max, min, sum, p95, p99, last), operator (gt, gte, lt, lte, eq), value 90, lookback 5 min | Warning, Critical when 20% past the value |+| **No Data** | No telemetry of a kind for N minutes. `any` fires only when all four kinds are silent. | Data type (any, endpoints, exceptions, metrics, tasks), 10 min | Critical |+| **AI Trace Cost** | One AI call costs at least the threshold | Trace name or `*`, $0.50 | Warning, Critical at 3x |+| **AI Conversation Cost** | One conversation's cost over 24 hours reaches the threshold | $5 | Warning, Critical at 3x |+| **AI Flagged Content** | An AI call matches a flagged term. The terms come from the project's AI settings. | Optional term list (empty means any flagged match) | Warning |+| **Monitor Down** | Any monitor in the project goes down, plus a recovery notice when it comes back | None | Critical, recovery Info |++The aggregation in Metric Threshold spans every series of the metric with no tag filter, so prefer `max` (or `min` for lower-is-bad metrics) where one bad host could hide in an average.++Apdex uses fixed bands: satisfied up to 750 ms, tolerating up to 1500 ms, anything slower or a 5xx is frustrated. Apdex = (satisfied + tolerating / 2) / total.++## When rules run++- **On ingest**: New Issue, Error Regression, AI Trace Cost, AI Conversation Cost, AI Flagged Content. These fire within seconds.+- **On state change**: Monitor Down, the moment a probe flips the monitor.+- **Polled**: everything else, every 60 seconds by default (self-hosted: `NOTIFICATION_POLL_SECONDS`).++Cooldowns differ by kind:++- **Polled rules** have one cooldown per rule. After it fires, it is not evaluated again until the cooldown ends. This cooldown survives restarts.+- **Ingest and monitor rules** cool down per item: per exception hash, trace name, conversation or monitor. Two different new errors a minute apart both alert. The same error does not alert again within its cooldown. This memory is in process only, so a restart can let the same item alert once more.+- The cooldown cannot be 0. Empty or 0 becomes 15 minutes.+- **Editing** a rule resets its cooldown and its per-item memory, so the new settings apply at once. Toggling it does not.++Delivery goes through a durable queue. Failed sends are retried after 1, 5, 15 and 60 minutes, five attempts in all. A queued message keeps the channel settings it was sent with.++## Disable versus snooze++- **Disable** turns a rule off until someone turns it back on. The dashboard asks for confirmation.+- **Snooze** mutes a rule for a set time and it comes back on its own. The dashboard offers 30 minutes and 1, 4, 8 or 24 hours. Clearing the snooze turns it back on early.+- A snoozed or disabled rule is **not evaluated at all**, so nothing is queued while it is muted and it does not catch up afterwards.++During a known incident or a deploy, snooze the noisy rule rather than disabling it: a snooze cannot be forgotten in the off position.++The Rules table shows each rule's status as **On**, **Off** or **Snoozed**.++## History++The History tab lists every notification with severity, rule, subject (linking to the page it is about), channel, status and time. It has search and a time range. Statuses:++| Status | Meaning |+|---|---|+| Sent | Delivered. On an escalation channel, a page was opened. |+| Failed | All retries failed. The error is kept. |+| Deduped | An escalation alert folded into a page that was already open |++History opens on the last 7 days.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List rules with enabled and snoozed state | `traceway alerts list` | `list_notification_rules` |+| Turn a rule on or off (write) | `traceway-write alerts enable <id>` / `disable <id>` | `set_notification_rule_enabled` |+| Snooze a rule (write) | `traceway-write alerts snooze <id> --minutes N` (0 clears) | `snooze_notification_rule` |++Creating and editing rules and channels, the History tab and the Test buttons stay in the dashboard. Channels hold credentials and webhook URLs.++To resolve an alert someone pasted, the read skill's `notifications` section explains how to go from an exception or performance alert to the data behind it.diff --git a/cli/pkg/mcpserver/knowledge/learn/endpoints-and-tasks.md b/cli/pkg/mcpserver/knowledge/learn/endpoints-and-tasks.mdnew file mode 100644index 00000000..630a7bf0--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/endpoints-and-tasks.md@@ -0,0 +1,80 @@+# Endpoints and tasks++Both pages are hidden for browser and mobile projects. Both are built from spans promoted at ingest (`traces-and-logs.md`), so a request or a task run always opens its own span waterfall.++## Endpoints (`/endpoints`)++Every HTTP request a backend serves, grouped by method and route template (`GET /api/users/:id`).++**The list**++| Column | Meaning |+|---|---|+| Endpoint | Method and route. Badges: **Stream** (SSE or WebSocket: left out of latency and Apdex, scored on errors only), **Healthcheck** (the project drops healthy healthcheck requests, so only those with status 400 or more are kept), **Non Root** or **Mixed** (all or some requests have a parent span, usually an upstream service in the same trace) |+| Calls | Request count |+| Typical | P50 |+| Slow | P95 |+| Awful | P99 |+| Impact | The impact level (below). The default sort. |++- Filters: search, HTTP method, and Root (all, root, non-root).+- The **Performance** chart above the table shows total time as a stacked area of the top 5 endpoints plus Other (drag across it to zoom the range), or P50, P95 or P99 as a bar chart of the top 8 endpoints on the current table page.+- **Healthchecks**: the project settings (**Edit Project > Healthchecks**) can drop healthy healthcheck requests, with extra healthcheck paths.+- Requests that return 404 without matching a route are grouped as `UNMATCHED`, so scanners do not create one endpoint per probed path. A 404 from a real route keeps its route.++**Impact score**: one number from 0 to 1 per endpoint that ranks the endpoint hurting users the most first. It is the **worst** of five components:++1. Apdex degradation: 1 minus Apdex.+2. Error-rate floor, where bad means slow or 5xx: over 10% gives 0.25, over 20% gives 0.50, over 33% gives 0.75.+3. P99 floor: over 3 s gives 0.25, over 6 s gives 0.50, over 8 s gives 0.75.+4. Client error (4xx) floor, with more than 10 requests and ignoring `UNMATCHED`: over 25% gives 0.50, over 50% gives 0.75.+5. A volume-aware floor: a smaller error share with a large number of bad requests still ranks high.++| Level | Score |+|---|---|+| Critical | 0.75 and up |+| High | 0.50 and up |+| Medium | 0.25 and up |+| Good | below 0.25 |++Every endpoint has an **impact reason** naming the dominant factor: "P99 latency is 9.2s", "N errors with X% error rate", "X% of requests returning 4xx errors", "X% of requests are slow or failing", or "Endpoint is healthy". Stream endpoints get error-only versions such as "Streaming endpoint is healthy".++**Apdex** uses fixed bands: satisfied up to 750 ms and not a 5xx, tolerating up to 1500 ms, anything slower or a 5xx is frustrated. Apdex = (satisfied + tolerating / 2) / total. 1.0 is perfect. Below about 0.85, users notice.++**Expected performance (slow endpoint marks)**: some endpoints are allowed to be slow, such as a report export or a batch upload. On the endpoint page, **Expected Performance** sets an offset in milliseconds and a reason. The offset is added to the Apdex bands and the P99 floor, so the endpoint stops being penalized up to that latency. Raw percentiles are never adjusted. An offset of 0 removes the mark. The header then shows "+N ms offset". Setting it needs write access on the project.++**The endpoint page** (`/endpoints/<endpoint>`)++- Tiles: average, median, P95 and P99 response time, Apdex, average error rate, average throughput (requests per minute). Stream endpoints show connections, error rate and throughput instead.+- The request table: recorded at, duration, status, body size, client IP, server, version and attributes, sortable. Search attribute values and add attribute filters (equals, not equals, contains, not contains) to find the requests of one tenant or user.++**A request** (`/endpoints/<endpoint>/<id>`)++- Details: endpoint, status, duration, recorded at, server, version, client IP, body size, attributes.+- **Exception Occurred**, linking to the issue, and captured **Messages**.+- The **Spans** waterfall: database queries, outgoing HTTP calls and other work inside the request, nested by parent. Large traces start folded, with **Expand all** and **Collapse all**. Each span opens its attributes. **Open the whole trace** jumps to the trace page.+- **Logs** for the trace, and the **Distributed Trace** card.++## Tasks (`/tasks`)++Background work outside a request: queue consumers (`CONSUMER` spans from any queue driver), scheduled commands (root `console.command` spans), cron jobs and scripts.++- **The list**: task name, runs, typical (P50), slow (P95), sorted by runs. Search and the Root filter. There is no impact score. Rank by count times (P95 minus P50) for a rough idea of where time goes.+- **The task page**: average, median, P95 and P99 duration and throughput, then the runs: recorded at, duration, client IP, server, version, attributes.+- **A run**: details, the exception if one happened, messages, the span waterfall and logs.+- A run **failed** when an exception was recorded on its own span. That is what the Task Failure Rate alert counts.++A queue worker whose span is parented to the request that enqueued it shares that request's trace id, so the distributed trace card shows the endpoint and the task together.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| Endpoints with percentiles and impact | `traceway endpoints list --since 24h [--order-by impact\|count\|p95\|lastSeen] [--search S]` | `list_endpoints` |+| Latency over time (find when it changed) | `traceway endpoints chart [--metric-type total_time\|p50\|p95\|p99] [--interval-minutes N]` | `endpoints_chart` |+| One request with its spans and errors | `traceway endpoints show <id> --recorded-at <t>` | `get_endpoint_request` |+| An endpoint's expected-performance mark | `traceway endpoints slow <endpoint>` | `get_slow_endpoint_config` |+| One task run | `traceway tasks show <id> --recorded-at <t>` | `get_task` |+| Mark an endpoint slow (write) | `traceway-write endpoints mark-slow <endpoint> --offset-ms N --reason R` | `set_slow_endpoint` |++There is no task list command. Find a task's runs through its exceptions, its trace id or the dashboard. Latency percentiles only come from endpoints, never from `metrics query`. The `traceway` skill's performance flow covers a full latency investigation.diff --git a/cli/pkg/mcpserver/knowledge/learn/issues.md b/cli/pkg/mcpserver/knowledge/learn/issues.mdnew file mode 100644index 00000000..b45b78fa--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/issues.md@@ -0,0 +1,65 @@+# Issues and exceptions++An **issue** is a group of exceptions (or captured messages) that share one fingerprint. The issues list ranks root causes, not repetitions: a bug in a hot path that throws ten thousand times is one row with a count of ten thousand.++## What creates an issue++- An unhandled exception or panic during a traced request or task.+- An error recorded on a span as an OpenTelemetry `exception` event.+- An exception or a message captured explicitly through a Traceway SDK (browser, mobile).++There are two kinds:++- **Errors** have a stack trace.+- **Messages** are captured strings with no exception. They group by their exact text, so variable data belongs in attributes. `"payment failed for order 123"` makes a new issue per order.++## Fingerprinting++Every error gets a **fingerprint**: a 16-hex-character hash of its normalized stack trace. The hash is the issue's identity. It is in the URL (`/issues/<hash>`), and archiving, regressions and alerts all key on it.++Before hashing, values that change between occurrences of the same bug are removed: the error message (only the type is kept), ids, UUIDs, hex addresses, IPs, emails, long numbers, goroutine numbers, absolute paths (only `file:line` stays), URL origins, module versions, JVM line numbers, columns (except on line 1, where minified bundles need them), and resolved JavaScript function names.++So the same failure keeps one issue across servers, environments, versions and users. A new issue appears when the failure changes: a different error type or a different code path. Line numbers count for most languages, so moving code inside a file can split an issue after a deploy (JVM frames are the exception). Uploading source maps or debug symbols for the first time rewrites the frames, so later occurrences form a new issue.++## The issues page (`/issues`)++- **Columns**: Issue (error type and first line), Trend (hourly sparkline), Events (count), Last Seen. Sort by Events or Last Seen (the default). Sort by last seen to see what is happening now.+- **Search**: a case-insensitive substring of the stack trace, scoped to **All**, **Issues** (errors only) or **Messages**.+- **Time range**: defaults to 24 hours. An issue is listed when it occurred in the range.+- **Archived issues** are hidden. The page has no toggle to show them.+- **Bulk archive**: select rows (up to 100) and **Archive**. When the selected issues have open on-call pages, the dialog offers to resolve them too (checked by default).++## The issue page (`/issues/<hash>`)++- The stack trace with **Formatted** and **Raw** views. Formatted folds library and system frames (JavaScript, Flutter, iOS, Java, Go). A **Message** badge marks captured messages.+- First seen, last seen, total occurrences, and the **Archive** button.+- The on-call team that owns the project and who is on call now.+- **Last Event**: when, server, version, trace id, attributes, and the **related endpoint, task or AI trace** it happened in, with its status, duration and a link. Browser issues show the replay clip from just before the error, or a **View full session** button.+- A **Distributed Trace** card when other endpoints, tasks, AI traces or exceptions share the trace id.+- On browser issues, **Session Context**: the console logs and user actions around the error, synced to the replay.+- The first 10 events, then **View all N events** (`/issues/<hash>/events`, 50 per page). Each event opens its own occurrence page.++**Occurrence** pages (`/issues/<hash>/<exceptionId>`) show one occurrence with the same event card. When debugging, fix the **last** occurrence, not the group: it is the one with the current code and data.++## Lifecycle++1. **Active**: it occurred.+2. **Archived**: someone marked it fixed or accepted. It is hidden from the list.+3. **Back**: an archived issue that occurs again after its archive time shows in the list again by itself. It stays archived until someone unarchives it, so it hides again only if it is archived again. On that first re-occurrence the **New Issue** rule fires once. The **Error Regression** rule fires on it and on every later occurrence while the issue is still archived, limited by its cooldown.++Archive an issue once it is fixed, so that a regression alerts. Unarchiving has no button in the dashboard. Agents with write access can do it, and the issue also comes back by itself if it occurs again.++## Attributes++An occurrence carries the key-value attributes in scope when it happened. Under a trace it also carries the span's attributes. Request URL, query, body and headers can be attached when the SDK is configured to record them.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List issues | `traceway exceptions list --since 24h [--search S] [--include-archived]` | `list_exceptions` |+| One issue with occurrences | `traceway exceptions show <hash>` | `get_exception` |+| One occurrence | `traceway exceptions occurrence <id> --recorded-at <t>` | `get_exception_occurrence` |+| Archive or unarchive (write) | `traceway-write exceptions archive\|unarchive <hash>...` | `archive_exceptions` / `unarchive_exceptions` |++Search is always a case-insensitive substring of the stack trace. The list comes back newest activity first (`lastSeen`); `--order-by firstSeen` or `count` changes that. `--include-archived` is the only way to list archived issues. The `traceway` skill's debug flow walks an issue from hash to root cause.diff --git a/cli/pkg/mcpserver/knowledge/learn/metrics-and-dashboards.md b/cli/pkg/mcpserver/knowledge/learn/metrics-and-dashboards.mdnew file mode 100644index 00000000..e3caacb8--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/metrics-and-dashboards.md@@ -0,0 +1,66 @@+# Metrics and dashboards++## Metrics++A metric point is a name (`system.cpu.utilization`, `orders.created`), a numeric value, a timestamp and tags (`server_name`, `state`, `direction`, ...).++- **Where they come from**: OpenTelemetry meters in the application (counters, histograms, gauges), runtime instrumentation (Go, Node.js and others), and host metrics from the Traceway OTel Agent or an OpenTelemetry Collector with the hostmetrics receiver (`system.*` names: CPU, memory, disk, filesystem, network, processes).+- **Histograms** are stored as two series, `<name>.avg` and `<name>.count`.+- **Tags** come from the data point's attributes, plus an allowlist of resource attributes Traceway lifts: `host.name`, `host.id`, `os.type`, `cloud.region`, `container.name`, `k8s.cluster.name`, `k8s.pod.name`, `k8s.node.name`, `postgresql.database.name` and a few more. The `server_name` tag comes from `service.name`. The allowlist also covers `k8s.namespace.name`, `k8s.deployment.name`, `cloud.provider`, `cloud.availability_zone` and `process.*`.+- **Resolution**: on ClickHouse it follows the range so long ranges stay fast: raw points up to 6 hours, 1-minute rollups up to 72 hours, 1-hour rollups up to 30 days, daily beyond. SQLite and DuckDB always read raw points.+- **Stored types**: gauges, sums and histograms. Exponential histograms and summaries are dropped.++Aggregations:++| Aggregation | Use |+|---|---|+| `avg`, `min`, `max`, `sum`, `count`, `last` | Gauges and per-bucket values. `max` is the honest choice when one bad series could hide behind healthy ones in an `avg`. |+| `rate` | Cumulative counters such as `system.network.io` and `system.disk.io`. Each series is differenced against its previous sample, resets are dropped, and the result is per second (`By` becomes `By/s`). Charting a counter as `avg` only climbs forever. |++A widget source can also be **inverted** (1 minus the value). The agent reports `system.cpu.utilization` per state, and `idle` inverted is the busy share.++Dashboards and agent queries have no percentile aggregation over metric points. Only the Metric Threshold alert rule can compute `p95` or `p99` of a metric. Latency percentiles come from endpoints and tasks (`endpoints-and-tasks.md`).++## Dashboards (`/dashboards`)++A dashboard is a set of metric widgets that belongs to the **organization**, not to one project. It is applied to any number of projects and shows as a tab on each of them. An edit made in one project is live in all of them.++The active tab's menu: **Rename Dashboard** (names are unique in the organization), **Edit as JSON**, **Export JSON**, **Apply to Projects**, **Remove from this Project** (it stays elsewhere), **Delete Dashboard** (everywhere, permanently).++**Adding**: ⌘K (Ctrl K) or **Add or find dashboards...** opens one search over the dashboards of every organization the user belongs to (selecting one applies it here, or copies it in from another organization), the template marketplace (selecting one installs a copy) and every metric name seen in the organization (selecting one opens the widget editor prefilled). An empty project shows **Browse Dashboards & Templates**.++**Templates**:++| Template | Metrics it expects |+|---|---|+| OTelemetry Server Agent | Host CPU, memory, disk and network from the Traceway OTel Agent |+| Go Application | Go runtime and process metrics |+| Traceway ClickHouse | `traceway.ch.*` from a monitored Traceway instance |+| Traceway DuckDB | `traceway.duckdb.*` from a monitored Traceway instance |++**Widgets**: Line Chart, Area Chart, Stacked Area, Bar Chart, Single Value, Gauge and Table. Each has one or more sources: a metric name, an aggregation, optional tag filters (equals), an optional group-by that draws one series per tag value, and optionally inverted. Several sources overlay on one chart. Hover for values, drag across a chart to zoom in.++**Instance filter**: the picker in the header narrows every widget to one `server_name` seen in the range. It lives in the URL (`?server=<name>`), is not saved to the dashboard, and is where a row on the organization's Servers page leads.++**Starring**: the star on a widget pins it to the project's home page, where starred widgets can be resized and reordered. Stars are per project.++**As code**: every dashboard is one JSON document (`schemaVersion`, `name`, `widgets` in display order, each with `id`, `title`, `widgetType`, `config.sources`). Edit it in place, export it, or import a single dashboard or a whole organization bundle. The import API has an upsert mode that matches by name, so CI can keep dashboards in sync from files. Keep widget ids when editing so home page stars survive.++**Grafana import**: paste a Grafana export. Time series and graph panels become line charts, stat becomes single value, gauge stays a gauge, and Prometheus queries become metric sources. Anything that does not convert faithfully is listed as a warning, never silently dropped.++Editing dashboards and widgets needs an organization role above `readonly`. Starring, tab order and home page layout follow the effective project role. The Dashboards page is hidden for browser and mobile projects.++## Reading it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| A metric series | `traceway metrics query --name <metric> --aggregation avg --since 1h [--tag key=value] [--group-by tag] [--interval-minutes N]` | `query_metrics` |++- An unknown metric name returns an empty series, so probing names is safe.+- A grouped query keeps the first 200 groups and says `truncatedGroups: true` when it cut some.+- The server widens buckets so no series has more than 2000 points, and returns the bucket size it used as `intervalMinutes`.+- Agents get `avg`, `sum`, `count`, `min` and `max`. `rate`, `last` and inverted sources are dashboard only, so read a counter's increase by comparing buckets.+- `query_metrics` refuses `p50`, `p95` and `p99`. The CLI accepts them, but the server computes `avg` instead.+- There is no metric-name discovery tool. Try likely names (an unknown one returns an empty series), or look at a dashboard.++Creating, editing and applying dashboards stays in the dashboard.diff --git a/cli/pkg/mcpserver/knowledge/learn/monitors.md b/cli/pkg/mcpserver/knowledge/learn/monitors.mdnew file mode 100644index 00000000..f439f108--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/monitors.md@@ -0,0 +1,147 @@+# Monitors, incidents, status pages and post-mortems++Monitors answer the question telemetry cannot: is the service reachable from the outside? Traces and logs only exist while requests arrive. A monitor keeps probing on a schedule, so the team learns the site is down before a user tells them.++Everything here lives under **Monitors** in the project sidebar (hidden for browser and mobile projects), in three tabs kept in `?tab=`:++| Tab | Who sees it | What it holds |+|---|---|---|+| Monitors | Every member | The project's checks. "New Monitor" needs write access on the project. |+| Status Pages | Organization owners and admins | Public uptime pages for the organization |+| Post-Mortems | Every member | The project's internal incident write-ups |++The sidebar badge counts the project's monitors that are down right now. The organization's **Monitors** page lists every monitor across all projects with the incident history (see `organization.md`).++## Check types++| Type | What it does | Configuration |+|---|---|---|+| **HTTP** | Requests a URL, like Postman would | URL (http or https), method (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS), headers, auth (none, basic, bearer, or a custom header), a body for POST, PUT, PATCH and DELETE (Content-Type defaults to `application/json`), follow redirects (on by default), skip TLS verification (off by default) |+| **TCP** | Opens a connection to a host and port | Host, port, optional TLS, an optional payload to send, and an optional "expect response containing" string (up to 64 KB is read) |+| **Browser** | Runs a real `@playwright/test` spec in headless Chromium | The script (up to 100 KB, edited on the check) and optional environment variables. Only runs where the operator turned browser checks on. Never available on Traceway Cloud. |++HTTP expected results, all optional:++- **Status codes**: a list such as `200, 204`. Left empty, anything below 400 passes.+- **Body contains** a substring, or **body matches** a regex. Only the first 1 MB of the body is checked.+- **Max response time** in milliseconds.+- **Min TLS days remaining**: fails the run when the certificate expires sooner. This is how a team catches a certificate about to expire. TCP checks over TLS have the same option.++When several assertions fail, the run's error lists all of them separated by `; `.++Shared settings on every check:++| Setting | Range | Default |+|---|---|---|+| Interval | 30 seconds to 24 hours (the UI offers 30s, 1m, 2m, 5m, 10m, 15m, 30m, 1h, 6h, 24h) | 1 minute |+| Timeout | 1 to 120 seconds | 30 seconds |+| Failures before down | 1 to 10 consecutive failures | 2 |++The type cannot change after creation. Saving an edit schedules a run right away. On Traceway Cloud, checks can only target public addresses. Self-hosted instances allow private and LAN targets unless the operator sets `SYNTHETICS_ALLOW_PRIVATE_TARGETS=false`.++## States and runs++| Status | Meaning |+|---|---|+| **Pending** | No result yet (stored as `unknown`) |+| **Up** | The last run passed |+| **Down** | The last N runs failed, where N is the failure threshold |+| **Paused** | The check is disabled. Pausing drops queued runs. It does not resolve an open incident. |++- One success sets the check Up immediately and resets the failure counter.+- A failure only turns the check Down once consecutive failures reach the threshold. This is flap damping: one flaky probe does not page anyone at 3am.+- **Missed** runs: a queued run that is not picked up within its window (the interval, capped at 5 minutes) is recorded as `missed` instead of running late. Missed runs never change the state and are left out of uptime and latency. If Traceway itself was down, the charts show a gap, never a made-up 100%.+- HTTP and TCP probes run on the Traceway server. Browser runs run on the server or on a remote runner, shown as "via <name>" in the run history. There are no probe regions.+- A failed browser run stores a screenshot and the Playwright output. Both open from the run history.++## The monitor page++Covers the last 30 days. It has no time picker.++- **Tiles**: uptime, average latency, interval, and recent incidents (red while one is ongoing).+- **Availability strip**: green all up, red all down, amber mixed, grey no data. The tooltip shows up, total and missed counts.+- **Latency chart**: average latency per bucket.+- **Run history**: filter by All, Up, Down or Missed. Each row has the time, the executor, the result, the latency, the status code (not for browser checks) and the full error.+- **Incidents**: each with its time range, error, Resolved or Ongoing, and a **Write post-mortem** link (or **Post-mortem** once one exists).+- **Actions** (write access): Run now, Pause or Resume, Edit, Delete. Deleting removes the run history and incidents and resolves the on-call pages the monitor opened.++The monitor list shows name, type, status, 30-day uptime (green at 99.9% or more, amber at 99% or more, red below), average latency and last run. It can be searched and filtered by type.++**Run now** queues an immediate run. It is unavailable while the check is paused, and refused while a run is already queued ("A run for this check is already queued.") or for a browser check when the server has browser checks turned off. Such browser checks also skip their scheduled runs. Use it to confirm a fix without waiting for the next interval. The result appears in the run history within seconds.++## Alerting on monitors++A **Monitor Down** alert rule covers every monitor in the project. It fires when a monitor goes down and sends a recovery notice (always Info, green in Slack) when it comes back. Pending to Up sends nothing. Pointed at an escalation channel, it opens an on-call page per monitor, and recovery resolves that page on its own. See `alerts.md` and `on-call.md`.++## Incidents++An incident is a span of time when something was down, with an optional public story: a title and a timeline of updates.++**Automatic incidents** come from monitors:++- Going down opens one, holding the probe's error, with an automatic **Investigating** update. Recovery resolves it with a **Resolved** update.+- The default title is "<monitor name> is down". Anyone with admin rights can rename it to something users understand, such as "Checkout is failing for some card payments". Clearing the title brings the default back.+- The monitor owns the lifecycle. An automatic incident cannot be resolved by hand, re-timed or deleted.+- The probe's error message stays internal. It never reaches a public status page.++**Manual incidents** record outages the monitors missed, or maintenance windows:++- Created with **Record Incident** on a status page's incident history (admins only). A title is required, plus an optional first update, a start time (backdating is fine) and an optional resolved time.+- Resolve one by posting a **Resolved** update or setting the resolved time. Clearing the resolved time reopens it. Manual incidents can be deleted, and a linked post-mortem survives.+- They never change a monitor's uptime numbers.++**Timeline updates** carry a status, **Investigating**, **Identified**, **Monitoring**, **Update** or **Resolved**, and a message of up to 2000 characters. They are public content, so posting, renaming and deleting need an organization owner or admin. Every member can read the incident history.++Where incidents are managed:++- **Status Pages tab > Incidents** on a page: the full paginated history of that page's monitors plus its manual incidents. Expand a row to rename it, post updates, open or write the post-mortem, and resolve or delete manual incidents.+- **The monitor page**: that monitor's incidents.+- **Organization > Monitors**: every incident in the organization that was open at any point in the selected range.++## Status pages++A status page publishes the uptime of selected monitors at `/status/<slug>`, with no login. Only organization owners and admins create and edit them.++| Field | Rules |+|---|---|+| Title | Required, up to 200 characters |+| Slug | 3 to 60 lowercase letters, digits and hyphens, unique |+| Description | Optional, up to 500 characters |+| Logo | PNG or JPEG up to 1 MB, uploaded after saving. SVG is refused. |+| Custom domain | Self-hosted only (see below). Optional hostname such as `status.acme.com`, unique, never the Traceway host itself. On Traceway Cloud leave it empty and frame the page instead. |+| Publicly accessible | On by default. A private page answers 404, the same as an unknown slug. |+| Monitors | 1 to 50. The dashboard picker offers the current project's monitors. |++What visitors see:++- A banner: "All systems operational", or a red "Some systems are experiencing issues" when a monitor is down.+- Per monitor: Operational, Major outage, or No recent data (paused monitors), its 90-day uptime, and 90 daily bars in UTC: **Operational** (green, 99.5% or more), **Partial outage** (amber), **Major outage** (red, no successful run) and **No data** (grey). Narrow screens show 60 or 30 days.+- **Past Incidents**: the last 90 days of incidents (up to 30), grouped by day, each with its title and timeline updates.+- No latency numbers and no internal error messages. Always a light theme.++The data is cached for 30 seconds and the page refreshes itself every minute. Any edit to the page or its incidents clears the cache. Status pages can be framed by any site. To serve one on a company domain, a self-hosted instance points a CNAME at Traceway behind a TLS proxy that passes the Host header through and sets **Custom domain**. On Traceway Cloud, or when touching the proxy is not an option, host a small HTML file that frames `/status/<slug>` full window.++## Post-mortems++Internal write-ups of an incident: what happened, the impact, the timeline, the root cause and the follow-ups. They belong to one project, so opening one under a different project answers not found. They never appear on a status page.++- **Creating**: a dialog asks only for a title, creates the document and opens the editor. It can be started from the Post-Mortems tab, from an incident on the monitor page, or from an incident on a status page's history (which pre-links that incident).+- **Editor**: rich text with a **Rich text / Markdown** toggle. Type `/` for headings, lists, tables and code blocks. Content is Markdown, up to 200 KB.+- **Tags**: lowercased, up to 20 per document, 50 characters each.+- **Incident link**: optional, one post-mortem per incident. The picker offers the project's own monitor incidents plus the organization's manual status page incidents that have no post-mortem yet. Linked incidents show a link to the document everywhere they appear. Deleting the incident or monitor only severs the link.+- **Activity**: every create and edit with who, when and which parts changed (title, content, tags, incident). Saving without a change records nothing.+- **Finding them**: search matches title, content and tags, and clicking tags filters by all of them together. When a similar incident hits, last time's fix is one search away.+- **Permissions**: every member with project access reads them. Creating, editing and deleting need write access on the project.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List monitors with their current status | `traceway monitors list` | `list_checks` |+| One monitor with its incidents | `traceway monitors show <id>` | `get_check` |+| List post-mortems | `traceway post-mortems list [--search S] [--tag T]` | `list_post_mortems` |+| Read a post-mortem | `traceway post-mortems show <id>` | `get_post_mortem` |+| Run a monitor now (write) | `traceway-write monitors run <id>` | `run_check` |+| Create or edit a post-mortem (write) | `traceway-write post-mortems create\|update` | `create_post_mortem` / `update_post_mortem` |++Creating or editing monitors, status pages, incidents and public timeline updates stays in the dashboard. Status pages and updates are public, so a person should decide what the world reads.diff --git a/cli/pkg/mcpserver/knowledge/learn/on-call.md b/cli/pkg/mcpserver/knowledge/learn/on-call.mdnew file mode 100644index 00000000..aa2dcbf5--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/on-call.md@@ -0,0 +1,132 @@+# On-call: teams, schedules, escalation and pages++On-call turns an alert into a person's phone ringing. An alert alone posts to a channel and hopes someone is watching. A **page** keeps escalating until a human acknowledges it.++## How the pieces fit++An alert rule whose channel is an **escalation policy** fires. Instead of sending a message it opens a **page**. The page walks the policy step by step. Each step's targets resolve to people through a **schedule** (whoever is on call), a **team** (every member) or a direct **user**. Each person is reached through their own **contact methods**, in the order their personal **notification rules** say.++Two ideas to hold on to:++- **The page is the unit of work, not the message.** A rule that fires two hundred times opens one page. Re-fires bump its event counter and never restart the escalation clock.+- **Escalation stops on acknowledge, not on delivery.** Sending a message proves nothing. Traceway keeps climbing the policy until someone acknowledges or the policy runs out.++Setup order: create a team, build its schedule, create a policy whose first step targets the schedule, add an **Escalation policy** channel on the Alerts page and attach rules to it, then have every responder add contact methods. A responder with no contact methods is still paged on their account email.++## Where it lives++**On-Call** in the project sidebar (`/on-call`), with a badge counting the project's open pages. Five tabs:++| Tab | What it shows |+|---|---|+| **Pages** (default) | The page queue. Filters: All active (open or acknowledged), Open, Acknowledged, Resolved. Columns: severity, subject, level ("L2 of 3", "exhausted", "repeat N"), age, events, status, who acknowledged or resolved, actions. Rows can be selected for bulk acknowledge or resolve. |+| **Overview** | Per team and per schedule: who is on call now, until when, and who is next |+| **Teams** | Teams with members, owned projects and schedules |+| **Schedules** | Schedules with their rendered timeline and overrides |+| **Policies** | Escalation policies with their chain |++Teams, schedules and policies belong to the **organization**, so the page has an organization switcher. Pages belong to a project. The organization's **On-Call** page lists pages from every project (`organization.md`). The issue page shows the team that owns the project and who is on call for it now.++## Teams++A team is a named group of people that owns projects. Each project is owned by at most one team. Fields: name (unique in the organization), description, members, owned projects. Member order only affects how the team is listed: a policy step that targets a team pages every member at once. Deleting a team deletes its schedules, and is refused while a policy targets the team or one of its schedules.++## Schedules++A schedule answers one question: who is on call right now. It belongs to a team and has its own **timezone** (an IANA name, defaulting to the organization's). Set the timezone to where the people live. Handoffs and restrictions are in that timezone and hold their wall-clock time through daylight saving.++A schedule is built from **layers**. Each layer is an independent rotation:++| Field | Meaning |+|---|---|+| Rotation | `daily`, `weekly`, or custom (every N days, 1 to 365) |+| Handoff time | When the shift changes hands, HH:MM |+| Handoff day | The weekday of the handoff, for weekly rotations |+| Rotation start | The date the rotation counts from |+| Members | The people to rotate through, in order, one per period |+| Restrictions | Optional windows that limit when the layer covers anything |++Restrictions are **daily** (for example 18:00 to 09:00, wrapping past midnight) or **weekly** (for example Saturday 00:00 to Monday 09:00). With none, the layer covers every minute. If a handoff falls inside a window, the person changes mid-window.++**Stacking**: a later layer wins over earlier ones where they overlap. Exactly one person is on call at any moment: the highest layer covering it. If no layer covers a moment, nobody is on call and a step targeting the schedule reaches nobody.++**Overrides** temporarily replace whoever the layers picked, for an appointment, a swapped weekend or a vacation. They beat every layer, and the newest override wins where two overlap. An override lasts at most 30 days. The person covering must be an organization member but does not have to be in the schedule. **Any member** can create one, not only admins. It can be deleted by its creator, the person it covers, or an admin. Overrides end on their own, so there is no need to edit the rotation and remember to put it back.++The **timeline** shows a row per layer and a final **Schedule** row, which is who actually gets paged. Overrides appear in the Schedule row as dashed shifts marked Override. A red line marks now. Ranges are Day, Week, 2 Weeks and Month, up to 62 days.++Limits: 20 layers per schedule, 50 members per layer, 10 restrictions per layer. A schedule used by a policy cannot be deleted until the step is removed. A member removed from the organization is removed from every layer (a layer left empty is dropped) and their overrides are deleted. Team, schedule and policy names are unique in the organization.++Common shapes:++- **One rotation**: one weekly layer over everybody.+- **Business hours and out of hours**: two layers with opposite restrictions. The second, smaller group covers nights and weekends.+- **Primary and secondary**: two schedules, and a policy whose second step targets the secondary.++## Escalation policies++A policy is the ordered list of who to wake, and how long to wait for each.++- **Steps**: 1 to 10. Each holds 1 to 10 targets and a delay: "escalate after N minutes if not acknowledged" (1 to 1440, default 5).+- **Targets**: a **schedule** (whoever is on call when the step runs, overrides included), a **team** (every member), a **user**, or a **channel** (any notification channel of the organization except an escalation one, to post the page to Slack, a webhook or email alongside the people). Within one step each person is notified once.+- **Repeat**: 0 to 5. After the last step, its delay passes and the chain starts again from step 1, that many more times. After that the escalation is **exhausted**: nothing more is sent, but the page stays open.+- **Urgency**: **Auto** (critical becomes high, everything else low), **Always high** or **Always low**. It picks which of a responder's two notification chains runs. It is fixed when the page opens, so a low-severity re-fire never downgrades a page.++A page keeps a copy of its policy from the moment it opened, so editing a policy never changes pages already escalating. A policy used by a channel cannot be deleted.++## Pages++| Status | Meaning |+|---|---|+| **Open** | Nobody has taken it. Escalation is running. |+| **Acknowledged** | Someone is on it. Escalation stopped and every queued delivery is cancelled, including the later steps of personal notification chains. |+| **Resolved** | Finished. The dedup key is released, so the same condition can open a fresh page. |++- **Deduplication**: while a page is unresolved, the same rule and item (endpoint, metric, task, exception hash, monitor...) bump the existing page instead of opening a new one. Rules with no item dedup at rule level, so one noisy rule is one page. This is what stops a flapping error from becoming a pager storm.+- **Escalation**: step 1 is notified within a second or so. Later steps follow after their delays.+- **Acknowledge and resolve need no write access.** A read-only responder paged at 3am can still take the incident and close it.+- **Resolve and archive**: resolving a page opened by a New Issue or Error Regression rule can also archive its issue (that part needs write access). Archiving an issue in turn offers to resolve its open pages.+- **Auto-resolve**: a Monitor Down page resolves itself when the monitor recovers. A blip at night that recovers needs no human.+- **The page detail** shows the subject with severity, urgency and status, the rule, event count and last event, the alert body, the escalation chain with the current step marked (or "Escalation exhausted"), and the **delivery timeline**: every delivery with its step, target, method and status (pending, sent, failed, cancelled). That timeline is what to read when someone says they never got paged. Personal phone numbers and email overrides are masked there.++**Acknowledging without logging in**: every delivery to a person carries its own acknowledge link (`/ack/twk_...`). Opening it shows a summary of the page and an **Acknowledge** button, with no login. Opening the link is read only, so an email scanner cannot acknowledge by accident. The link can only acknowledge that one page, it is credited to the person it was sent to, and it stops working once the page is resolved. Deliveries to a channel target get the ordinary dashboard link instead, since a shared room has no single owner.++Page messages start with `[Page]`, or `[Page - escalation L2]` for later steps, and end with the acknowledge link.++## Contact methods and notification rules++Personal settings under **Account** (tabs **Contact Methods** and **Notification Rules**). Only the person can see or change their own.++| Contact method | Configuration |+|---|---|+| Email | Optional address. Blank uses the account email. |+| Slack | Incoming webhook URL, optional channel and username |+| Pushover | User key and app token |+| Telegram | Bot token and chat id |+| SMS | E.164 phone number such as `+12025550123`. Only offered when the server has Twilio configured. |++- SMS numbers must be verified before they are paged: a 6-digit code that expires in 10 minutes, with 5 attempts and at most 3 codes per hour.+- Every method has an enable toggle and a **Test** button ("If you received this, pages will reach you here.").+- **Notification rules** are two ordered chains, **High urgency** and **Low urgency**. Each step is "notify <method> after N minutes" (0 to 120, up to 10 steps). A typical high chain: Slack at 0, push at 2, SMS at 5. The whole chain is scheduled when the page reaches the person, and acknowledging cancels the steps that have not fired. If the first method cannot be used, the rest move earlier so the first usable one goes out at once.+- No chain means every enabled, verified method at once. No methods at all means the account email.++## Permissions++| Action | Who |+|---|---|+| View teams, schedules, policies, who is on call | Any organization member |+| Create or edit teams, schedules and policies | Organization owner or admin |+| Create an override | Any organization member |+| Delete an override | Its creator, the person it covers, or an admin |+| View, acknowledge and resolve pages | Anyone with read access to the project |+| Contact methods and notification rules | The person themselves |++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List pages | `traceway pages list [--status active\|open\|acknowledged\|resolved]` | `list_pages` |+| One page with its escalation and delivery log | `traceway pages show <id>` | `get_page` |+| Acknowledge (write) | `traceway-write pages ack <id>` | `acknowledge_page` |+| Resolve, optionally archiving the issue (write) | `traceway-write pages resolve <id> [--archive-issue]` | `resolve_page` |++Teams, schedules, overrides, policies and contact methods are dashboard only, both to read and to change. To answer "who is on call", send the user to **On-Call > Overview**, or to the issue page, which shows the on-call person for that project.diff --git a/cli/pkg/mcpserver/knowledge/learn/organization.md b/cli/pkg/mcpserver/knowledge/learn/organization.mdnew file mode 100644index 00000000..d4349bb7--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/organization.md@@ -0,0 +1,89 @@+# Organization, projects, access and settings++## Organizations and projects++- An **organization** is the tenant. It owns members and roles, projects, dashboards, teams, schedules, escalation policies and status pages. Nothing is shared across organizations. A user can belong to several, with one role in each.+- A **project** is one application boundary and belongs to exactly one organization. Telemetry is isolated per project, and almost every page is scoped to the current project. Switch projects from the switcher in the top-left header, where projects are grouped under their organization.+- **Frameworks**: a backend project is always **OpenTelemetry**, whatever the language. Browser projects are React, Svelte, Vue.js or jQuery, and mobile projects are Flutter, React Native, Android or iOS. Browser and mobile projects get a smaller sidebar: Issues, Sessions, Alerts, On-Call and Connection, with no endpoints, tasks, spans, logs, profiles, dashboards, AI traces or monitors. Their home page opens Issues.+- **Recommended split**: one backend project for all server-side signals (APIs, workers, schedulers, AI calls, logs, metrics, the host agent), with a distinct `service.name` per process. One project per independently deployed browser app and per independently released mobile app. Prefer more projects over more organizations: the organization views, dashboards, on-call and status pages are all organization-wide.++## Roles++| Role | Access |+|---|---|+| `owner` | Everything, including managing the organization |+| `admin` | Everything in every project, plus members, settings, teams, schedules, policies and status pages |+| `user` | Read and write in the organization's projects |+| `readonly` | Read only. Can still acknowledge and resolve on-call pages and create schedule overrides. |++Admins can override the role per project for `user` and `readonly` members (Settings > Team Members, expand a member). Owners and admins always have full access. The **effective role** on a project is the owner or admin role, else the override, else the organization role. A read-only effective role hides the project token.++A token or agent login never has more access than the person who created it.++## Home page (`/`)++The project's landing page, for backend projects. It answers "is anything wrong right now?":++- **Starred** widgets from dashboards, always over the last 24 hours. They can be reordered, resized and unstarred.+- **Endpoints**: the worst endpoints by impact over 24 hours (Good ones hidden), with Calls, Typical (P50), Slow (P95) and Impact.+- **Issues**: the 10 latest issues in 24 hours, messages excluded.+- A project with no data yet shows **Connect Your Application** with setup steps and **Check Again**. An account with no projects shows **Create Your First Project** with **Set Up Projects**, which opens the guided setup at `/setup`.++From an agent, the same question is the `whats_broken` recipe: recent exceptions, error logs and the worst endpoints by impact.++## Organization views (`/organization`)++For organizations with more than one project: open the organization itself in the switcher. Login lands here when the first organization has several projects. A single-project organization has no organization pages. Every member can open them, read-only included, and they only show projects the person can already see. If one project cannot be read, the rest still render with a notice.++| Page | What it shows |+|---|---|+| **Servers** | Every server reporting metrics in the last 30 minutes, one row per `server_name` per project: CPU, memory, disk, network, last signal, and host, OS, cloud and Kubernetes details. Health: **Critical** (CPU or memory 95% or more, disk 90% or more), **Warning** (CPU 80%, memory 85%, disk 80%), **Stale** (nothing for 3 minutes), **Healthy**. Filter by health and project, group by project or Kubernetes cluster. A row opens that server's dashboard. Needs host metrics from the OTel Agent or a collector. |+| **Issues** | Issues from every project in the range (24 hours by default), with the project, trend, events and last seen |+| **Monitors** | Every monitor with status, 30-day uptime and latency, and the incident history across monitors and status pages (3 months by default) |+| **On-Call** | Pages from every project (1 month by default), filtered by status and searchable, refreshed every minute |+| **Projects** | Every project with its framework and the person's effective access |++Servers and Monitors are hidden when every project is a browser or mobile app.++## Connection (`/connection`)++The setup guide for the current project: the project token, the OTLP endpoint and the snippet for the chosen language and framework. Two tabs:++- **AI**: install the skills with `npx skills add tracewayapp/traceway --all` and paste a ready-made prompt with the URL and token. The `traceway-setup` skill instruments the application.+- **Manual**: step-by-step setup.++Browser and mobile projects also get **Source Map Upload** (browser and Android) or **Symbol Upload** (Flutter and iOS) with an upload token for CI, hidden from read-only members. Regenerating it invalidates the old one.++## Account (`/account`)++Per-person settings:++- **Personal Access Tokens**: name, prefix, access, created, last used, expires. Access is **Read only** (`twp_`, the default, can be non-expiring) or **Read and write** (`tww_`, expires within 1 to 90 days, and only writes where an admin turned on Agent Access). A token is shown once.+- **Contact Methods** and **Notification Rules** for on-call (`on-call.md`).++## Settings (`/settings`, owners and admins)++Stacked sections, with an organization switcher for people who manage several:++- **Organization Details**: the name, and the timezone (**Update Timezone**), which sets the timestamps every member sees and the default for new schedules.+- **Team Members**: name, email, role, status, per-project role overrides. **Pending Invitations**. Invitations carry a role.+- **Agent Access**: the **Allow agent writes** switch and the **Agent activity** log (when, who, credential, project, action, result). See below.++Per-project settings open from the project switcher (**Edit Project**), not from Settings: **Project** (name, framework), **Healthchecks** (drop healthy healthcheck requests, extra healthcheck paths), **Profiles** (extra pprof labels), **AI** (flagged term packs and custom terms), and the **Danger Zone**.++## How agents get access++- The `traceway` CLI and the `/mcp` server are **read only** for product data. The one exception is `traceway setup apply`, which submits an approved project setup plan with a `tws_` setup token. Logins use a browser device flow, `--password`, or a personal access token.+- **Writes are opt in at three levels**, all of which must agree:+ 1. A write credential: a `tww_` token, a `traceway-write` login, or the `/mcp/write` server.+ 2. An organization owner or admin turns on **Settings > Agent Access**.+ 3. The person behind the credential has the role the change needs, as in the dashboard. A `readonly` member can still acknowledge and resolve pages, but not make the other writes.+- Agent credentials only reach the routes the CLI and MCP use. Account, member, token and settings routes refuse them, as do creating rules, channels, monitors, schedules and status pages, and every delete.+- Every agent write, accepted or refused by the switch, is in the agent activity log for 90 days.++The writes agents can make are archiving and unarchiving issues, acknowledging and resolving pages, enabling, disabling and snoozing alert rules, running a monitor, creating and editing post-mortems, and marking an endpoint slow. The `traceway-write` skill covers how to make them safely.++| Task | CLI | MCP tool |+|---|---|---|+| List projects | `traceway projects list` | `list_projects` |+| Pick the current project | `traceway projects use <id>` | the `project_id` param on any tool |diff --git a/cli/pkg/mcpserver/knowledge/learn/overview.md b/cli/pkg/mcpserver/knowledge/learn/overview.mdnew file mode 100644index 00000000..c9f891e6--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/overview.md@@ -0,0 +1,77 @@+# Learn Traceway++Traceway is an observability platform. Applications send telemetry: OpenTelemetry over OTLP/HTTP from backends, and the Traceway SDKs from browser and mobile apps. Traceway turns it into issues, request and task analytics, traces, logs, metrics and dashboards, session replay, AI cost tracking and profiles. On top of that it runs uptime monitors, public status pages, alerting and on-call paging.++This guide explains every part of the product: what each page shows, the terms it uses, how teams are meant to use it, and how an agent reads or changes it through the `traceway` CLI or the MCP server.++## How to use this guide++- Answer "how does X work", "where do I find X" and "what does X mean" from the topic files below. Read only the one or two the question needs.+- Quote the exact names the dashboard uses (tab names, buttons, rule types), so the user can find them.+- When the user wants live data, switch to the `traceway` skill (or the MCP tools): it holds the debugging and performance playbooks.+- When the user wants something changed, the `traceway-write` skill covers the changes agents are allowed to make. Everything else is done in the dashboard, and the topic files say so.+- When the user wants an application instrumented, use the `traceway-setup` skill.++## Core ideas++- **Organization** owns people, projects, dashboards, on-call and status pages. **Project** is one application, and almost every page is scoped to it. A trace can cross several projects of one organization.+- **Roles**: `owner`, `admin`, `user`, `readonly`, with per-project overrides for `user` and `readonly` members.+- **Time windows**: every telemetry page is bounded by a range kept in the URL (`?preset=24h`, or `?from=&to=`). Presets: 5m, 30m, 60m, 3h, 6h, 12h, 24h, 3d, 7d, 1M, 3M. CLI and MCP reads take `--since` or `--from/--to`.+- **Spans are the primitive.** Endpoints, tasks, AI traces and issues are spans promoted at ingest. One **trace id** links a request to its downstream calls, logs and exceptions.+- **Alert, page, incident** are different things. An **alert** is a rule sending a notification. A **page** is an on-call escalation that keeps going until someone acknowledges it. An **incident** is a period when a monitor was down (or one recorded by hand), with an optional public story on a status page.++## Topics++| Topic | File | MCP resource | Covers |+|---|---|---|---|+| Issues | [issues.md](issues.md) | `traceway://knowledge/learn/issues` | Exceptions, fingerprinting, the issue and occurrence pages, archiving, regressions |+| Endpoints and tasks | [endpoints-and-tasks.md](endpoints-and-tasks.md) | `traceway://knowledge/learn/endpoints-and-tasks` | P50, P95, P99, impact score, Apdex, expected-performance marks, requests, background tasks |+| Spans, traces and logs | [traces-and-logs.md](traces-and-logs.md) | `traceway://knowledge/learn/traces-and-logs` | The span explorer, whole-trace waterfalls, distributed traces, log search, live tail |+| Metrics and dashboards | [metrics-and-dashboards.md](metrics-and-dashboards.md) | `traceway://knowledge/learn/metrics-and-dashboards` | Metric names and tags, aggregations and rate, dashboards, widgets, templates, starring |+| Sessions, AI traces, profiles | [sessions-and-ai.md](sessions-and-ai.md) | `traceway://knowledge/learn/sessions-and-ai` | Session replay, LLM calls, conversations, flagged content, flame graphs |+| Monitors and status pages | [monitors.md](monitors.md) | `traceway://knowledge/learn/monitors` | HTTP, TCP and browser checks, runs, incidents, public status pages, post-mortems |+| Alerts | [alerts.md](alerts.md) | `traceway://knowledge/learn/alerts` | Every rule type and its settings, channels, cooldown, snooze, history |+| On-call | [on-call.md](on-call.md) | `traceway://knowledge/learn/on-call` | Teams, schedules, layers, overrides, escalation policies, pages, contact methods |+| Organization and access | [organization.md](organization.md) | `traceway://knowledge/learn/organization` | Projects, roles, the home page, organization views, Connection, Account, Settings, agent access |++## Page map++| Page | Path | Topic |+|---|---|---|+| Dashboard (home) | `/` | organization.md |+| Issues | `/issues`, `/issues/<hash>` | issues.md |+| Logs | `/logs` | traces-and-logs.md |+| Endpoints | `/endpoints`, `/endpoints/<endpoint>` | endpoints-and-tasks.md |+| Tasks | `/tasks` | endpoints-and-tasks.md |+| Spans | `/spans`, `/spans/<traceId>` | traces-and-logs.md |+| Profiles | `/profiles` | sessions-and-ai.md |+| Sessions | `/sessions` (browser and mobile projects) | sessions-and-ai.md |+| AI Traces | `/ai-traces` | sessions-and-ai.md |+| Dashboards | `/dashboards` | metrics-and-dashboards.md |+| Monitors | `/monitors` (tabs Monitors, Status Pages, Post-Mortems) | monitors.md |+| Public status page | `/status/<slug>` | monitors.md |+| Alerts | `/notifications` (tabs Channels, Rules, History) | alerts.md |+| On-Call | `/on-call` (tabs Pages, Overview, Teams, Schedules, Policies) | on-call.md |+| Connection | `/connection` | organization.md |+| Account | `/account` | organization.md, on-call.md |+| Settings | `/settings` (owners and admins) | organization.md |+| Organization | `/organization` (Servers, Issues, Monitors, On-Call, Projects) | organization.md |+| Project setup | `/setup` | organization.md |++Browser and mobile projects only show Issues, Sessions, Alerts, On-Call and Connection.++## Common questions++| Question | Answer in |+|---|---|+| Why did two errors land in the same issue, or one error split in two? | issues.md, Fingerprinting |+| What does the impact score mean and why is this endpoint Critical? | endpoints-and-tasks.md |+| What happens when I acknowledge a page? Who gets paged next? | on-call.md, Pages and Escalation policies |+| Who is on call right now, and how do I swap a shift? | on-call.md, Schedules and Overrides |+| Snooze or disable a noisy alert? | alerts.md, Disable versus snooze |+| Why is my monitor down after one failure, or not down after several? | monitors.md, States and runs |+| How do I publish uptime to customers? | monitors.md, Status pages |+| Where do I write up the incident? | monitors.md, Post-mortems |+| Why is a span missing from the waterfall? | traces-and-logs.md |+| Why does my counter metric only go up? | metrics-and-dashboards.md, Aggregations |+| Can an agent change things in Traceway? | organization.md, How agents get access |diff --git a/cli/pkg/mcpserver/knowledge/learn/sessions-and-ai.md b/cli/pkg/mcpserver/knowledge/learn/sessions-and-ai.mdnew file mode 100644index 00000000..3be3fdfa--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/sessions-and-ai.md@@ -0,0 +1,48 @@+# Sessions, AI traces and profiles++## Sessions (`/sessions`)++Only in the sidebar of browser and mobile projects. A session is the recording of one user's visit, usually the life of one open tab: what they clicked, typed, scrolled and saw, with the console logs and network calls alongside.++- The browser SDK records sessions when `recordAllSessions: true` is set. Without it, only a short clip from just before each exception is kept, shown on the issue page.+- A session ends after 15 minutes of inactivity, at 60 minutes in total, or when the page unloads. The server does not rely on the closing message arriving: it ends the session at the last activity it saw.+- **Attributes**: the SDK stamps `url`, `path`, `referrer`, `userAgent`, `language`, `platform`, `viewport`, `screen` and `timezone`. The server adds `client.ip`. The app adds its own with `setAttributes` (for example `userId`, `email`, `tenant`).+- **The list**: search a session id, IP or attribute value. Attribute filters use equals (case sensitive), not equals, contains or not contains (case insensitive), and all filters must match. Columns: session, attributes (click one to filter), started, duration, version. Filters are kept in the URL.+- **A session**: started, duration, app version, attributes, the replay player (rrweb for web, video for Flutter) with speed and fullscreen, **Logs** and **Actions** tabs synced to the replay, and **Exceptions in this session**, each linking to its issue.+- From an issue, **View full session** opens the session the exception happened in.++Replay itself is dashboard only. Read: `traceway sessions show <id> --started-at <t>`, MCP `get_session`, which return the session and its exceptions.++## AI traces (`/ai-traces`)++Hidden for browser and mobile projects. One record per LLM call, from any OpenTelemetry span with `gen_ai.*` attributes, whether it is a root span or a child of a request or job (a span that is already an endpoint or task stays one, so model calls belong on their own child spans).++Each call records: model, provider, duration, input, output, cached, reasoning and total tokens, input, output and total cost, finish reason, operation, user id, tool calls, server, version, attributes, its spans and the full conversation (prompt and completion, rendered as a chat).++Three tabs:++| Tab | What it shows |+|---|---|+| **Traces** | Calls grouped by trace name (the agent or workflow): calls, typical and slow duration, total tokens, total cost, last seen. Sorted by cost. A trace name opens tiles (average, median and P95 duration, total cost, total tokens) and its calls (model, tokens in and out, cost, provider), and each call opens its detail. |+| **Conversations** | Calls grouped into conversations: user, turns, tools, models, tokens, cost, last seen. Conversations above the 95th percentile of cost or turns are highlighted. Filter by flagged only, model or tool, and search conversation ids, users, models, tools and flagged terms. A **Flagged terms** button edits the project's terms in place. A conversation opens a chat timeline with tool calls inline, per-turn cost, and a Raw JSON view. |+| **Users** | Searchable. Per user: conversations, calls, median turns, average cost per conversation, total cost, flagged conversations, last seen |++A call's conversation id is `gen_ai.conversation.id`, else `session.id`, else the trace id, so one agent run inside a request still groups its calls.++**Flagged content**: at ingest, prompts and completions are matched (whole word, case insensitive) against the language packs and custom terms chosen in the project settings **AI** tab. Packs: English (default), German, Spanish, French, Italian, Portuguese, Serbian. Custom terms: up to 200, one per line. Changes apply to calls ingested afterwards. Flagged calls carry the matched terms, and the **AI Flagged Content** alert rule can notify on them.++Cost alerts: **AI Trace Cost** for one expensive call, **AI Conversation Cost** for a conversation that gets expensive over 24 hours (`alerts.md`).++Read: `traceway ai-traces show <id> --recorded-at <t>`, MCP `get_ai_trace` (one call with its conversation). Lists, conversations and users are dashboard only.++## Profiles (`/profiles`)++Hidden for browser and mobile projects. Continuous profiles per service. Use them after a waterfall says the time is in the application's own code and the question is which function.++- **The list**: service, profile type, profiles, samples, total, trend, last seen.+- **A service**: profile types CPU, In-Use, Alloc, In-Use Obj, Alloc Obj, Goroutines, Mutex, Block, Wall and Lock (depending on the language). Filter by labels, group by app version or server, and show CPU as cores or per second.+- A trend chart (drag to pick a range), a **flame graph** with search and a collapse-recursion option, a function detail (sandwich) view, and **top functions** with flat and cumulative time.+- **Compare** against a baseline version or server, as a differential flame graph (hotter or cooler) or side by side. This is how to see what a release made slower.+- **Download .pprof** for local tools.++Profiles are dashboard only. There is no CLI or MCP tool.diff --git a/cli/pkg/mcpserver/knowledge/learn/traces-and-logs.md b/cli/pkg/mcpserver/knowledge/learn/traces-and-logs.mdnew file mode 100644index 00000000..bafc3cee--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/learn/traces-and-logs.md@@ -0,0 +1,86 @@+# Spans, traces and logs++## Spans are the primitive++Traceway is OpenTelemetry native. A **trace** is one logical operation (a request, a queued job, an LLM call) as it moves through the system. It is a tree of **spans** that share one **trace id** (32 hex characters). Each span has a span id, a parent span id (empty for a root), a name, a kind (`SERVER`, `CLIENT`, `INTERNAL`, `PRODUCER`, `CONSUMER`), a start time, a duration, a status, attributes and events.++At ingest, some spans are also copied into the tables the list pages read. The copy keeps the span's ids:++| Span | Becomes |+|---|---|+| An HTTP `SERVER` span (or a root `INTERNAL` span with HTTP attributes) that is an entry point: no HTTP server span above it in the same export batch, so nested HTTP spans exported separately can each become an endpoint | An **endpoint** request (`endpoints-and-tasks.md`) |+| A `CONSUMER` span, or a root span with `console.command` | A **task** run |+| A span with `gen_ai.*` attributes, unless it already became an endpoint or task | An **AI trace** (`sessions-and-ai.md`) |+| An `exception` event (or `exception.*` attributes) on any span | An **issue** occurrence (`issues.md`) |+| Everything else | A span in the waterfall |++So an endpoint's waterfall is just the spans of its trace below its own span, and everything connected to it is whatever shares its trace id. An exception belongs to the nearest endpoint, task or AI trace above the span it happened on.++Two rules worth knowing when something seems missing:++- **Span reads are bound to 24 hours** either side of the entity being viewed. A span recorded further away is not shown on that page.+- **Orphans**: a span whose parent never arrived is shown under the trace's root entity, marked "Parent span is unavailable". It nests normally once the parent arrives.++## Spans page (`/spans`)++A search over every span of the project. Hidden in the sidebar for browser and mobile projects.++- **Filters**: span name (contains, case insensitive), service, kind, status (unset, ok, error), minimum and maximum duration, trace id, and up to 10 exact attribute matches (`key = value`).+- **Sort**: start time or duration, either direction.+- **Time range**: defaults to the last 60 minutes, and can be up to 31 days. A search that takes too long answers with a warning to narrow the range or add filters.+- The service filter lists the busiest 100 services in the range.++## The trace page (`/spans/<traceId>`)++The whole trace as one waterfall, across every service and **every project of the organization**, because the services of one trace usually report to different projects. Other organizations stay out.++- Each row names its service. Bars are coloured per service once a trace crosses services, and error spans are marked.+- Clicking a span opens its attributes, service, kind, status and scope. Attributes load when the popover opens.+- Large traces: over 500 spans, any node with more than 50 children starts folded, with a pill counting the hidden spans and an error marker when one of them failed. **Expand all** and **Collapse all** sit in the header. Over the row cap, the page keeps errors first, then entry points, then the slowest spans, and says the trace is partial.+- The trace's logs are listed alongside, from every project of the organization, with a service column.+- The URL needs `?at=` (any time near the trace) and can carry `?span=` to highlight one span.++## Distributed trace card++On endpoint request pages, task run pages and issue events, a **Distributed Trace** card lists every endpoint, task, AI trace and exception that shares the trace id, across the projects the user can open, nested by span parentage. It only appears when there is more than one such node. Each node has a project badge and a **View** button. A browser request and the backend request it called share the trace id through W3C `traceparent` propagation, so they appear together. For the whole span tree, use **Open the whole trace** on the waterfall.++Reading it from an agent: `traceway traces show <trace-id> --recorded-at <t>`, MCP `get_trace`. `--recorded-at` is the timestamp of the occurrence or node the trace id came from.++## Logs (`/logs`)++OpenTelemetry log records with a timestamp, severity, service (`service.name`), body, trace id and span id, and three attribute layers:++- **Resource** attributes describe the process (`service.version`, `host.name`, `deployment.environment`).+- **Scope** attributes describe the logger or instrumentation library.+- **Log** attributes belong to one record (`user.id`, `order.id`).++Severity is a number, grouped into levels: TRACE 1 to 4, DEBUG 5 to 8, INFO 9 to 12, WARN 13 to 16, ERROR 17 to 20, FATAL 21 and up. The severity dropdown is a threshold: `WARN+` keeps warnings and worse.++Filters, which all combine:++- **Search**, by **Message** (the body), **Service** or **Trace ID**. On ClickHouse a single-word body search is a fast whole-word match that is case sensitive (`timeout` does not find `Timeout` or `timeouts`). Anything longer, and every search on SQLite and DuckDB, is a case-insensitive substring match.+- **Severity**: All levels, or a threshold from TRACE+ to FATAL.+- **Attribute filters** (**Add filter**): any `resource.*`, `scope.*` or log attribute key, with equals, not equals, contains or not contains. Not equals is how teams mute a noisy logger. Each filter is a pill, red for exclusions. Expanding a log row lets you click its body, trace id, span id or scope to filter on them.+- **Time range**: presets or custom, 24 hours by default. Results are newest first by default (timestamp, level and service are sortable), and **Load 50 more** fetches more.++Filters are kept in the URL, so a filtered view can be shared.++**Live** turns the page into a live tail. It polls every 5 seconds, prepends new records and keeps up to 2000 rows. It works with preset ranges only, honours every filter, holds the scroll position while reading, and changing the sort stops it.++Structured message templates (Serilog, `Microsoft.Extensions.Logging` and others) are rendered inline: `{Provider}` in the body is replaced by the matching attribute and highlighted. A placeholder with no attribute stays as written.++**Logs and traces**: a log written inside an active span carries that span's trace and span ids. Every endpoint request, task run and AI trace page has a **Logs** panel with that trace's logs from the same project, and the trace page lists them from the whole organization.++Retention: 90 days on ClickHouse. Self-hosted SQLite and DuckDB keep 30 days by default, and an operator can also cap the row count.++## Reading it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| Search logs | `traceway logs query --since 1h [--min-severity 17] [--service S] [--search text] [--trace-id T]` | `query_logs` |+| Logs of one request | `traceway logs query --trace-id <trace-id> --since 24h` | `query_logs` with `trace_id` |+| A whole distributed trace | `traceway traces show <trace-id> --recorded-at <t>` | `get_trace` |++The span explorer and the waterfall attributes popover are dashboard only. For one request's spans, open the endpoint or task request (`get_endpoint_request`, `get_task`), which returns its span waterfall.++A trace id is usually the fastest route to a root cause: one id gives the request, its downstream calls, its logs and its exceptions.diff --git a/cli/pkg/mcpserver/knowledge/operations.md b/cli/pkg/mcpserver/knowledge/operations.mdnew file mode 100644index 00000000..150fe533--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/operations.md@@ -0,0 +1,66 @@+## Operating with write access++Write access lets an agent take the routine actions an on-call engineer takes during and after an incident. It is opt-in at three levels, and every level has to agree before a write goes through:++1. **The credential.** Only write credentials can write: a `tww_` personal access token, a `traceway-write login`, or an MCP client connected to the `/mcp/write` server. A `twp_` token, a `traceway login` and the `/mcp` server are read only, whatever the person's role.+2. **The organization.** An admin has to turn on Settings > Agent Access. Until then every agent write is refused with a 403 that says so.+3. **The person.** The write runs with the role of the person who created the credential, under the same rules as the dashboard. A `readonly` member's write token cannot archive issues, change alerts, run monitors or edit post-mortems. Acknowledging and resolving pages needs no write role, so any member's write token can do that.++Every write a write credential makes in the organization, accepted or refused because Agent Access is off, is recorded in the organization's agent activity log with the person, the credential, the project and the result.++### What an agent can change++| Action | CLI (`traceway-write`) | MCP tool | Reversible |+|---|---|---|---|+| Archive or unarchive issues | `exceptions archive <hash>...` / `unarchive` | `archive_exceptions` / `unarchive_exceptions` | Yes |+| Acknowledge a page | `pages ack <id>` | `acknowledge_page` | No, but harmless: it only stops escalation |+| Resolve a page | `pages resolve <id> [--archive-issue]` | `resolve_page` | No |+| Enable or disable an alert rule | `alerts enable <id>` / `alerts disable <id>` | `set_notification_rule_enabled` | Yes |+| Snooze an alert rule | `alerts snooze <id> --minutes N` (0 clears) | `snooze_notification_rule` | Yes, it expires on its own |+| Run a monitor now | `monitors run <id>` | `run_check` | Nothing to undo |+| Write a post-mortem | `post-mortems create` / `update <id>` | `create_post_mortem` / `update_post_mortem` | Edits are kept in the activity log |+| Mark an endpoint expected-slow | `endpoints mark-slow <endpoint> --offset-ms N --reason ...` (0 removes) | `set_slow_endpoint` | Yes |++Everything else (creating rules and channels, editing schedules and policies, status pages and public incident updates, members, tokens, project settings, deleting anything) stays in the dashboard. Those routes refuse agent credentials outright.++### Rules for every write++- **Only on request.** Investigating, debugging, summarizing or "taking a look" never implies a write. The user has to ask for the change.+- **Say it before doing it.** One line naming the action, the record and the new value: "Snoozing rule 12 (Endpoint P95 on GET /api/search) for 60 minutes." The CLI asks for confirmation on a TTY and needs `--yes` otherwise. MCP clients run their own approval step.+- **Prefer the reversible option.** Snooze rather than disable. Acknowledge rather than resolve while the problem is still live. Archive an issue rather than resolving its page with `--archive-issue` if you are unsure the page is done.+- **Report what changed and how to undo it.**+- **Treat a 403 as an answer.** "This credential is read-only" or "Agent write access is turned off" is a policy decision. Do not retry, switch credentials or look for another route. Tell the user what it said and who can change it.++### Playbooks++#### Someone got paged++1. `pages list` (status `active`) to find the page, then `pages show <id>` for the rule, subject and who was notified.+2. Investigate with the read tools. For an issue page, the page carries the exception hash: follow the debug flow.+3. When the user says they are on it: `pages ack <id>`. Escalation stops for everyone.+4. When the cause is fixed and confirmed: `pages resolve <id>`, with `--archive-issue` only if the user wants the issue archived too.++#### An alert is flapping during a known incident++1. `alerts list` to find the rule id and confirm it is the noisy one.+2. `alerts snooze <id> --minutes 60` (or as long as the user asks). The rule is muted and comes back on its own.+3. Tell the user when the snooze ends. Disable a rule only when the user wants it off until someone turns it back on.++#### Confirming a fix++1. `monitors run <id>` for the affected monitor.+2. Wait about one interval, then `monitors show <id>`: the latest run and whether the open incident resolved.+3. For an issue, `exceptions show <hash>` and check that no occurrence is newer than the deploy. Archive it only when the user agrees it is fixed.++#### Writing a post-mortem++1. Gather facts with the read tools: the incident window from `monitors show`, the issues and their first and last occurrences, the pages and who acknowledged them, the slow endpoints and the trace of a failing request.+2. Draft the document in markdown with these sections: Summary, Impact (who and how much, with numbers), Timeline (UTC, from first signal to resolution), Root cause, Resolution, Follow-up actions (each with an owner if known). Only state what the telemetry or the user confirmed, and mark open questions as open.+3. Show the draft to the user. Create it only after they approve: `post-mortems create --title "..." --content-file draft.md --tag <tag> --incident <id>`.+4. Later edits: `post-mortems show <id>` first, then `post-mortems update <id> --content-file revised.md --expected-updated-at <updatedAt from that show>` with the full revised body. If someone edited it in between, the update fails with a conflict: show it again and reapply the change. `--unlink-incident` removes a wrong incident link.++#### An endpoint is slow by design++1. Confirm with the user that the latency is accepted, and get the reason.+2. Check the current p95 with `endpoints list --search "<endpoint>"`.+3. `endpoints mark-slow "<endpoint>" --offset-ms <a bit above p95> --reason "<why>"`. Raw percentiles do not change. Apdex and impact stop penalizing up to the offset.diff --git a/cli/pkg/mcpserver/knowledge/timestamps.md b/cli/pkg/mcpserver/knowledge/timestamps.mdindex 4da38a55..61c65366 100644--- a/cli/pkg/mcpserver/knowledge/timestamps.md+++ b/cli/pkg/mcpserver/knowledge/timestamps.md@@ -1,19 +1,19 @@## Fast by-id lookups (always pass the timestamp)-The by-id detail commands — `exceptions occurrence`, `endpoints show`, `tasks show`, `ai-traces show`, `sessions show`, `traces show` — **require** the record's timestamp (`--recorded-at`, or `--started-at` for sessions). Telemetry tables are partitioned by day: with the timestamp the lookup is bounded to a small window and ClickHouse prunes to a few partitions; without it the server scans every partition (slow cold load). The flag is mandatory for exactly this reason — never omit it. It can be approximate (within ±24h), and you can recover or estimate it when it isn't handed to you; see "When you don't have the timestamp" below.+The by-id detail commands (`exceptions occurrence`, `endpoints show`, `tasks show`, `ai-traces show`, `sessions show`, `traces show`) **require** the record's timestamp (`--recorded-at`, or `--started-at` for sessions). Telemetry tables are partitioned by day: with the timestamp the lookup is bounded to a small window and ClickHouse prunes to a few partitions; without it the server scans every partition (slow cold load). The flag is mandatory for exactly this reason, so never omit it. It can be approximate (within ±24h), and you can recover or estimate it when it isn't handed to you; see "When you don't have the timestamp" below.Where the timestamp comes from, in order of preference:-1. **A dashboard URL** — the `?t=<iso>` param is the record's `recordedAt`; URL-decode it and pass it verbatim. (Sessions have no `t`; use the session start, `from=`, or a linked occurrence's `recordedAt`.)-2. **A list/group you already fetched** — every `exceptions show` occurrence carries `recordedAt`. Capture the id and its `recordedAt` together, then drill in.-3. **A notification** — see below.+1. **A dashboard URL**: the `?t=<iso>` param is the record's `recordedAt`; URL-decode it and pass it verbatim. (Sessions have no `t`; use the session start, `from=`, or a linked occurrence's `recordedAt`.)+2. **A list/group you already fetched**: every `exceptions show` occurrence carries `recordedAt`. Capture the id and its `recordedAt` together, then drill in.+3. **A notification**: see below.Query order when you hold an id: resolve its `recordedAt` first (URL, group, or notification), then call the by-id command with it.### When you don't have the timestamp-The flag is required, so you must supply *something* — but it can be approximate. The lookup window is **±24h** around what you pass (**±48h** for `traces show`), and if the record isn't in that window the server falls back to an unbounded scan. So a timestamp within a day of the truth stays fast; a wrong guess still returns the right record, just slower. Resolve it in this order:+The flag is required, so you must supply *something*, but it can be approximate. The lookup window is **±24h** around what you pass (**±48h** for `traces show`), and if the record isn't in that window the server falls back to an unbounded scan. So a timestamp within a day of the truth stays fast; a wrong guess still returns the right record, just slower. Resolve it in this order:-1. **Recover it from an API.** For an occurrence whose hash you know (e.g. `/issues/<hash>/<occurrenceId>` pasted without `?t=`), run `traceway exceptions show <hash>` and read that occurrence's `recordedAt` — the hash endpoint needs no timestamp. A group's `firstSeen`/`lastSeen` from `exceptions list` bound when its occurrences happened (`lastSeen` ≈ the most recent one).-2. **Estimate from context.** A notification's send time, the issue's `firstSeen`/`lastSeen`, or the URL's `preset`/`from` window all put you inside ±24h — good enough for a fast lookup.-3. **Ask the user.** If nothing pins it down (e.g. a bare occurrence/endpoint id with no hash, no time, and no list to recover from), ask roughly when it happened — "around when did this fire? within a day is enough" — and pass that. Don't invent a placeholder like "now" when the issue is old; that defeats the pruning and can miss the ±24h window entirely.+1. **Recover it from an API.** For an occurrence whose hash you know (e.g. `/issues/<hash>/<occurrenceId>` pasted without `?t=`), run `traceway exceptions show <hash>` and read that occurrence's `recordedAt`. The hash endpoint needs no timestamp. A group's `firstSeen`/`lastSeen` from `exceptions list` bound when its occurrences happened (`lastSeen` ≈ the most recent one).+2. **Estimate from context.** A notification's send time, the issue's `firstSeen`/`lastSeen`, or the URL's `preset`/`from` window all put you inside ±24h. That is good enough for a fast lookup.+3. **Ask the user.** If nothing pins it down (e.g. a bare occurrence/endpoint id with no hash, no time, and no list to recover from), ask roughly when it happened ("around when did this fire? within a day is enough") and pass that. Don't invent a placeholder like "now" when the issue is old; that defeats the pruning and can miss the ±24h window entirely.diff --git a/cli/pkg/mcpserver/knowledge/tool-map.md b/cli/pkg/mcpserver/knowledge/tool-map.mdindex 79f309aa..7506b6b9 100644--- a/cli/pkg/mcpserver/knowledge/tool-map.md+++ b/cli/pkg/mcpserver/knowledge/tool-map.md@@ -8,8 +8,6 @@ The knowledge resources show `traceway` CLI commands in their examples. Every co| `traceway exceptions list` | `list_exceptions` || `traceway exceptions show <hash>` | `get_exception` || `traceway exceptions occurrence <id> --recorded-at <t>` | `get_exception_occurrence` |-| `traceway exceptions archive <hash> --yes` | `archive_exceptions` |-| `traceway exceptions unarchive <hash> --yes` | `unarchive_exceptions` || `traceway logs query` | `query_logs` || `traceway endpoints list` | `list_endpoints` || `traceway endpoints show <id> --recorded-at <t>` | `get_endpoint_request` |@@ -20,6 +18,22 @@ The knowledge resources show `traceway` CLI commands in their examples. Every co| `traceway sessions show <id> --started-at <t>` | `get_session` || `traceway traces show <id> --recorded-at <t>` | `get_trace` || `traceway metrics query --name <n>` | `query_metrics` |+| `traceway pages list` / `pages show <id>` | `list_pages` / `get_page` |+| `traceway alerts list` | `list_notification_rules` |+| `traceway monitors list` / `monitors show <id>` | `list_checks` / `get_check` |+| `traceway post-mortems list` / `post-mortems show <id>` | `list_post_mortems` / `get_post_mortem` |++Write server only (`traceway-write mcp`, or `/mcp/write` on the instance):++| CLI command | MCP tool |+|---|---|+| `traceway-write exceptions archive <hash> --yes` / `unarchive` | `archive_exceptions` / `unarchive_exceptions` |+| `traceway-write pages ack <id>` / `pages resolve <id>` | `acknowledge_page` / `resolve_page` |+| `traceway-write alerts enable <id>` / `alerts disable <id>` | `set_notification_rule_enabled` |+| `traceway-write alerts snooze <id> --minutes N` | `snooze_notification_rule` |+| `traceway-write monitors run <id>` | `run_check` |+| `traceway-write post-mortems create` / `update <id>` | `create_post_mortem` / `update_post_mortem` |+| `traceway-write endpoints mark-slow <endpoint>` | `set_slow_endpoint` |Flag translation: `--since/--from/--to` are `since`/`from`/`to`; `--page/--page-size` are `page`/`page_size`; `--recorded-at` is `recorded_at`; `--started-at` is `started_at`; `--min-severity` is `min_severity`; `--search-type` is `search_type`; `--order-by` is `order_by`; `--interval-minutes` is `interval_minutes`; `--metric-type` is `metric_type`.@@ -27,6 +41,6 @@ Differences from the CLI:- Project selection: tools take an optional `project_id` param and fall back to the CLI's current project. There is no `projects use` tool; the default is whatever `traceway projects use` set on the host machine.- `query_metrics` rejects `p50/p95/p99` aggregations outright (the CLI accepts them but the server silently computes avg). Latency percentiles come from `list_endpoints`.-- No confirmation gate: `archive_exceptions`/`unarchive_exceptions` execute immediately, so only call them on an explicit user request. The MCP client's own tool-approval flow is the confirmation.+- No confirmation gate: write tools execute immediately, so only call them on an explicit user request. The MCP client's own tool-approval flow is the confirmation. `--content-file` on the post-mortem commands becomes the `content_md` string param.- Login, logout, and profile management are CLI-only (`traceway login` in a terminal); the MCP server uses the credentials stored by the CLI.- Shell-piping recipes (`jq` filters) in the knowledge files describe CLI usage; with MCP tools, read the same fields from the structured tool result instead.diff --git a/cli/pkg/mcpserver/knowledge/url-resolution.md b/cli/pkg/mcpserver/knowledge/url-resolution.mdindex f5d5d44b..8115fd9a 100644--- a/cli/pkg/mcpserver/knowledge/url-resolution.md+++ b/cli/pkg/mcpserver/knowledge/url-resolution.md@@ -6,7 +6,7 @@ Users paste dashboard URLs (`https://<instance>/<route>`) as references in any f|---|---|---|| `/issues/<hash>` and `/issues/<hash>/events` | Exception group (hash = 16 hex chars) | `traceway exceptions show <hash>` || `/issues/<hash>/<occurrenceId>` (UUID) | One occurrence within the group | `traceway exceptions occurrence <occurrenceId> --recorded-at <t>` where `t` is the URL's `?t=` param. Direct and fast; also returns the occurrence's `sessionId` and session recording. No URL? get `recordedAt` from `traceway exceptions show <hash>` occurrences |-| `/endpoints/<endpoint>` | Endpoint group; the segment is the URL-encoded endpoint name (`GET%20%2Fapi%2Fusers%2F%3Aid` is `GET /api/users/:id`) | Decode it, then `traceway endpoints list --search "<decoded name>"` (the group has no id; `endpoints show` is for one request — next row) |+| `/endpoints/<endpoint>` | Endpoint group; the segment is the URL-encoded endpoint name (`GET%20%2Fapi%2Fusers%2F%3Aid` is `GET /api/users/:id`) | Decode it, then `traceway endpoints list --search "<decoded name>"` (the group has no id; `endpoints show` is for one request, see the next row) || `/endpoints/<endpoint>/<endpointId>` | One request (transaction) of that endpoint | `traceway endpoints show <endpointId> --recorded-at <t>` (`t` = the URL's `?t=` param). Returns the request, its span waterfall, and any linked exception/messages || `/tasks/<task>` | Background task group | No CLI for the group; for one run use the next row || `/tasks/<task>/<taskId>` | Single task run | `traceway tasks show <taskId> --recorded-at <t>` (`t` = the URL's `?t=` param) |@@ -22,4 +22,4 @@ Users paste dashboard URLs (`https://<instance>/<route>`) as references in any f- `from`/`to` are ISO timestamps; pass via `--from`/`--to`, appending `Z` (or the correct offset) when missing, since the CLI requires RFC3339.- No time params means the page was on its default; pick `--since` per the ground rules.-`preset`/`from`/`to` set the *window* for list/group views. Detail URLs additionally carry **`?t=<iso>`** — the single record's timestamp, URL-encoded. That `t` value is exactly what the by-id commands need as `--recorded-at` (or `--started-at` for sessions). See "Fast by-id lookups" next.+`preset`/`from`/`to` set the *window* for list/group views. Detail URLs additionally carry **`?t=<iso>`**, the single record's timestamp, URL-encoded. That `t` value is exactly what the by-id commands need as `--recorded-at` (or `--started-at` for sessions). See "Fast by-id lookups" next.diff --git a/cli/pkg/mcpserver/knowledge/write-instructions.md b/cli/pkg/mcpserver/knowledge/write-instructions.mdnew file mode 100644index 00000000..18ef3685--- /dev/null+++ b/cli/pkg/mcpserver/knowledge/write-instructions.md@@ -0,0 +1,12 @@+## Write access++This server was started with write access, so it also has mutating tools: archive_exceptions, unarchive_exceptions, acknowledge_page, resolve_page, set_notification_rule_enabled, snooze_notification_rule, run_check, create_post_mortem, update_post_mortem and set_slow_endpoint. Every one of them changes what the whole team sees.++- Only call a mutating tool when the user asked for that change. Investigating, debugging or summarizing never implies a write.+- Before the call, state the exact change in one line: the tool, the record and the new value. Then make it.+- Prefer the reversible option: snooze a noisy rule rather than disabling it, acknowledge a page before resolving it, archive rather than resolve with archive_issue.+- After the call, report what changed and how to undo it.+- A 403 that says the credential is read-only, or that agent write access is off for the organization, is a policy decision. Do not retry or look for another route. Tell the user what it said; an organization admin turns agent writes on in Settings > Agent Access.+- Every agent write is recorded in the organization's agent activity log with the credential that made it (the token, or the OAuth client).++Read traceway://knowledge/operations before your first write: it covers the rules, what each write does, and playbooks for pages, alerts, monitors and post-mortems. For how each area of the product works, read traceway://knowledge/learn.diff --git a/cli/pkg/mcpserver/resources.go b/cli/pkg/mcpserver/resources.goindex 1c73cdc4..b797d10a 100644--- a/cli/pkg/mcpserver/resources.go+++ b/cli/pkg/mcpserver/resources.go@@ -2,6 +2,7 @@ package mcpserverimport ("context"+ "slices""github.com/modelcontextprotocol/go-sdk/mcp"@@ -45,14 +46,67 @@ var knowledgeResources = []struct {uri: "traceway://knowledge/query-recipes", file: "query-recipes.md", name: "Query recipes",description: "Ready-made triage queries: what is broken right now, what broke since a deploy, worst endpoint by latency, errors for one service.",},+ {+ uri: "traceway://knowledge/learn", file: "learn/overview.md", name: "Learn Traceway: overview",+ description: "How Traceway is organized (organizations, projects, roles, time windows), a map of every dashboard page, and which learn/* resource covers each part. Read when the user asks how Traceway works, where something is, or what a term means.",+ },+ {+ uri: "traceway://knowledge/learn/issues", file: "learn/issues.md", name: "Learn: issues and exceptions",+ description: "How exceptions are grouped into issues, what the issue and occurrence pages show, search, archiving and regressions.",+ },+ {+ uri: "traceway://knowledge/learn/endpoints-and-tasks", file: "learn/endpoints-and-tasks.md", name: "Learn: endpoints and tasks",+ description: "Endpoint and task analytics: percentiles, impact score, Apdex, slow-endpoint marks, request and task detail pages.",+ },+ {+ uri: "traceway://knowledge/learn/traces-and-logs", file: "learn/traces-and-logs.md", name: "Learn: spans, traces and logs",+ description: "The span explorer, whole-trace waterfalls across projects, the distributed trace card, and log search with severities and trace correlation.",+ },+ {+ uri: "traceway://knowledge/learn/metrics-and-dashboards", file: "learn/metrics-and-dashboards.md", name: "Learn: metrics and dashboards",+ description: "Metric types and aggregations (including rate), dashboards, widgets, templates, import and export, starring onto the home page.",+ },+ {+ uri: "traceway://knowledge/learn/sessions-and-ai", file: "learn/sessions-and-ai.md", name: "Learn: sessions, AI traces and profiles",+ description: "Browser and mobile sessions with replay, AI traces, conversations and users with flagged content, and continuous profiles.",+ },+ {+ uri: "traceway://knowledge/learn/monitors", file: "learn/monitors.md", name: "Learn: monitors, status pages and post-mortems",+ description: "Uptime monitors (http, tcp, browser), runs, incidents, public status pages with timeline updates, and post-mortem documents.",+ },+ {+ uri: "traceway://knowledge/learn/alerts", file: "learn/alerts.md", name: "Learn: alerts",+ description: "Every alert rule type and its settings, cooldowns, snoozing, channels and notification history.",+ },+ {+ uri: "traceway://knowledge/learn/on-call", file: "learn/on-call.md", name: "Learn: on-call",+ description: "Teams, schedules (layers, rotations, restrictions, overrides), escalation policies, pages and their lifecycle, contact methods and personal notification rules.",+ },+ {+ uri: "traceway://knowledge/learn/organization", file: "learn/organization.md", name: "Learn: organization, access and settings",+ description: "Organization views, projects and connection, roles and per-project overrides, account, personal access tokens, settings and agent access.",+ },{uri: "traceway://knowledge/tool-map", file: "tool-map.md", name: "CLI to MCP tool map",description: "The 1:1 mapping between traceway CLI commands (used in the other resources' examples) and this server's MCP tools, plus the few deliberate differences.",},}-func addResources(srv *mcp.Server) {- for _, r := range knowledgeResources {+var writeResources = []struct {+ uri, file, name, description string+}{+ {+ uri: "traceway://knowledge/operations", file: "operations.md", name: "Operating with write access",+ description: "The three opt-in levels for agent writes, what each write tool changes, the rules for every write, and playbooks for pages, flapping alerts, confirming fixes, post-mortems and slow endpoints. Read before your first write.",+ },+}++func addResources(srv *mcp.Server, allowWrite bool) {+ resources := knowledgeResources+ if allowWrite {+ resources = append(slices.Clone(knowledgeResources), writeResources...)+ }+ for _, r := range resources {text := knowledge.MustRead(r.file)uri := r.urisrv.AddResource(&mcp.Resource{diff --git a/cli/pkg/mcpserver/schema.go b/cli/pkg/mcpserver/schema.goindex 63514fb6..372cf47e 100644--- a/cli/pkg/mcpserver/schema.go+++ b/cli/pkg/mcpserver/schema.go@@ -48,3 +48,7 @@ func allowNullMaps(s *jsonschema.Schema) {allowNullMaps(s.Items)allowNullMaps(s.AdditionalProperties)}++// passThroughSchema describes the tools whose result is the server's JSON+// passed through unchanged: always an object, shape owned by the backend.+var passThroughSchema = &jsonschema.Schema{Type: "object"}diff --git a/cli/pkg/mcpserver/server.go b/cli/pkg/mcpserver/server.goindex f2690e4d..fc96c328 100644--- a/cli/pkg/mcpserver/server.go+++ b/cli/pkg/mcpserver/server.go@@ -38,6 +38,10 @@ type Config struct {// CLI-session advice.AuthHint stringPerRequestBearer bool+ // AllowWrite registers the mutating tools and the write playbook. The+ // server still enforces scopes: a read token on a write server is refused+ // by the API on every mutating call.+ AllowWrite bool}// sharedSchemaCache warms an mcp.SchemaCache once, by registering the full@@ -49,7 +53,7 @@ var sharedSchemaCache = sync.OnceValue(func() *mcp.SchemaCache {&mcp.Implementation{Name: "traceway", Title: "Traceway", Version: "warmup"},&mcp.ServerOptions{SchemaCache: cache},)- (&server{}).addTools(warm)+ (&server{cfg: Config{AllowWrite: true}}).addTools(warm)return cache})@@ -61,6 +65,9 @@ func New(cfg Config) *mcp.Server {version = "dev"}instructions := knowledge.MustRead("instructions.md")+ if cfg.AllowWrite {+ instructions += "\n\n" + knowledge.MustRead("write-instructions.md")+ }if cfg.InstanceURL != "" {instructions += "\n\nThe connected Traceway instance is " + cfg.InstanceURL + ". Dashboard URLs the user pastes should match this origin, and when citing a record for the user, link it there (e.g. " + cfg.InstanceURL + "/issues/<hash>)."}@@ -71,7 +78,7 @@ func New(cfg Config) *mcp.Server {s := &server{cfg: cfg}s.addTools(srv)addPrompts(srv)- addResources(srv)+ addResources(srv, cfg.AllowWrite)return srv}diff --git a/cli/pkg/mcpserver/server_test.go b/cli/pkg/mcpserver/server_test.goindex fd1ae5bf..42bda145 100644--- a/cli/pkg/mcpserver/server_test.go+++ b/cli/pkg/mcpserver/server_test.go@@ -2,6 +2,7 @@ package mcpserverimport ("encoding/json"+ "io/fs""net/http""net/http/httptest""strings"@@ -10,11 +11,22 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""github.com/tracewayapp/traceway/cli/pkg/client"+ "github.com/tracewayapp/traceway/cli/pkg/mcpserver/knowledge")// connect stands up the MCP server over in-memory transports against the// given fake backend and returns a connected client session.func connect(t *testing.T, backend http.Handler, projectID string) *mcp.ClientSession {+ t.Helper()+ return connectServer(t, backend, projectID, false)+}++func connectWrite(t *testing.T, backend http.Handler, projectID string) *mcp.ClientSession {+ t.Helper()+ return connectServer(t, backend, projectID, true)+}++func connectServer(t *testing.T, backend http.Handler, projectID string, allowWrite bool) *mcp.ClientSession {t.Helper()ts := httptest.NewServer(backend)t.Cleanup(ts.Close)@@ -24,6 +36,7 @@ func connect(t *testing.T, backend http.Handler, projectID string) *mcp.ClientSeDefaultProjectID: projectID,InstanceURL: ts.URL,Version: "test",+ AllowWrite: allowWrite,})serverTransport, clientTransport := mcp.NewInMemoryTransports()@@ -77,11 +90,43 @@ func TestListTools_surfaceAndAnnotations(t *testing.T) {"get_exception_occurrence": true, "query_logs": true, "list_endpoints": true,"get_endpoint_request": true, "endpoints_chart": true, "get_slow_endpoint_config": true,"query_metrics": true, "get_task": true, "get_ai_trace": true, "get_session": true,- "get_trace": true,+ "get_trace": true, "list_pages": true, "get_page": true,+ "list_notification_rules": true, "list_checks": true, "get_check": true,+ "list_post_mortems": true, "get_post_mortem": true,+ }+ assertToolSurface(t, res.Tools, wantReadOnly)+}++func TestListTools_writeServerAddsMutatingTools(t *testing.T) {+ cs := connectWrite(t, emptyBackend(), "p-1")+ res, err := cs.ListTools(t.Context(), nil)+ if err != nil {+ t.Fatal(err)+ }+ want := map[string]bool{+ "list_projects": true, "list_exceptions": true, "get_exception": true,+ "get_exception_occurrence": true, "query_logs": true, "list_endpoints": true,+ "get_endpoint_request": true, "endpoints_chart": true, "get_slow_endpoint_config": true,+ "query_metrics": true, "get_task": true, "get_ai_trace": true, "get_session": true,+ "get_trace": true, "list_pages": true, "get_page": true,+ "list_notification_rules": true, "list_checks": true, "get_check": true,+ "list_post_mortems": true, "get_post_mortem": true,"archive_exceptions": false, "unarchive_exceptions": false,+ "acknowledge_page": false, "resolve_page": false,+ "set_notification_rule_enabled": false, "snooze_notification_rule": false,+ "run_check": false, "create_post_mortem": false, "update_post_mortem": false,+ "set_slow_endpoint": false,}+ assertToolSurface(t, res.Tools, want)+ if init := cs.InitializeResult(); init == nil || !strings.Contains(init.Instructions, "Write access") {+ t.Errorf("write server instructions should carry the write rules")+ }+}++func assertToolSurface(t *testing.T, tools []*mcp.Tool, wantReadOnly map[string]bool) {+ t.Helper()got := map[string]bool{}- for _, tool := range res.Tools {+ for _, tool := range tools {if tool.OutputSchema == nil {t.Errorf("tool %s has no output schema", tool.Name)}@@ -319,7 +364,7 @@ func TestArchiveExceptions_hitsArchiveRoute(t *testing.T) {w.Header().Set("Content-Type", "application/json")_, _ = w.Write([]byte(`{"success":true}`))})- cs := connect(t, backend, "p-1")+ cs := connectWrite(t, backend, "p-1")res := callTool(t, cs, "archive_exceptions", map[string]any{"hashes": []string{"abc123def4567890"}})if res.IsError {t.Fatalf("unexpected tool error: %s", resultText(t, res))@@ -398,6 +443,22 @@ func TestResources_listAndRead(t *testing.T) {}}+func TestResources_everyLearnTopicIsServed(t *testing.T) {+ topics, err := fs.Glob(knowledge.FS, "learn/*.md")+ if err != nil {+ t.Fatal(err)+ }+ served := map[string]bool{}+ for _, r := range knowledgeResources {+ served[r.file] = true+ }+ for _, topic := range topics {+ if !served[topic] {+ t.Errorf("%s has no traceway://knowledge resource", topic)+ }+ }+}+func TestPrompts_renderFromKnowledge(t *testing.T) {cs := connect(t, emptyBackend(), "p-1")list, err := cs.ListPrompts(t.Context(), nil)diff --git a/cli/pkg/mcpserver/tools.go b/cli/pkg/mcpserver/tools.goindex 198e8317..f0845d4a 100644--- a/cli/pkg/mcpserver/tools.go+++ b/cli/pkg/mcpserver/tools.go@@ -108,6 +108,16 @@ func (s *server) addTools(srv *mcp.Server) {Annotations: readOnly(),}, s.getTrace)+ s.addOperationReadTools(srv)+ if s.cfg.AllowWrite {+ s.addWriteTools(srv)+ }+}++// addWriteTools registers the mutating tools. They exist only on the write+// server (traceway-write mcp, or /mcp/write on the backend), so a read+// session never sees them in its tool list.+func (s *server) addWriteTools(srv *mcp.Server) {mcp.AddTool(srv, &mcp.Tool{Name: "archive_exceptions",OutputSchema: outSchema[archiveResult](),@@ -121,4 +131,6 @@ func (s *server) addTools(srv *mcp.Server) {Description: "Unarchive previously archived exception groups by hash. MUTATING. Only call when the user explicitly asked for it.",Annotations: mutating(),}, s.unarchiveExceptions)++ s.addOperationWriteTools(srv)}diff --git a/cli/pkg/mcpserver/tools_operations.go b/cli/pkg/mcpserver/tools_operations.gonew file mode 100644index 00000000..d7037d03--- /dev/null+++ b/cli/pkg/mcpserver/tools_operations.go@@ -0,0 +1,422 @@+package mcpserver++import (+ "context"+ "encoding/json"++ "github.com/modelcontextprotocol/go-sdk/mcp"++ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func (s *server) addOperationReadTools(srv *mcp.Server) {+ mcp.AddTool(srv, &mcp.Tool{+ Name: "list_pages",+ OutputSchema: passThroughSchema,+ Description: "List on-call pages (alerts that paged a person through an escalation policy). status: active (open or acknowledged, the default), open, acknowledged, resolved. A page carries its rule, subject, urgency, eventCount and, for issue pages, the exceptionHash it was opened for.",+ Annotations: readOnly(),+ }, s.listPages)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "get_page",+ OutputSchema: passThroughSchema,+ Description: "Get one on-call page by its numeric id plus its delivery log: who was notified, on which contact method, at which escalation level, and whether it was acknowledged by link.",+ Annotations: readOnly(),+ }, s.getPage)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "list_notification_rules",+ OutputSchema: passThroughSchema,+ Description: "List the project's alert rules: id, name, ruleType (new_error, error_regression, error_rate_threshold, error_count_threshold, endpoint_p95_threshold, endpoint_p99_threshold, endpoint_error_rate, apdex_drop, throughput_drop, metric_threshold, no_data, task_duration_threshold, task_failure_rate, impact_score_*, ai_trace_cost, ai_conversation_cost, ai_flagged_content, check_down), enabled, snoozedUntil, threshold config and the channels they notify.",+ Annotations: readOnly(),+ }, s.listNotificationRules)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "list_checks",+ OutputSchema: passThroughSchema,+ Description: "List the project's monitors (synthetic checks): id, name, checkType (http, tcp, browser), config (URL or host and assertions), intervalSeconds, enabled, currentStatus (up, down or pending) and consecutiveFailures.",+ Annotations: readOnly(),+ }, s.listChecks)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "get_check",+ OutputSchema: passThroughSchema,+ Description: "Get one monitor by numeric id with its recent incidents (when it went down, when it recovered, incident titles and linked post-mortems).",+ Annotations: readOnly(),+ }, s.getCheck)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "list_post_mortems",+ OutputSchema: passThroughSchema,+ Description: "List the project's post-mortems, newest first. search matches title, content and tags; tags are ANDed.",+ Annotations: readOnly(),+ }, s.listPostMortems)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "get_post_mortem",+ OutputSchema: passThroughSchema,+ Description: "Get one post-mortem by numeric id: title, markdown content, tags, the linked incident and author names.",+ Annotations: readOnly(),+ }, s.getPostMortem)+}++func (s *server) addOperationWriteTools(srv *mcp.Server) {+ mcp.AddTool(srv, &mcp.Tool{+ Name: "acknowledge_page",+ OutputSchema: passThroughSchema,+ Description: "Acknowledge an open on-call page: it stops escalating to the next level. MUTATING and visible to the whole team. Only call when the user asked to acknowledge this page.",+ Annotations: mutating(),+ }, s.acknowledgePage)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "resolve_page",+ OutputSchema: passThroughSchema,+ Description: "Resolve an open or acknowledged on-call page. archive_issue also archives the issue the page was opened for. MUTATING and not undoable from the API. Only call when the user said the problem is handled.",+ Annotations: destructive(),+ }, s.resolvePage)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "set_notification_rule_enabled",+ OutputSchema: passThroughSchema,+ Description: "Turn an alert rule on or off. Idempotent: it sets the requested state, so a rule already in it is left alone. MUTATING. A disabled rule notifies nobody until re-enabled, so say so to the user.",+ Annotations: mutating(),+ }, s.setNotificationRuleEnabled)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "snooze_notification_rule",+ OutputSchema: passThroughSchema,+ Description: "Snooze an alert rule for duration_minutes from now (it is skipped entirely and comes back on its own); calling it again restarts the snooze, and 0 clears it. MUTATING. Prefer this over disabling for a known incident.",+ Annotations: mutatingRepeatable(),+ }, s.snoozeNotificationRule)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "run_check",+ OutputSchema: passThroughSchema,+ Description: "Queue an immediate run of a monitor, for example to confirm a fix. Fails with 422 when a run is already queued or browser checks are disabled. The result shows up in get_check after the run.",+ Annotations: additive(),+ }, s.runCheck)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "create_post_mortem",+ OutputSchema: passThroughSchema,+ Description: "Create a post-mortem document in the project. content_md is markdown. incident_id optionally links the incident it covers (one post-mortem per incident). MUTATING: the document is visible to the team.",+ Annotations: additive(),+ }, s.createPostMortem)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "update_post_mortem",+ OutputSchema: passThroughSchema,+ Description: "Update a post-mortem. Only the fields you pass change; content_md replaces the whole body, so read it with get_post_mortem, send the full revised text, and pass that read's updatedAt as expected_updated_at. If someone edited the document since that read, the call fails with a 409 conflict instead of overwriting their change: read it again and reapply. Every edit is recorded in the post-mortem's activity log. MUTATING.",+ Annotations: mutating(),+ }, s.updatePostMortem)++ mcp.AddTool(srv, &mcp.Tool{+ Name: "set_slow_endpoint",+ OutputSchema: passThroughSchema,+ Description: "Mark an endpoint as expected-slow: offset_ms is the accepted latency allowance and reason the note shown to the team. offset_ms 0 removes the mark. It shifts apdex and impact scoring for that endpoint, so only set it when the user decided the latency is acceptable. MUTATING.",+ Annotations: mutating(),+ }, s.setSlowEndpoint)+}++type pageIdIn struct {+ projectIn+ ID int `json:"id" jsonschema:"The page's numeric id, from list_pages or a /pages/<id> URL."`+}++type listPagesIn struct {+ projectIn+ pageIn+ Status string `json:"status,omitempty" jsonschema:"active (default), open, acknowledged, or resolved."`+}++func (s *server) listPages(ctx context.Context, req *mcp.CallToolRequest, in listPagesIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ page, err := in.pageIn.resolve()+ if err != nil {+ return nil, nil, err+ }+ if err := validateEnum("status", in.Status, client.PageStatuses); err != nil {+ return nil, nil, err+ }+ status := in.Status+ if status == "" {+ status = "active"+ }+ return s.raw(s.client(req).ListPages(ctx, projectID, client.ListPagesRequest{Status: status, Pagination: page}))+}++func (s *server) getPage(ctx context.Context, req *mcp.CallToolRequest, in pageIdIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).GetPage(ctx, projectID, in.ID))+}++func (s *server) acknowledgePage(ctx context.Context, req *mcp.CallToolRequest, in pageIdIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ if err := s.client(req).AcknowledgePage(ctx, projectID, in.ID); err != nil {+ return nil, nil, s.apiErr(err)+ }+ return nil, map[string]any{"status": "acknowledged", "id": in.ID}, nil+}++type resolvePageIn struct {+ pageIdIn+ ArchiveIssue bool `json:"archive_issue,omitempty" jsonschema:"Also archive the issue the page was opened for. Only when the user asked for it."`+}++func (s *server) resolvePage(ctx context.Context, req *mcp.CallToolRequest, in resolvePageIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ if err := s.client(req).ResolvePage(ctx, projectID, in.ID, in.ArchiveIssue); err != nil {+ return nil, nil, s.apiErr(err)+ }+ return nil, map[string]any{"status": "resolved", "id": in.ID, "archivedIssue": in.ArchiveIssue}, nil+}++func (s *server) listNotificationRules(ctx context.Context, req *mcp.CallToolRequest, in projectIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).ListNotificationRules(ctx, projectID))+}++type ruleEnabledIn struct {+ projectIn+ ID int `json:"id" jsonschema:"The rule's numeric id, from list_notification_rules."`+ Enabled bool `json:"enabled" jsonschema:"true to turn the rule on, false to turn it off."`+}++func (s *server) setNotificationRuleEnabled(ctx context.Context, req *mcp.CallToolRequest, in ruleEnabledIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).SetNotificationRuleEnabled(ctx, projectID, in.ID, in.Enabled))+}++type ruleSnoozeIn struct {+ projectIn+ ID int `json:"id" jsonschema:"The rule's numeric id, from list_notification_rules."`+ DurationMinutes int `json:"duration_minutes" jsonschema:"How long to snooze, in minutes. 0 clears the snooze."`+}++func (s *server) snoozeNotificationRule(ctx context.Context, req *mcp.CallToolRequest, in ruleSnoozeIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ if in.DurationMinutes < 0 {+ return nil, nil, usageErrf("duration_minutes must be 0 or greater")+ }+ return s.raw(s.client(req).SnoozeNotificationRule(ctx, projectID, in.ID, in.DurationMinutes))+}++func (s *server) listChecks(ctx context.Context, req *mcp.CallToolRequest, in projectIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).ListChecks(ctx, projectID))+}++type checkIdIn struct {+ projectIn+ ID int `json:"id" jsonschema:"The monitor's numeric id, from list_checks or a /monitors/<id> URL."`+}++func (s *server) getCheck(ctx context.Context, req *mcp.CallToolRequest, in checkIdIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).GetCheck(ctx, projectID, in.ID))+}++func (s *server) runCheck(ctx context.Context, req *mcp.CallToolRequest, in checkIdIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).RunCheck(ctx, projectID, in.ID))+}++type listPostMortemsIn struct {+ projectIn+ pageIn+ Search string `json:"search,omitempty" jsonschema:"Matches title, content and tags."`+ Tags []string `json:"tags,omitempty" jsonschema:"Only post-mortems carrying every one of these tags."`+}++func (s *server) listPostMortems(ctx context.Context, req *mcp.CallToolRequest, in listPostMortemsIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ page, err := in.pageIn.resolve()+ if err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).ListPostMortems(ctx, projectID, client.ListPostMortemsRequest{+ Search: in.Search, Tags: in.Tags, Page: page.Page, PageSize: page.PageSize,+ }))+}++type postMortemIdIn struct {+ projectIn+ ID int `json:"id" jsonschema:"The post-mortem's numeric id, from list_post_mortems or a /monitors/post-mortems/<id> URL."`+}++func (s *server) getPostMortem(ctx context.Context, req *mcp.CallToolRequest, in postMortemIdIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ return s.raw(s.client(req).GetPostMortem(ctx, projectID, in.ID))+}++type createPostMortemIn struct {+ projectIn+ Title string `json:"title" jsonschema:"Document title, required."`+ ContentMd string `json:"content_md,omitempty" jsonschema:"Markdown body. A good post-mortem covers summary, impact, timeline (UTC), root cause, resolution and follow-up actions."`+ Tags []string `json:"tags,omitempty" jsonschema:"Short labels such as database or deploy."`+ IncidentID int `json:"incident_id,omitempty" jsonschema:"Optional incident to link, from get_check incidents. One post-mortem per incident."`+}++func (s *server) createPostMortem(ctx context.Context, req *mcp.CallToolRequest, in createPostMortemIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if in.Title == "" {+ return nil, nil, usageErrf("title is required")+ }+ input := client.PostMortemInput{Title: in.Title, ContentMd: in.ContentMd, Tags: in.Tags}+ if in.IncidentID > 0 {+ input.IncidentId = &in.IncidentID+ }+ return s.raw(s.client(req).CreatePostMortem(ctx, projectID, input))+}++type updatePostMortemIn struct {+ projectIn+ ID int `json:"id" jsonschema:"The post-mortem's numeric id."`+ Title *string `json:"title,omitempty" jsonschema:"New title."`+ ContentMd *string `json:"content_md,omitempty" jsonschema:"New markdown body, replacing the whole document. Requires expected_updated_at."`+ Tags *[]string `json:"tags,omitempty" jsonschema:"New tag list, replacing the old one."`+ IncidentID int `json:"incident_id,omitempty" jsonschema:"Link this incident."`+ UnlinkIncident bool `json:"unlink_incident,omitempty" jsonschema:"Remove the incident link."`+ ExpectedUpdatedAt string `json:"expected_updated_at,omitempty" jsonschema:"The updatedAt of the version your edit is based on, exactly as get_post_mortem returned it. If the document changed since, the update fails with a 409 instead of overwriting that change."`+}++func (s *server) updatePostMortem(ctx context.Context, req *mcp.CallToolRequest, in updatePostMortemIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if err := positiveID("id", in.ID); err != nil {+ return nil, nil, err+ }+ if in.ContentMd != nil && in.ExpectedUpdatedAt == "" {+ return nil, nil, usageErrf("content_md replaces the whole body, so expected_updated_at is required: pass the updatedAt from the get_post_mortem your revision is based on")+ }+ if in.IncidentID > 0 && in.UnlinkIncident {+ return nil, nil, usageErrf("pass incident_id or unlink_incident, not both")+ }+ patch := client.PostMortemPatch{Title: in.Title, ContentMd: in.ContentMd, Tags: in.Tags, UnlinkIncident: in.UnlinkIncident, ExpectedUpdatedAt: in.ExpectedUpdatedAt}+ if in.IncidentID > 0 {+ patch.IncidentId = &in.IncidentID+ }+ return s.raw(s.client(req).UpdatePostMortem(ctx, projectID, in.ID, patch))+}++type setSlowEndpointIn struct {+ projectIn+ Endpoint string `json:"endpoint" jsonschema:"The endpoint name exactly as list_endpoints shows it, like GET /api/users/:id."`+ OffsetMs uint32 `json:"offset_ms" jsonschema:"Accepted extra latency in milliseconds. 0 removes the mark."`+ Reason string `json:"reason,omitempty" jsonschema:"Why this latency is acceptable, shown to the team."`+}++func (s *server) setSlowEndpoint(ctx context.Context, req *mcp.CallToolRequest, in setSlowEndpointIn) (*mcp.CallToolResult, any, error) {+ projectID, err := s.project(in.ProjectID)+ if err != nil {+ return nil, nil, err+ }+ if in.Endpoint == "" {+ return nil, nil, usageErrf("endpoint is required")+ }+ if err := s.client(req).SetSlowEndpoint(ctx, projectID, client.SetSlowEndpointRequest{Endpoint: in.Endpoint, OffsetMs: in.OffsetMs, Reason: in.Reason}); err != nil {+ return nil, nil, s.apiErr(err)+ }+ return nil, map[string]any{"status": "updated", "endpoint": in.Endpoint, "offsetMs": in.OffsetMs}, nil+}++// raw adapts a pass-through client call to a tool result: structured content+// must be a JSON object, so arrays are wrapped under "data".+func (s *server) raw(resp json.RawMessage, err error) (*mcp.CallToolResult, any, error) {+ if err != nil {+ return nil, nil, s.apiErr(err)+ }+ var v any+ if len(resp) == 0 {+ return nil, map[string]any{"status": "ok"}, nil+ }+ if err := json.Unmarshal(resp, &v); err != nil {+ return nil, nil, err+ }+ if _, ok := v.(map[string]any); !ok {+ v = map[string]any{"data": v}+ }+ return nil, v, nil+}++func positiveID(param string, id int) error {+ if id < 1 {+ return usageErrf("%s must be a positive integer", param)+ }+ return nil+}++func additive() *mcp.ToolAnnotations {+ nonDestructive := false+ return &mcp.ToolAnnotations{DestructiveHint: &nonDestructive}+}++func destructive() *mcp.ToolAnnotations {+ isDestructive := true+ return &mcp.ToolAnnotations{DestructiveHint: &isDestructive}+}diff --git a/cli/pkg/mcpserver/tools_operations_test.go b/cli/pkg/mcpserver/tools_operations_test.gonew file mode 100644index 00000000..1b7a58ad--- /dev/null+++ b/cli/pkg/mcpserver/tools_operations_test.go@@ -0,0 +1,129 @@+package mcpserver++import (+ "encoding/json"+ "net/http"+ "strings"+ "testing"+)++func TestListPages_defaultsToActive(t *testing.T) {+ var body map[string]any+ backend := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/pages" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ _, _ = w.Write([]byte(`{"data":[],"pagination":{"page":1,"pageSize":20,"total":0,"totalPages":0}}`))+ })+ cs := connect(t, backend, "p-1")+ res := callTool(t, cs, "list_pages", nil)+ if res.IsError {+ t.Fatalf("tool error: %s", resultText(t, res))+ }+ if body["status"] != "active" {+ t.Errorf("status = %v", body["status"])+ }+ if res.StructuredContent == nil {+ t.Error("pass-through tools must return structured content")+ }+}++func TestPassThrough_wrapsArrays(t *testing.T) {+ backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`[{"id":1}]`))+ })+ cs := connect(t, backend, "p-1")+ res := callTool(t, cs, "list_notification_rules", nil)+ if res.IsError {+ t.Fatalf("tool error: %s", resultText(t, res))+ }+ m, ok := res.StructuredContent.(map[string]any)+ if !ok || m["data"] == nil {+ t.Errorf("an array result must be wrapped under data, got %#v", res.StructuredContent)+ }+}++func TestUpdatePostMortem_mergesWithCurrent(t *testing.T) {+ var put map[string]any+ backend := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodGet {+ _, _ = w.Write([]byte(`{"id":3,"title":"Keep me","contentMd":"old","tags":["a"],"incidentId":null,"updatedAt":"2026-10-15T10:05:00Z"}`))+ return+ }+ _ = json.NewDecoder(r.Body).Decode(&put)+ _, _ = w.Write([]byte(`{"id":3,"title":"Keep me","contentMd":"new"}`))+ })+ cs := connectWrite(t, backend, "p-1")+ res := callTool(t, cs, "update_post_mortem", map[string]any{"id": 3, "content_md": "new", "expected_updated_at": "2026-10-15T10:00:00Z"})+ if res.IsError {+ t.Fatalf("tool error: %s", resultText(t, res))+ }+ if put["title"] != "Keep me" || put["contentMd"] != "new" {+ t.Errorf("PUT body = %v", put)+ }+ if put["expectedUpdatedAt"] != "2026-10-15T10:00:00Z" {+ t.Errorf("expectedUpdatedAt = %v, want the revision the agent read", put["expectedUpdatedAt"])+ }+}++func TestUpdatePostMortem_contentNeedsExpectedUpdatedAt(t *testing.T) {+ called := false+ backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ called = true+ _, _ = w.Write([]byte(`{}`))+ })+ cs := connectWrite(t, backend, "p-1")+ res := callTool(t, cs, "update_post_mortem", map[string]any{"id": 3, "content_md": "new"})+ if !res.IsError || !strings.Contains(resultText(t, res), "expected_updated_at") || called {+ t.Errorf("want an invalid_argument error before any request, got %s (called %v)", resultText(t, res), called)+ }+}++func TestWriteTools_surfaceForbiddenMessage(t *testing.T) {+ backend := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"error":"Agent write access is turned off for this organization."}`))+ })+ cs := connectWrite(t, backend, "p-1")+ res := callTool(t, cs, "acknowledge_page", map[string]any{"id": 4})+ if !res.IsError || !strings.Contains(resultText(t, res), "turned off") || !strings.Contains(resultText(t, res), "error=forbidden") {+ t.Errorf("want a forbidden tool error carrying the reason, got %s", resultText(t, res))+ }+}++func TestReadServer_hasNoOperationsResource(t *testing.T) {+ read := connect(t, emptyBackend(), "p-1")+ write := connectWrite(t, emptyBackend(), "p-1")+ has := func(uri string, list []string) bool {+ for _, u := range list {+ if u == uri {+ return true+ }+ }+ return false+ }+ readRes, err := read.ListResources(t.Context(), nil)+ if err != nil {+ t.Fatal(err)+ }+ writeRes, err := write.ListResources(t.Context(), nil)+ if err != nil {+ t.Fatal(err)+ }+ var readURIs, writeURIs []string+ for _, r := range readRes.Resources {+ readURIs = append(readURIs, r.URI)+ }+ for _, r := range writeRes.Resources {+ writeURIs = append(writeURIs, r.URI)+ }+ if has("traceway://knowledge/operations", readURIs) || !has("traceway://knowledge/operations", writeURIs) {+ t.Errorf("operations resource: read %v, write %v", readURIs, writeURIs)+ }+ for _, uri := range []string{"traceway://knowledge/learn", "traceway://knowledge/learn/on-call"} {+ if !has(uri, readURIs) || !has(uri, writeURIs) {+ t.Errorf("both servers carry %s: read %v, write %v", uri, readURIs, writeURIs)+ }+ }+}diff --git a/cli/test/contract/mcp_test.go b/cli/test/contract/mcp_test.goindex 620ced11..266a72ac 100644--- a/cli/test/contract/mcp_test.go+++ b/cli/test/contract/mcp_test.go@@ -1,6 +1,10 @@package contractimport (+ "encoding/base64"+ "encoding/json"+ "net/http"+ "strconv""strings""testing""time"@@ -16,11 +20,172 @@ import (// above pin the wire shapes; this asserts the MCP layer's parameter plumbing// (project fallback, time ranges, mandatory timestamps) works end to end.func TestContract_mcpToolSurface(t *testing.T) {+ cs := connectInMemory(t, false)++ from := seedAt.Add(-time.Hour).Format(time.RFC3339)+ to := seedAt.Add(time.Hour).Format(time.RFC3339)+ at := seedAt.Format(time.RFC3339)++ call := toolCaller(t, cs)+ call("list_projects", nil, projectID)+ call("list_exceptions", map[string]any{"from": from, "to": to}, seedHash)+ call("get_exception", map[string]any{"hash": seedHash}, seedExceptionID.String())+ call("get_exception_occurrence", map[string]any{"id": seedExceptionID.String(), "recorded_at": at}, seedHash)+ call("query_logs", map[string]any{"from": from, "to": to, "service_name": "contract-svc"}, "contract-svc")+ call("list_endpoints", map[string]any{"from": from, "to": to}, "GET /api/contract")+ call("get_endpoint_request", map[string]any{"id": seedEndpointID.String(), "recorded_at": at}, seedEndpointID.String())+ call("endpoints_chart", map[string]any{"from": from, "to": to}, "endpoints")+ call("get_slow_endpoint_config", map[string]any{"endpoint": "GET /api/contract"}, "offsetMs")+ call("query_metrics", map[string]any{+ "from": from, "to": to, "interval_minutes": 60,+ "queries": []map[string]any{{"name": seedMetricName}},+ }, seedMetricName)+ call("get_task", map[string]any{"id": seedTaskID.String(), "recorded_at": at}, seedTaskID.String())+ call("get_ai_trace", map[string]any{"id": seedAiTraceID.String(), "recorded_at": at}, seedAiTraceID.String())+ call("get_session", map[string]any{"id": seedSessionID.String(), "started_at": at}, seedSessionID.String())+ call("get_trace", map[string]any{"id": seedTraceID, "recorded_at": at}, seedTraceID)++ call("list_pages", map[string]any{"status": "resolved"}, "pagination")+ call("list_notification_rules", nil, "rules")+ call("list_checks", nil, "checks")+ call("list_post_mortems", nil, "pagination")+}++// TestContract_mcpWriteTools calls every write tool through /mcp/write with a+// write token after the organization opted in, so a write route missing from+// the backend's agent allowlist fails here, not in production.+func TestContract_mcpWriteTools(t *testing.T) {+ setAgentWrites(t, true)+ t.Cleanup(func() { setAgentWrites(t, false) })+ cs, err := connectRemote(t, "/mcp/write", oauthScopedAccessToken(t, "traceway:write"))+ if err != nil {+ t.Fatalf("connect /mcp/write: %v", err)+ }+ t.Cleanup(func() { _ = cs.Close() })+ callTool := toolCaller(t, cs)+ call := func(name string, args map[string]any, wantSubstr string) map[string]any {+ t.Helper()+ if args == nil {+ args = map[string]any{}+ }+ args["project_id"] = projectID+ return callTool(name, args, wantSubstr)+ }+ ruleID, checkID, pageID := seedOperations(t)++ call("archive_exceptions", map[string]any{"hashes": []string{seedHash}}, "archived")+ call("unarchive_exceptions", map[string]any{"hashes": []string{seedHash}}, "unarchived")+ call("set_slow_endpoint", map[string]any{"endpoint": "GET /api/contract", "offset_ms": 250, "reason": "contract"}, "updated")+ call("get_slow_endpoint_config", map[string]any{"endpoint": "GET /api/contract"}, "250")+ call("set_slow_endpoint", map[string]any{"endpoint": "GET /api/contract", "offset_ms": 0}, "updated")++ created := call("create_post_mortem", map[string]any{"title": "Contract outage", "content_md": "first draft", "tags": []string{"contract"}}, "Contract outage")+ id, ok := created["id"].(float64)+ if !ok {+ t.Fatalf("create_post_mortem returned no id: %v", created)+ }+ call("update_post_mortem", map[string]any{"id": int(id), "content_md": "revised", "expected_updated_at": created["updatedAt"]}, "revised")+ got := call("get_post_mortem", map[string]any{"id": int(id)}, "revised")+ if got["title"] != "Contract outage" {+ t.Errorf("update_post_mortem must keep fields it was not given, title = %v", got["title"])+ }+ stale, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "update_post_mortem", Arguments: map[string]any{+ "project_id": projectID, "id": int(id), "content_md": "based on the first draft", "expected_updated_at": created["updatedAt"],+ }})+ if err != nil || !stale.IsError || !strings.Contains(stale.Content[0].(*mcp.TextContent).Text, "changed since it was read") {+ t.Errorf("an update based on a stale read must be refused with a conflict, got err=%v result=%+v", err, stale)+ }+ call("list_post_mortems", map[string]any{"search": "Contract"}, "Contract outage")++ call("set_notification_rule_enabled", map[string]any{"id": ruleID, "enabled": false}, "")+ call("set_notification_rule_enabled", map[string]any{"id": ruleID, "enabled": true}, "")+ call("snooze_notification_rule", map[string]any{"id": ruleID, "duration_minutes": 30}, "snoozedUntil")+ call("snooze_notification_rule", map[string]any{"id": ruleID, "duration_minutes": 0}, "")+ call("list_notification_rules", nil, "Contract rule")++ call("run_check", map[string]any{"id": checkID}, "")+ call("get_check", map[string]any{"id": checkID}, "Contract check")++ call("acknowledge_page", map[string]any{"id": pageID}, "")+ call("get_page", map[string]any{"id": pageID}, "acknowledged")+ call("resolve_page", map[string]any{"id": pageID}, "")+ call("get_page", map[string]any{"id": pageID}, "resolved")+}++// seedOperations creates, with the dashboard session, the alert rule, monitor+// and open page the write tools act on. The page comes from an escalation+// channel's test button, the one way to open a real page without firing a rule.+func seedOperations(t *testing.T) (ruleID, checkID, pageID int) {+ t.Helper()+ q := "?projectId=" + projectID+ post := func(path string, body any) map[string]any {+ status, _, res := doJSON(t, http.MethodPost, path, jwtToken, body)+ if status != http.StatusOK && status != http.StatusCreated {+ t.Fatalf("POST %s: %d %v", path, status, res)+ }+ return res+ }+ number := func(res map[string]any, key string) int {+ v, ok := res[key].(float64)+ if !ok {+ t.Fatalf("response has no numeric %q: %v", key, res)+ }+ return int(v)+ }++ email := post("/api/notification-channels"+q, map[string]any{"name": "Contract email", "channelType": "email", "config": map[string]any{"recipients": []string{"[email protected]"}}})+ ruleID = number(post("/api/notification-rules"+q, map[string]any{+ "channelId": number(email, "id"), "name": "Contract rule", "ruleType": "error_rate_threshold",+ "config": map[string]any{"thresholdPercent": 50, "lookbackMinutes": 5, "minRequests": 10}, "cooldownMinutes": 15,+ }), "id")++ checkID = number(post("/api/synthetics/checks"+q, map[string]any{+ "name": "Contract check", "checkType": "http", "intervalSeconds": 3600, "timeoutSeconds": 10, "failureThreshold": 2,+ "config": map[string]any{"url": baseURL + "/api/has-organizations", "method": "GET"},+ }), "id")++ policy := post("/api/organizations/"+strconv.Itoa(organizationOfProject(t))+"/escalation-policies", map[string]any{+ "name": "Contract policy",+ "definition": map[string]any{"schemaVersion": 1, "repeatCount": 0, "steps": []map[string]any{+ {"delayMinutes": 5, "targets": []map[string]any{{"type": "user", "id": jwtUserID(t)}}},+ }},+ })+ escalation := post("/api/notification-channels"+q, map[string]any{"name": "Contract paging", "channelType": "escalation", "config": map[string]any{"policyId": number(policy, "id")}})+ post("/api/notification-channels/"+strconv.Itoa(number(escalation, "id"))+"/test"+q, nil)++ pages := post("/api/pages"+q, map[string]any{"status": "open", "pagination": map[string]any{"page": 1, "pageSize": 10}})+ data, _ := pages["data"].([]any)+ if len(data) == 0 {+ t.Fatalf("the escalation channel test opened no page: %v", pages)+ }+ first, _ := data[0].(map[string]any)+ return ruleID, checkID, number(first, "id")+}++func jwtUserID(t *testing.T) int {+ t.Helper()+ parts := strings.Split(jwtToken, ".")+ payload, err := base64.RawURLEncoding.DecodeString(parts[1])+ if err != nil {+ t.Fatal(err)+ }+ var claims struct {+ UserID int `json:"userId"`+ }+ if err := json.Unmarshal(payload, &claims); err != nil || claims.UserID == 0 {+ t.Fatalf("session JWT carries no userId: %v %s", err, payload)+ }+ return claims.UserID+}++func connectInMemory(t *testing.T, allowWrite bool) *mcp.ClientSession {+ t.Helper()srv := mcpserver.New(mcpserver.Config{Client: client.New(baseURL, client.WithJWT(jwtToken)),DefaultProjectID: projectID,InstanceURL: baseURL,Version: "contract",+ AllowWrite: allowWrite,})serverTransport, clientTransport := mcp.NewInMemoryTransports()if _, err := srv.Connect(t.Context(), serverTransport, nil); err != nil {@@ -30,13 +195,12 @@ func TestContract_mcpToolSurface(t *testing.T) {if err != nil {t.Fatalf("client connect: %v", err)}- defer func() { _ = cs.Close() }()-- from := seedAt.Add(-time.Hour).Format(time.RFC3339)- to := seedAt.Add(time.Hour).Format(time.RFC3339)- at := seedAt.Format(time.RFC3339)+ t.Cleanup(func() { _ = cs.Close() })+ return cs+}- call := func(name string, args map[string]any, wantSubstr string) {+func toolCaller(t *testing.T, cs *mcp.ClientSession) func(name string, args map[string]any, wantSubstr string) map[string]any {+ return func(name string, args map[string]any, wantSubstr string) map[string]any {t.Helper()res, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: name, Arguments: args})if err != nil {@@ -54,27 +218,7 @@ func TestContract_mcpToolSurface(t *testing.T) {if wantSubstr != "" && !strings.Contains(text.String(), wantSubstr) {t.Errorf("%s: result missing %q: %s", name, wantSubstr, clip([]byte(text.String())))}+ structured, _ := res.StructuredContent.(map[string]any)+ return structured}-- call("list_projects", nil, projectID)- call("list_exceptions", map[string]any{"from": from, "to": to}, seedHash)- call("get_exception", map[string]any{"hash": seedHash}, seedExceptionID.String())- call("get_exception_occurrence", map[string]any{"id": seedExceptionID.String(), "recorded_at": at}, seedHash)- call("query_logs", map[string]any{"from": from, "to": to, "service_name": "contract-svc"}, "contract-svc")- call("list_endpoints", map[string]any{"from": from, "to": to}, "GET /api/contract")- call("get_endpoint_request", map[string]any{"id": seedEndpointID.String(), "recorded_at": at}, seedEndpointID.String())- call("endpoints_chart", map[string]any{"from": from, "to": to}, "endpoints")- call("get_slow_endpoint_config", map[string]any{"endpoint": "GET /api/contract"}, "offsetMs")- call("query_metrics", map[string]any{- "from": from, "to": to, "interval_minutes": 60,- "queries": []map[string]any{{"name": seedMetricName}},- }, seedMetricName)- call("get_task", map[string]any{"id": seedTaskID.String(), "recorded_at": at}, seedTaskID.String())- call("get_ai_trace", map[string]any{"id": seedAiTraceID.String(), "recorded_at": at}, seedAiTraceID.String())- call("get_session", map[string]any{"id": seedSessionID.String(), "started_at": at}, seedSessionID.String())- call("get_trace", map[string]any{"id": seedTraceID, "recorded_at": at}, seedTraceID)-- // Archive round trip last, restoring state for any test that follows.- call("archive_exceptions", map[string]any{"hashes": []string{seedHash}}, "archived")- call("unarchive_exceptions", map[string]any{"hashes": []string{seedHash}}, "unarchived")}diff --git a/cli/test/contract/oauth_mcp_test.go b/cli/test/contract/oauth_mcp_test.goindex 947a7ee8..fdee60e7 100644--- a/cli/test/contract/oauth_mcp_test.go+++ b/cli/test/contract/oauth_mcp_test.go@@ -9,6 +9,7 @@ import ("net/http""net/url""slices"+ "strconv""strings""testing""time"@@ -77,6 +78,11 @@ func registerOAuthClient(t *testing.T, redirectURI string) string {}func approveAndGetCode(t *testing.T, clientID, redirectURI, challenge, state string) string {+ t.Helper()+ return approveScopedCode(t, clientID, redirectURI, challenge, state, "")+}++func approveScopedCode(t *testing.T, clientID, redirectURI, challenge, state, scope string) string {t.Helper()status, _, body := doJSON(t, http.MethodPost, "/api/oauth/approve", jwtToken, map[string]any{"client_id": clientID,@@ -85,6 +91,7 @@ func approveAndGetCode(t *testing.T, clientID, redirectURI, challenge, state str"code_challenge": challenge,"code_challenge_method": "S256","resource": baseURL + "/mcp",+ "scope": scope,})if status != http.StatusOK {t.Fatalf("approve: status %d body %v", status, body)@@ -118,11 +125,16 @@ func exchangeCode(t *testing.T, clientID, redirectURI, code, verifier string) (i}func oauthAccessToken(t *testing.T) string {+ t.Helper()+ return oauthScopedAccessToken(t, "")+}++func oauthScopedAccessToken(t *testing.T, scope string) string {t.Helper()redirectURI := "http://127.0.0.1:47831/callback"clientID := registerOAuthClient(t, redirectURI)verifier, challenge := pkcePair(t)- code := approveAndGetCode(t, clientID, redirectURI, challenge, "mcp-state")+ code := approveScopedCode(t, clientID, redirectURI, challenge, "mcp-state", scope)status, body := exchangeCode(t, clientID, redirectURI, code, verifier)if status != http.StatusOK {t.Fatalf("exchange: status %d body %v", status, body)@@ -382,8 +394,13 @@ func TestContract_mcpOverStreamableHTTP(t *testing.T) {if err != nil {t.Fatal(err)}- if len(tools.Tools) != 16 {- t.Errorf("got %d tools, want 16", len(tools.Tools))+ if len(tools.Tools) != 21 {+ t.Errorf("got %d tools, want 21", len(tools.Tools))+ }+ for _, tool := range tools.Tools {+ if !tool.Annotations.ReadOnlyHint {+ t.Errorf("/mcp must only expose read tools, found %s", tool.Name)+ }}for _, tool := range tools.Tools {if tool.OutputSchema == nil {@@ -437,3 +454,143 @@ func TestContract_mcpOverStreamableHTTP(t *testing.T) {t.Errorf("list_projects over the mount failed: %s", text(projects))}}++func connectRemote(t *testing.T, path, token string) (*mcp.ClientSession, error) {+ t.Helper()+ transport := &mcp.StreamableClientTransport{+ Endpoint: baseURL + path,+ HTTPClient: &http.Client{Transport: bearerTransport{token}, Timeout: 60 * time.Second},+ }+ return mcp.NewClient(&mcp.Implementation{Name: "contract-remote", Version: "0"}, nil).Connect(t.Context(), transport, nil)+}++func organizationOfProject(t *testing.T) int {+ t.Helper()+ req, _ := http.NewRequest(http.MethodGet, baseURL+"/api/projects", nil)+ req.Header.Set("Authorization", "Bearer "+jwtToken)+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer resp.Body.Close()+ var projects []struct {+ Id string `json:"id"`+ OrganizationId int `json:"organizationId"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&projects); err != nil {+ t.Fatal(err)+ }+ for _, p := range projects {+ if p.Id == projectID {+ return p.OrganizationId+ }+ }+ t.Fatalf("seeded project %s not in /api/projects", projectID)+ return 0+}++func setAgentWrites(t *testing.T, enabled bool) {+ t.Helper()+ path := "/api/organizations/" + strconv.Itoa(organizationOfProject(t)) + "/agent-access"+ if status, _, body := doJSON(t, http.MethodPut, path, jwtToken, map[string]any{"agentWriteEnabled": enabled}); status != http.StatusOK {+ t.Fatalf("set agent writes: %d %v", status, body)+ }+}++// TestContract_mcpWriteMount walks the three opt-in levels over the real+// /mcp/write mount: a read token is refused at the door, a write token is+// refused by the organization until an admin opts in, and then it writes.+func TestContract_mcpWriteMount(t *testing.T) {+ status, _, prm := doJSON(t, http.MethodGet, "/.well-known/oauth-protected-resource/mcp/write", "", nil)+ if status != http.StatusOK || prm["resource"] != baseURL+"/mcp/write" {+ t.Fatalf("write resource metadata: %d %v", status, prm)+ }+ if scopes, _ := prm["scopes_supported"].([]any); !slices.Contains(scopes, any("traceway:write")) {+ t.Errorf("write resource must advertise traceway:write, got %v", prm["scopes_supported"])+ }++ // A dashboard session is refused too: sessions skip the agent gate, so+ // one behind /mcp/write would write past the opt-in and the audit log.+ for name, token := range map[string]string{"read token": oauthAccessToken(t), "dashboard session": jwtToken} {+ req, _ := http.NewRequest(http.MethodPost, baseURL+"/mcp/write", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`))+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json, text/event-stream")+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusForbidden || !strings.Contains(resp.Header.Get("WWW-Authenticate"), `scope="traceway:write"`) {+ t.Fatalf("%s on /mcp/write = %d %q, want 403 with a traceway:write scope challenge", name, resp.StatusCode, resp.Header.Get("WWW-Authenticate"))+ }+ }++ writeToken := oauthScopedAccessToken(t, "traceway:write")+ cs, err := connectRemote(t, "/mcp/write", writeToken)+ if err != nil {+ t.Fatalf("connect /mcp/write: %v", err)+ }+ defer func() { _ = cs.Close() }()+ tools, err := cs.ListTools(t.Context(), nil)+ if err != nil {+ t.Fatal(err)+ }+ if len(tools.Tools) != 31 {+ t.Errorf("/mcp/write tools = %d, want 31", len(tools.Tools))+ }++ archive := func() (*mcp.CallToolResult, string) {+ res, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "archive_exceptions", Arguments: map[string]any{"project_id": projectID, "hashes": []string{seedHash}}})+ if err != nil {+ t.Fatalf("archive: %v", err)+ }+ var sb strings.Builder+ for _, c := range res.Content {+ if tc, ok := c.(*mcp.TextContent); ok {+ sb.WriteString(tc.Text)+ }+ }+ return res, sb.String()+ }++ setAgentWrites(t, false)+ if res, text := archive(); !res.IsError || !strings.Contains(text, "turned off") {+ t.Fatalf("write before opt-in should be refused by the organization, got %v %s", res.IsError, text)+ }++ setAgentWrites(t, true)+ t.Cleanup(func() { setAgentWrites(t, false) })+ if res, text := archive(); res.IsError {+ t.Fatalf("write after opt-in: %s", text)+ }+ unarchive, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "unarchive_exceptions", Arguments: map[string]any{"project_id": projectID, "hashes": []string{seedHash}}})+ if err != nil || unarchive.IsError {+ t.Fatalf("unarchive after opt-in: %v", err)+ }++ readSession, err := connectRemote(t, "/mcp", writeToken)+ if err != nil {+ t.Fatalf("connect /mcp with a write token: %v", err)+ }+ defer func() { _ = readSession.Close() }()+ readTools, err := readSession.ListTools(t.Context(), nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, tool := range readTools.Tools {+ if tool.Name == "archive_exceptions" {+ t.Error("/mcp must not expose write tools even to a write token")+ }+ }++ path := "/api/organizations/" + strconv.Itoa(organizationOfProject(t)) + "/agent-activity"+ status, _, activity := doJSON(t, http.MethodGet, path, jwtToken, nil)+ if status != http.StatusOK {+ t.Fatalf("agent activity: %d %v", status, activity)+ }+ pagination, _ := activity["pagination"].(map[string]any)+ if total, _ := pagination["total"].(float64); total < 3 {+ t.Errorf("agent activity should hold the refused and the two accepted writes, total = %v", pagination["total"])+ }+}diff --git a/cli/tools/skillgen/main.go b/cli/tools/skillgen/main.goindex 0a3e8551..a1afe25c 100644--- a/cli/tools/skillgen/main.go+++ b/cli/tools/skillgen/main.go@@ -1,6 +1,9 @@-// skillgen assembles the published Claude Code skill (skills/traceway/) from-// the canonical knowledge chunks embedded in pkg/mcpserver/knowledge, so the-// skill and the MCP server cannot drift. Run via 'just gen-skills' from cli/.+// skillgen assembles the published Claude Code skills from the canonical+// knowledge chunks embedded in pkg/mcpserver/knowledge, so the skills and the+// MCP server cannot drift. It writes the read-only skill to skills/traceway/,+// the product guide to skills/traceway-learn/, and the write skill to+// plugins/tw-write/skills/traceway-write/, a separate Claude Code plugin from+// the read-only tw one. Run via 'just gen-skills' from cli/.//// Note: skills-lock.json pins an installer-computed hash of the skill; after// regenerating, reinstall the skill (or rerun the skill installer) to refresh@@ -21,14 +24,51 @@ import (//go:embed skill.tmpl.mdvar skillTemplate string-const perfHeader = "<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/performance.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->\n"+//go:embed skill-write.tmpl.md+var writeSkillTemplate string+//go:embed skill-learn.tmpl.md+var learnSkillTemplate string++var learnTopics = []string{+ "issues.md",+ "endpoints-and-tasks.md",+ "traces-and-logs.md",+ "metrics-and-dashboards.md",+ "sessions-and-ai.md",+ "monitors.md",+ "alerts.md",+ "on-call.md",+ "organization.md",+}++func copiedHeader(file string) string {+ return "<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/" + file + " by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->\n"+}++// main takes an optional root to write into instead of the repository root,+// which is how gen-skills-check generates into a temp dir and diffs.func main() {- outDir := "../skills/traceway"+ root := ".."if len(os.Args) > 1 {- outDir = os.Args[1]+ root = os.Args[1]+ }++ readDir := filepath.Join(root, "skills", "traceway")+ write(filepath.Join(readDir, "SKILL.md"), render(skillTemplate))+ write(filepath.Join(readDir, "performance.md"), copiedHeader("performance.md")+knowledge.MustRead("performance.md"))++ learnDir := filepath.Join(root, "skills", "traceway-learn")+ write(filepath.Join(learnDir, "SKILL.md"), render(learnSkillTemplate))+ for _, topic := range learnTopics {+ write(filepath.Join(learnDir, topic), copiedHeader("learn/"+topic)+knowledge.MustRead("learn/"+topic))}+ writeDir := filepath.Join(root, "plugins", "tw-write", "skills", "traceway-write")+ write(filepath.Join(writeDir, "SKILL.md"), render(writeSkillTemplate))+}++func render(text string) string {tmpl := template.Must(template.New("skill").Funcs(template.FuncMap{"include": func(name string) (string, error) {b, err := knowledge.FS.ReadFile(name)@@ -37,17 +77,19 @@ func main() {}return strings.TrimRight(string(b), "\n"), nil},- }).Parse(skillTemplate))+ }).Parse(text))var sb strings.Builderif err := tmpl.Execute(&sb, nil); err != nil {fatal(err)}- write(filepath.Join(outDir, "SKILL.md"), sb.String())- write(filepath.Join(outDir, "performance.md"), perfHeader+knowledge.MustRead("performance.md"))+ return sb.String()}func write(path, content string) {+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ fatal(err)+ }if err := os.WriteFile(path, []byte(content), 0o644); err != nil {fatal(err)}diff --git a/cli/tools/skillgen/main_test.go b/cli/tools/skillgen/main_test.gonew file mode 100644index 00000000..96df038c--- /dev/null+++ b/cli/tools/skillgen/main_test.go@@ -0,0 +1,27 @@+package main++import (+ "io/fs"+ "path"+ "slices"+ "testing"++ "github.com/tracewayapp/traceway/cli/pkg/mcpserver/knowledge"+)++func TestLearnTopicsCoverEveryChunk(t *testing.T) {+ files, err := fs.Glob(knowledge.FS, "learn/*.md")+ if err != nil {+ t.Fatal(err)+ }+ var want []string+ for _, f := range files {+ if name := path.Base(f); name != "overview.md" {+ want = append(want, name)+ }+ }+ got := slices.Sorted(slices.Values(learnTopics))+ if !slices.Equal(got, want) {+ t.Errorf("learnTopics = %v, want every learn chunk except overview.md: %v", got, want)+ }+}diff --git a/cli/tools/skillgen/skill-learn.tmpl.md b/cli/tools/skillgen/skill-learn.tmpl.mdnew file mode 100644index 00000000..02f76fd0--- /dev/null+++ b/cli/tools/skillgen/skill-learn.tmpl.md@@ -0,0 +1,7 @@+---+name: traceway-learn+description: 'The full guide to Traceway, the observability platform. Explains every part of the product and how it is meant to be used: issues and exception grouping, endpoints and the impact score, tasks, spans and traces, logs, metrics and dashboards, sessions, AI traces, profiles, monitors, incidents, status pages, post-mortems, alert rules and channels, on-call teams, schedules, overrides, escalation policies and pages, contact methods, roles, organization views, settings and agent access. Use when the user asks how a Traceway page or feature works, where to find something, what a term means, or how to set up a workflow such as paging or a status page.'+---+<!-- GENERATED FILE: assembled from cli/pkg/mcpserver/knowledge/learn by cli/tools/skillgen. Edit the chunks there and run just gen-skills in cli/. -->++{{include "learn/overview.md"}}diff --git a/cli/tools/skillgen/skill-write.tmpl.md b/cli/tools/skillgen/skill-write.tmpl.mdnew file mode 100644index 00000000..9be86e80--- /dev/null+++ b/cli/tools/skillgen/skill-write.tmpl.md@@ -0,0 +1,85 @@+---+name: traceway-write+description: 'Operate a Traceway instance with write access. Use when the user wants an agent to change something in Traceway: archive or unarchive issues, acknowledge or resolve on-call pages, snooze, enable or disable alert rules, run a monitor now, create or edit a post-mortem, or mark an endpoint as expected-slow. Requires the separate traceway-write CLI or the /mcp/write server, a write credential, and an organization admin who turned on agent writes.'+---+<!-- GENERATED FILE: assembled from cli/pkg/mcpserver/knowledge by cli/tools/skillgen. Edit the chunks there and run just gen-skills in cli/. -->++# Traceway with write access++This skill drives the `traceway-write` CLI (or the write MCP server) to make the routine changes an on-call engineer makes: archive issues, acknowledge and resolve pages, snooze or toggle alert rules, run monitors, write post-mortems and mark slow endpoints.++To explain how a part of Traceway works before or after a change (what acknowledging a page does to escalation, how a snooze differs from disabling a rule, how a monitor opens an incident), use the `traceway-learn` skill. It is the full product guide. Over MCP the same guide is the `traceway://knowledge/learn` resources.++For pure investigation (debugging an issue, latency analysis), the read-only `traceway` skill has the deeper playbooks. Its commands work the same way here: every read command of `traceway` also exists in `traceway-write`.++> If a `traceway-write` MCP server is connected (stdio `traceway-write mcp`, or `https://<instance>/mcp/write`), prefer its tools over shelling out. Its resources carry this skill's knowledge, and its tool names are listed in the table below.++## Setup++### 1. Install the write CLI++`traceway-write` is a separate binary with its own login, so a read-only `traceway` install can never be upgraded to write in place.++```bash+curl -fsSL https://cli.tracewayapp.com/install.sh | sh -s -- --write+traceway-write version+```++Prebuilt archives are on the [releases page](https://github.com/tracewayapp/traceway/releases) under `cli/vX.Y.Z` tags as `traceway-write_<version>_<os>_<arch>.tar.gz`. From source: `cd traceway/cli && go build -tags write -o bin/traceway-write ./cmd/traceway`.++### 2. Log in with write access++Ask the user to run the browser login themselves (in Claude Code: `! traceway-write login --url https://<instance>`). The approval page says the login asks for read and write access.++```bash+traceway-write login --url https://<instance>+```++Headless alternative: the user creates a **Read and write** personal access token (Account > Personal Access Tokens, prefix `tww_`, expires within 90 days) and stores it without echoing it:++```bash+printf '%s' "$TRACEWAY_WRITE_TOKEN" | traceway-write login --url https://<instance> --token-stdin+```++A read token (`twp_`) stored in `traceway-write` still cannot write: the server refuses every write with "This credential is read-only".++### 3. Organization opt-in++An organization owner or admin must turn on **Settings > Agent Access > Allow agent writes**. Until then writes answer 403 "Agent write access is turned off for this organization". Do not try to work around it: tell the user who can turn it on.++### 4. Select a project++```bash+traceway-write projects list+traceway-write projects use <project-id>+```++### MCP instead of the CLI++- Local stdio: `claude mcp add traceway-write -- traceway-write mcp` (uses the `traceway-write login`).+- Remote: add `https://<instance>/mcp/write` as an HTTP MCP server. The client runs OAuth and the consent page asks for read and write access. The plain `/mcp` server never exposes write tools, even to a write token.++{{include "operations.md"}}++## Command reference++Every `traceway` read command works in `traceway-write` (`exceptions list|show|occurrence`, `logs query`, `endpoints list|chart|show|slow`, `tasks show`, `ai-traces show`, `sessions show`, `traces show`, `metrics query`, `pages list|show`, `alerts list`, `monitors list|show`, `post-mortems list|show`). The write commands:++| Command | MCP tool | What it changes |+|---|---|---|+| `traceway-write exceptions archive <hash>... [--yes]` | `archive_exceptions` | Hides issues from the default list |+| `traceway-write exceptions unarchive <hash>... [--yes]` | `unarchive_exceptions` | Brings them back |+| `traceway-write pages ack <id>` | `acknowledge_page` | Stops escalation for a page |+| `traceway-write pages resolve <id> [--archive-issue]` | `resolve_page` | Closes a page, optionally archiving its issue |+| `traceway-write alerts enable <id>` / `disable <id>` | `set_notification_rule_enabled` | Turns a rule on or off |+| `traceway-write alerts snooze <id> --minutes N` | `snooze_notification_rule` | Silences a rule for N minutes; 0 clears |+| `traceway-write monitors run <id>` | `run_check` | Queues an immediate monitor run |+| `traceway-write post-mortems create --title T [--content-file F] [--tag X] [--incident N]` | `create_post_mortem` | New post-mortem |+| `traceway-write post-mortems update <id> [--title] [--content-file --expected-updated-at] [--tag] [--incident \| --unlink-incident]` | `update_post_mortem` | Edits only the flags passed. A new body needs the `updatedAt` it was based on |+| `traceway-write endpoints mark-slow <endpoint> --offset-ms N --reason R` | `set_slow_endpoint` | Accepted latency for an endpoint; 0 removes |++Every write command prints what it is about to do and asks for confirmation on a TTY. In scripts and agents pass `--yes` (or set `TRACEWAY_ASSUME_YES=1`) only after the user asked for that exact change. Output, flags, exit codes and error envelopes are the same as the read CLI: JSON when piped, `--fields` to trim, exit code 4 for auth and permission errors.++{{include "url-resolution.md"}}++{{include "timestamps.md"}}diff --git a/cli/tools/skillgen/skill.tmpl.md b/cli/tools/skillgen/skill.tmpl.mdindex 763bbad0..597811ff 100644--- a/cli/tools/skillgen/skill.tmpl.md+++ b/cli/tools/skillgen/skill.tmpl.md@@ -18,6 +18,8 @@ Drive a Traceway instance from the terminal with the `traceway` CLI. The first w> The CLI is under active development. If a flag documented here does not appear in `traceway <command> --help`, trust the binary.> If a `traceway` MCP server is connected, prefer its tools over shelling out to the CLI: they wrap the same API with the same semantics, and this skill's knowledge is available as its resources. The server is this same binary (`traceway mcp`).+> This skill only reads. To change anything (archive issues, acknowledge or resolve pages, snooze alerts, run monitors, write post-mortems), the user installs the separate `traceway-write` CLI and the `traceway-write` skill.+> When the user asks how a part of Traceway works (schedules, escalation, status pages, alert rules, impact score and the rest), use the `traceway-learn` skill. It is the full product guide.{{include "ground-rules.md"}}@@ -108,7 +110,6 @@ For free-form requests ("what's broken in prod?", "is /api/checkout slow?", "sho| `traceway exceptions list` | Grouped exceptions; `--search`, `--search-type text\|regex`, `--order-by lastSeen\|firstSeen\|count`, `--include-archived` || `traceway exceptions show <hash>` | One group: full stack trace + occurrences || `traceway exceptions occurrence <id> --recorded-at <t>` | One occurrence by id (fast): full detail + `sessionId` + recording |-| `traceway exceptions archive/unarchive <hash>...` | Mutating; explicit user request + `--yes` only || `traceway logs query` | Logs; `--search` (`--search-type body\|attribute`), `--service`, `--min-severity <n>`, `--trace-id` || `traceway endpoints list` | Per-endpoint p50/p95/p99 and counts; `--search`, `--order-by impact\|count\|p95\|lastSeen` || `traceway endpoints chart` | Latency over time for the top endpoints; `--metric-type total_time\|p50\|p95\|p99`, `--interval-minutes`. Use to find when latency changed |@@ -119,6 +120,10 @@ For free-form requests ("what's broken in prod?", "is /api/checkout slow?", "sho| `traceway sessions show <id> --started-at <t>` | One session by id + the exceptions that fired in it || `traceway traces show <id> --recorded-at <t>` | Distributed trace: every service node sharing the id || `traceway metrics query --name <metric>` | Time series; `--aggregation`, `--tag`, `--group-by`, `--interval-minutes` |+| `traceway pages list` / `pages show <id>` | On-call pages; `--status active\|open\|acknowledged\|resolved` |+| `traceway alerts list` | Alert rules: type, enabled, snoozed until |+| `traceway monitors list` / `monitors show <id>` | Uptime monitors, their status and incidents |+| `traceway post-mortems list` / `post-mortems show <id>` | Post-mortem documents; `--search`, `--tag` || `traceway profiles {list,use}`, `login`, `logout`, `version` | Profile and session management |The by-id `show`/`occurrence` commands take their id from a dashboard URL, a notification, or an `exceptions show` occurrence — and **require** the record's timestamp (`--recorded-at` / `--started-at`); see "Fast by-id lookups" above.diff --git a/docs/components/AgentSkillsCallout.jsx b/docs/components/AgentSkillsCallout.jsxindex 872d7cdc..e7e8e818 100644--- a/docs/components/AgentSkillsCallout.jsx+++ b/docs/components/AgentSkillsCallout.jsx@@ -1,6 +1,6 @@import { useState } from "react";-const COMMAND = "npx skills add tracewayapp/traceway";+const COMMAND = "npx skills add tracewayapp/traceway --all";export default function AgentSkillsCallout() {const [copied, setCopied] = useState(false);diff --git a/docs/pages/learn/_meta.json b/docs/pages/learn/_meta.jsonindex 6dbd5966..55d2d689 100644--- a/docs/pages/learn/_meta.json+++ b/docs/pages/learn/_meta.json@@ -25,6 +25,7 @@"cli": "CLI","cli-auth": "CLI Authentication","mcp": "MCP Server",+ "agent-write-access": "Agent Write Access","embedded-mode": "Embedded Mode","otel-agent": "OTel Agent","kubernetes": "Kubernetes",diff --git a/docs/pages/learn/agent-write-access.mdx b/docs/pages/learn/agent-write-access.mdxnew file mode 100644index 00000000..8316c611--- /dev/null+++ b/docs/pages/learn/agent-write-access.mdx@@ -0,0 +1,99 @@+# Agent Write Access++import { Callout } from "nextra/components";++AI agents can do more than read your telemetry. With write access they can make the routine changes an on-call engineer makes: archive an issue once it is fixed, acknowledge and resolve pages, snooze a noisy alert, run a monitor to confirm a fix, write the post-mortem, and mark an endpoint as expected-slow.++Writes are off by default and opt-in at three levels. All three have to agree before an agent can change anything:++| Level | What it means | Who decides |+|---|---|---|+| **Credential** | Only write credentials can write: a `tww_` token, a `traceway-write` login, or the `/mcp/write` server. Everything else is read only. | The person creating the token or logging in |+| **Organization** | An admin turns on **Settings > Agent Access**. Until then every agent write is refused. | Organization owners and admins |+| **Role** | The write runs with the role of the person who created the credential, under the same rules as the dashboard. A `readonly` member's write token cannot archive issues, change alerts, run monitors or edit post-mortems. Like in the dashboard, any member can acknowledge and resolve pages. | Existing roles and per-project overrides |++Every write a write credential makes in the organization is recorded in its agent activity log, including the writes refused because Agent Access is off.++## What agents can change++| Action | `traceway-write` command | MCP tool |+|---|---|---|+| Archive or unarchive issues | `exceptions archive <hash>...` / `unarchive` | `archive_exceptions` / `unarchive_exceptions` |+| Acknowledge a page | `pages ack <id>` | `acknowledge_page` |+| Resolve a page, optionally archiving its issue | `pages resolve <id> [--archive-issue]` | `resolve_page` |+| Turn an alert rule on or off | `alerts enable <id>` / `alerts disable <id>` | `set_notification_rule_enabled` |+| Snooze an alert rule | `alerts snooze <id> --minutes N` | `snooze_notification_rule` |+| Run a monitor now | `monitors run <id>` | `run_check` |+| Create or edit a post-mortem | `post-mortems create` / `update <id>` | `create_post_mortem` / `update_post_mortem` |+| Mark an endpoint as expected-slow | `endpoints mark-slow <endpoint> --offset-ms N` | `set_slow_endpoint` |++Everything else stays in the dashboard. Agent credentials are refused outright on every other route, including creating rules and channels, editing schedules and escalation policies, status pages and public incident updates, members and invitations, tokens, project settings, and every delete. A new dashboard route is never reachable by an agent until it is added to the agent allowlist on purpose.++## Turning it on++An organization owner or admin opens **Settings**, finds the **Agent Access** card, and switches on **Allow agent writes**. The same card lists every agent write: when, who, which credential, which project, the action and the result. Turn the switch off at any time and agent writes stop immediately. Read access is not affected.++The log keeps 90 days of history.++## Write credentials++### Write tokens++In **Account > Personal Access Tokens**, choose **Access: Read and write** when creating a token. Write tokens start with `tww_` instead of `twp_`, so they stand out in logs and secret scanners. They must expire within 90 days.++Read tokens (`twp_`) are the default. Tokens created before agent write access existed are read only. Create a new write token where an automation needs to write.++### The traceway-write CLI++`traceway-write` is a separate binary with its own login and its own config directory (`$XDG_CONFIG_HOME/traceway-write`, `$XDG_STATE_HOME/traceway-write`), so a read-only `traceway` install can never be upgraded to write in place.++```bash+curl -fsSL https://cli.tracewayapp.com/install.sh | sh -s -- --write+traceway-write login --url https://<your-instance>+traceway-write projects use <project-id>+```++Its browser login asks for read and write access, and the approval page says so. `traceway-write` has every read command of `traceway`, plus the write commands in the table above. Each write prints what it is about to change and needs `--yes` (or `TRACEWAY_ASSUME_YES=1`) outside an interactive terminal.++The read-only `traceway` CLI answers the write commands with a `write_required` error pointing here.++### The write MCP server++Every backend serves two MCP endpoints:++- `/mcp` is read only. It never lists a write tool, even for a write token.+- `/mcp/write` adds the write tools and only accepts write credentials. A read token gets `403` with a `scope="traceway:write"` challenge, which OAuth clients use to ask for the right scope.++```bash+# Claude Code, remote+claude mcp add --transport http traceway-write https://<your-instance>/mcp/write++# Claude Code, local (uses the traceway-write login)+claude mcp add traceway-write -- traceway-write mcp+```++The OAuth consent page shows a **Read and write access** warning when a client asks for the write scope.++### The traceway-write skill++The `traceway-write` skill teaches an agent the rules for writes (only on request, say the change first, prefer the reversible option) and playbooks for pages, flapping alerts, confirming fixes and writing post-mortems. `npx skills add tracewayapp/traceway --all` installs it with the other skills. In Claude Code it is its own plugin, `tw-write`, separate from the read-only `tw` plugin. The skill alone changes nothing: writes still need the `traceway-write` CLI or a write token, and an admin who turned on Agent Access. For how each part of Traceway works, it relies on the read-only `traceway-learn` skill (see [MCP Server](/learn/mcp#the-product-guide)).++```+/plugin marketplace add tracewayapp/traceway+/plugin install tw-write@traceway+```++Other agents can copy the skill folder from [`plugins/tw-write/skills/traceway-write`](https://github.com/tracewayapp/traceway/tree/main/plugins/tw-write/skills/traceway-write).++<Callout type="info">+ The binary, the MCP endpoint and the skill make write access an explicit, separate choice. The server is what enforces it: scopes on the credential, the agent route allowlist and the organization switch are all checked on every request, whatever client sent it.+</Callout>++## Upgrading++- **Existing personal access tokens become read only**, and existing CLI and MCP logins keep working as read only. Dashboard sessions are unaffected.+- **Every token, CLI login and MCP client is limited to the agent routes**, the reads plus the writes listed above, even for reading. A script that used a personal access token for anything else, such as creating projects, managing members, or deleting post-mortems, now gets `403` and has to move to the dashboard.+- **`traceway exceptions archive` and `unarchive` moved to `traceway-write`.** The read-only CLI answers them with a `write_required` error.+- **Password logins from the CLI** now receive a token scoped like the CLI that asked for it, not a full dashboard session: a 15-minute access token the CLI refreshes on its own, revoked by `logout`.++To give an automation write access, create a write token or log in with `traceway-write`, and have an admin turn on Agent Access.diff --git a/docs/pages/learn/cli-auth.mdx b/docs/pages/learn/cli-auth.mdxindex 19734a1c..0d906223 100644--- a/docs/pages/learn/cli-auth.mdx+++ b/docs/pages/learn/cli-auth.mdx@@ -19,6 +19,8 @@ traceway login ──► POST /api/auth/device/authorizeThe CLI refreshes the access token automatically when it expires, rotating the refresh token each time. You stay logged in for up to 90 days of inactivity without re-entering anything.+A `traceway login` is always read only. The separate `traceway-write` CLI runs the same flow under its own client id, and the approval page tells you it asks for read and write access. See [Agent Write Access](/learn/agent-write-access).+The device flow needs an interactive terminal (someone has to approve the code). In CI or scripts, use a personal access token or password login instead; on a headless box you can pass `--no-browser` and approve the code from another device.## Password login@@ -29,7 +31,7 @@ traceway login --username [email protected] # implies --passwordtraceway login --password-stdin # reads the password from stdin```-Password logins are not refreshable: when the token expires you log in again.+The CLI asks for a token scoped to itself, so a `traceway --password` login is read only and cannot be used as a dashboard session. Like a browser login it is a short-lived access token that the CLI refreshes automatically, and `traceway logout` revokes it on the server. (Against a Traceway server older than agent scopes, a password login is a 7-day token that is not refreshable.)## Personal access tokens@@ -41,7 +43,14 @@ traceway login --token twp_xxxxxxxxxxxxecho "twp_xxxxxxxxxxxx" | traceway login --token-stdin```-PATs are the right choice for CI and long-running automation. They're shown once at creation, carry an optional expiry, and can be revoked at any time from the same dashboard page. The backend accepts a `twp_`-prefixed token anywhere it accepts a dashboard token.+PATs are the right choice for CI and long-running automation. They're shown once at creation, carry an optional expiry, and can be revoked at any time from the same dashboard page.++A token has an access level:++- **Read only** (`twp_`, the default) reads telemetry, monitors, pages, alerts and post-mortems. It never changes anything.+- **Read and write** (`tww_`) can also make the changes listed in [Agent Write Access](/learn/agent-write-access), in organizations where an admin turned agent writes on. It must expire within 90 days.++Tokens only reach the API routes the CLI and MCP server use. Account, member, token and settings routes refuse them, so a leaked token cannot mint another token or approve a login.## Logging outdiff --git a/docs/pages/learn/cli.mdx b/docs/pages/learn/cli.mdxindex 2bd89468..78f86430 100644--- a/docs/pages/learn/cli.mdx+++ b/docs/pages/learn/cli.mdx@@ -2,7 +2,7 @@import { Callout } from "nextra/components";-`traceway` is a command-line client for the Traceway HTTP API: exceptions, logs, endpoints, tasks, traces, and metrics from a terminal. It is designed to be first-class for both humans (with `gh`-style ergonomics) and LLM agents invoking it via shell tools: JSON output when piped, stable error identifiers and exit codes, and nothing that hangs waiting for input. For a quick tour, see the [CLI product page](https://tracewayapp.com/product/cli).+`traceway` is a command-line client for the Traceway HTTP API: exceptions, logs, endpoints, tasks, traces, metrics, monitors, alerts, on-call pages and post-mortems from a terminal. It is read only. Changes go through the separate `traceway-write` CLI described in [Agent Write Access](/learn/agent-write-access). It is designed to be first-class for both humans (with `gh`-style ergonomics) and LLM agents invoking it via shell tools: JSON output when piped, stable error identifiers and exit codes, and nothing that hangs waiting for input. For a quick tour, see the [CLI product page](https://tracewayapp.com/product/cli).## Installation@@ -12,7 +12,7 @@ import { Callout } from "nextra/components";curl -fsSL https://cli.tracewayapp.com/install.sh | sh```-The installer detects your OS and architecture, downloads the latest CLI release from GitHub, verifies its sha256 checksum, and installs `traceway` to `/usr/local/bin` (when writable) or `~/.local/bin`, without sudo. Two environment variables tweak it: `TRACEWAY_CLI_VERSION` pins a version (e.g. `1.9.3`) and `TRACEWAY_INSTALL_DIR` overrides the target directory.+Add `-s -- --write` to install `traceway-write` instead (see [Agent Write Access](/learn/agent-write-access)). The installer detects your OS and architecture, downloads the latest CLI release from GitHub, verifies its sha256 checksum, and installs `traceway` to `/usr/local/bin` (when writable) or `~/.local/bin`, without sudo. Two environment variables tweak it: `TRACEWAY_CLI_VERSION` pins a version (e.g. `1.9.3`) and `TRACEWAY_INSTALL_DIR` overrides the target directory.### Prebuilt binaries@@ -66,8 +66,6 @@ The default `traceway login` runs a browser device flow with an auto-refreshing| `traceway exceptions list` | Recent grouped exceptions || `traceway exceptions show <hash>` | A single exception group + occurrences || `traceway exceptions occurrence <id> --recorded-at <t>` | A single occurrence by id (+ `sessionId` and recording) |-| `traceway exceptions archive <hash>...` | Archive one or more groups (mutating; needs `--yes` non-interactively) |-| `traceway exceptions unarchive <hash>...` | Unarchive (mutating; needs `--yes` non-interactively) || `traceway logs query` | Query logs with severity / service / search filters || `traceway endpoints list` | Per-endpoint p50/p95/p99 stats || `traceway endpoints show <id> --recorded-at <t>` | A single request (transaction) by id: spans + linked errors |@@ -76,6 +74,10 @@ The default `traceway login` runs a browser device flow with an auto-refreshing| `traceway sessions show <id> --started-at <t>` | A single session by id + the exceptions that fired in it || `traceway traces show <id> --recorded-at <t>` | A distributed trace: every service node sharing the id || `traceway metrics query` | Time-series metric queries |+| `traceway pages {list,show}` | On-call pages (`--status active\|open\|acknowledged\|resolved`) |+| `traceway alerts list` | Alert rules with their enabled and snoozed state |+| `traceway monitors {list,show}` | Uptime monitors and their incidents |+| `traceway post-mortems {list,show}` | Post-mortem documents (`--search`, `--tag`) || `traceway mcp` | Serve the [MCP server](/learn/mcp) over stdio |Run `traceway <command> --help` for full per-command flags.@@ -132,9 +134,15 @@ The `error` field is a stable snake_case identifier that scripts and LLMs can br| 6 | Rate limited || 7 | Server (5xx) |-## Mutations require confirmation+## Write commands-`exceptions archive` and `exceptions unarchive` are the only commands that change server state, and they require explicit consent:+`traceway` changes nothing. Its write commands (`exceptions archive`, `pages ack`, `alerts snooze` and the rest) exist only in `traceway-write`, a separate binary with its own login. Running one of them in `traceway` fails with `write_required` (exit 2). Install the write CLI with:++```bash+curl -fsSL https://cli.tracewayapp.com/install.sh | sh -s -- --write+```++Every `traceway-write` write requires explicit consent:- Pass `--yes` to skip the prompt.- Or set `TRACEWAY_ASSUME_YES=1` in the environment.diff --git a/docs/pages/learn/mcp.mdx b/docs/pages/learn/mcp.mdxindex f6f87f66..7c8b0571 100644--- a/docs/pages/learn/mcp.mdx+++ b/docs/pages/learn/mcp.mdx@@ -4,6 +4,8 @@ Traceway speaks [MCP](https://modelcontextprotocol.io) in two ways: the `tracewaThe server is a thin layer over the same API client the CLI uses, and it ships the same operator playbooks the Traceway skill contains, exposed as MCP resources and prompts. One binary, one login, three surfaces.+Both servers described here are read only. A separate write server (`/mcp/write`, or `traceway-write mcp`) adds tools that archive issues, acknowledge pages, snooze alerts and edit post-mortems, behind write credentials and an organization opt-in. See [Agent Write Access](/learn/agent-write-access).+## Remote server (zero install)Point any streamable-HTTP MCP client at your instance and it handles login itself:@@ -17,6 +19,8 @@ On first use the client discovers the OAuth metadata, registers itself (RFC 7591Non-OAuth clients (or CI) can instead send a personal access token directly: `Authorization: Bearer twp_...` on every request.+`/mcp` never lists a write tool, whatever the credential. Agent credentials (personal access tokens and OAuth tokens) only reach the API routes the tools need; the rest of the dashboard API refuses them.+Two things differ from the local server: there is no default project (pass `project_id`, or let the model call `list_projects` first), and an unauthenticated request gets a `401` with a `WWW-Authenticate` challenge pointing at `/.well-known/oauth-protected-resource/mcp`, which is how spec-compliant clients find the login flow. The discovery documents and the `/mcp` endpoint answer CORS preflights, so browser-based clients (like the MCP Inspector auth debugger) can reach them too.## Local server (CLI session)@@ -62,7 +66,7 @@ Skip the CLI session entirely with environment variables:## Tools-Every tool wraps one API call and declares an output schema, so results come back as validated `structuredContent` alongside the JSON text. All read tools are annotated read-only; only the two archive tools mutate anything, and their descriptions instruct agents to use them solely on explicit request.+Every tool wraps one API call and declares an output schema, so results come back as validated `structuredContent` alongside the JSON text. Every tool on this server is annotated read-only.| Tool | Purpose ||---|---|@@ -77,7 +81,12 @@ Every tool wraps one API call and declares an output schema, so results come bac| `get_slow_endpoint_config` | Operator-accepted latency baseline || `query_metrics` | Time-bucketed metric series || `get_task` / `get_ai_trace` / `get_session` / `get_trace` | By-id detail lookups |-| `archive_exceptions` / `unarchive_exceptions` | The only mutating tools |+| `list_pages` / `get_page` | On-call pages and their delivery log |+| `list_notification_rules` | Alert rules, enabled and snoozed state |+| `list_checks` / `get_check` | Monitors and their incidents |+| `list_post_mortems` / `get_post_mortem` | Post-mortem documents |++The write server adds `archive_exceptions`, `unarchive_exceptions`, `acknowledge_page`, `resolve_page`, `set_notification_rule_enabled`, `snooze_notification_rule`, `run_check`, `create_post_mortem`, `update_post_mortem` and `set_slow_endpoint`.Project selection is per call: every project-scoped tool accepts a `project_id` parameter and falls back to the CLI's current project.@@ -88,10 +97,28 @@ The by-id detail tools require the record's timestamp (`recorded_at`, or `starteThe debugging knowledge lives in the server, not in the client:- **Prompts**: `debug_issue`, `investigate_performance`, `whats_broken`, and `resolve_notification` render the full investigation playbooks with your argument inlined.-- **Resources**: `traceway://knowledge/*` documents cover the debug flow, the performance bottleneck checklist, dashboard URL resolution, timestamp recovery, notification handling, and a CLI-to-tool map.+- **Resources**: `traceway://knowledge/*` documents cover the debug flow, the performance bottleneck checklist, dashboard URL resolution, timestamp recovery, notification handling, the product guide, and a CLI-to-tool map. The write server adds the write playbook (`traceway://knowledge/operations`).++These are the same documents the Traceway Claude Code skills are generated from, so the skills and the MCP server never disagree.-These are the same documents the Traceway Claude Code skill is generated from, so the CLI skill and the MCP server never disagree.+### The product guide++`traceway://knowledge/learn` is a guide to every part of Traceway, with one resource per area:++| Resource | Covers |+|---|---|+| `learn/issues` | Exception grouping, the issue and occurrence pages, archiving and regressions |+| `learn/endpoints-and-tasks` | Percentiles, the impact score, Apdex, expected-performance marks, background tasks |+| `learn/traces-and-logs` | The span explorer, whole-trace waterfalls, distributed traces, log search |+| `learn/metrics-and-dashboards` | Metric aggregations, dashboards, widgets, templates |+| `learn/sessions-and-ai` | Session replay, AI traces and conversations, profiles |+| `learn/monitors` | Monitors, incidents, status pages, post-mortems |+| `learn/alerts` | Every alert rule type, channels, cooldowns, snoozing |+| `learn/on-call` | Teams, schedules, overrides, escalation policies, pages, contact methods |+| `learn/organization` | Projects, roles, organization views, settings, agent access |++The same guide ships as the `traceway-learn` skill, installed with the other skills (`npx skills add tracewayapp/traceway --all`, or the `tw` Claude Code plugin). Ask an agent how paging escalates, why an endpoint is Critical, or how to put a status page on your own domain, and it answers from the guide.## Errors-Tool errors carry the CLI's stable error codes in the text, formatted as `error=<code>: <message>. Hint: <hint>`, so agents can branch on `token_expired`, `not_found`, `rate_limited`, `no_project`, and friends.+Tool errors carry the CLI's stable error codes in the text, formatted as `error=<code>: <message>. Hint: <hint>`, so agents can branch on `token_expired`, `not_found`, `rate_limited`, `no_project`, and friends. A `forbidden` error carries the server's reason, such as a read-only credential or agent writes being turned off.diff --git a/frontend/src/lib/state/organization.svelte.ts b/frontend/src/lib/state/organization.svelte.tsindex 104c1ba4..d83c065d 100644--- a/frontend/src/lib/state/organization.svelte.ts+++ b/frontend/src/lib/state/organization.svelte.ts@@ -33,6 +33,29 @@ export interface OrganizationSettings {members: OrganizationMember[];invitations: Invitation[];userRole: string;+ agentWriteEnabled: boolean;+}++export interface AgentWriteEvent {+ id: string;+ organizationId: number;+ projectId: string;+ projectName: string;+ userId: number;+ userEmail: string;+ credentialKind: 'pat' | 'oauth';+ credentialRef: string;+ credentialName: string;+ method: string;+ route: string;+ path: string;+ statusCode: number;+ createdAt: string;+}++export interface AgentActivityResponse {+ data: AgentWriteEvent[];+ pagination: { page: number; pageSize: number; total: number; totalPages: number };}export interface MemberProjectRole {@@ -54,6 +77,7 @@ class OrganizationState {loading = $state(false);error = $state<string | null>(null);userRole = $state<string | null>(null);+ agentWriteEnabled = $state(false);isOwner = $derived(this.userRole === 'owner');isAdmin = $derived(this.userRole === 'admin');@@ -79,6 +103,7 @@ class OrganizationState {this.members = response.members;this.invitations = response.invitations;this.userRole = response.userRole;+ this.agentWriteEnabled = response.agentWriteEnabled ?? false;} catch (e: unknown) {if (seq !== this.loadSeq) return;this.error = e instanceof Error ? e.message : 'Failed to load settings';@@ -140,11 +165,27 @@ class OrganizationState {}}+ async setAgentWriteEnabled(organizationId: number, enabled: boolean) {+ await api.put(`/organizations/${organizationId}/agent-access`, { agentWriteEnabled: enabled });+ this.agentWriteEnabled = enabled;+ }++ async loadAgentActivity(+ organizationId: number,+ page: number,+ pageSize: number+ ): Promise<AgentActivityResponse> {+ return (await api.get(+ `/organizations/${organizationId}/agent-activity?page=${page}&pageSize=${pageSize}`+ )) as AgentActivityResponse;+ }+clear() {this.currentOrganization = null;this.members = [];this.invitations = [];this.userRole = null;+ this.agentWriteEnabled = false;this.error = null;}}diff --git a/frontend/src/lib/state/personal-access-tokens.svelte.ts b/frontend/src/lib/state/personal-access-tokens.svelte.tsindex b265450a..b8c9f1e6 100644--- a/frontend/src/lib/state/personal-access-tokens.svelte.ts+++ b/frontend/src/lib/state/personal-access-tokens.svelte.ts@@ -1,9 +1,12 @@import { api } from '$lib/api';+export type TokenScope = 'traceway:read' | 'traceway:write';+export interface PersonalAccessToken {id: string;prefix: string;name: string;+ scope: TokenScope;lastUsedAt: string | null;expiresAt: string | null;createdAt: string;@@ -14,6 +17,7 @@ export interface CreatedToken {name: string;prefix: string;token: string;+ scope: TokenScope;createdAt: string;expiresAt: string | null;}@@ -35,10 +39,15 @@ class PersonalAccessTokensState {}}- async create(name: string, expiresInDays: number | null): Promise<CreatedToken> {+ async create(+ name: string,+ expiresInDays: number | null,+ scope: TokenScope+ ): Promise<CreatedToken> {const res = (await api.post('/personal-access-tokens', {name,- expiresInDays+ expiresInDays,+ scope})) as CreatedToken;await this.load();return res;diff --git a/frontend/src/lib/utils/ai-setup.ts b/frontend/src/lib/utils/ai-setup.tsindex 22ad8138..eacdff25 100644--- a/frontend/src/lib/utils/ai-setup.ts+++ b/frontend/src/lib/utils/ai-setup.ts@@ -1,4 +1,4 @@-export const SKILL_INSTALL_COMMAND = 'npx skills add tracewayapp/traceway';+export const SKILL_INSTALL_COMMAND = 'npx skills add tracewayapp/traceway --all';export type PromptPart = {text: string;diff --git a/frontend/src/routes/account/create-token-dialog.svelte b/frontend/src/routes/account/create-token-dialog.svelteindex d47e8009..d22c3cc3 100644--- a/frontend/src/routes/account/create-token-dialog.svelte+++ b/frontend/src/routes/account/create-token-dialog.svelte@@ -9,29 +9,50 @@import { ErrorAlert } from '$lib/components/ui/error-alert';import { toast } from 'svelte-sonner';import CopyableInline from '$lib/components/setup/copyable-inline.svelte';- import { personalAccessTokensState } from '$lib/state/personal-access-tokens.svelte';+ import { WarningCallout } from '$lib/components/ui/warning-callout';+ import {+ personalAccessTokensState,+ type TokenScope+ } from '$lib/state/personal-access-tokens.svelte';let { open = $bindable() }: { open: boolean } = $props();let name = $state('');let expiry = $state('30');+ let scope = $state<TokenScope>('traceway:read');let loading = $state(false);let error = $state('');let createdToken = $state<string | null>(null);- const expiryOptions = [+ const scopeOptions: { value: TokenScope; label: string }[] = [+ { value: 'traceway:read', label: 'Read only' },+ { value: 'traceway:write', label: 'Read and write' }+ ];++ const expiryOptions = $derived([+ { value: '7', label: '7 days' },{ value: '30', label: '30 days' },{ value: '60', label: '60 days' },{ value: '90', label: '90 days' },- { value: '0', label: 'No expiration' }- ];+ ...(scope === 'traceway:write' ? [] : [{ value: '0', label: 'No expiration' }])+ ]);++ $effect(() => {+ if (scope === 'traceway:write' && expiry === '0') {+ expiry = '30';+ }+ });async function handleCreate() {loading = true;error = '';try {const days = parseInt(expiry, 10);- const res = await personalAccessTokensState.create(name.trim(), days > 0 ? days : null);+ const res = await personalAccessTokensState.create(+ name.trim(),+ days > 0 ? days : null,+ scope+ );createdToken = res.token;toast.success('Successfully created the Token', { position: 'top-center' });} catch (e: unknown) {@@ -45,6 +66,7 @@if (!isOpen) {name = '';expiry = '30';+ scope = 'traceway:read';error = '';createdToken = null;}@@ -79,7 +101,7 @@<AlertDialog.Header><AlertDialog.Title>New Token</AlertDialog.Title><AlertDialog.Description>- Use this token to authenticate the Traceway CLI or scripts.+ Use this token to authenticate the Traceway CLI, an MCP client or scripts.</AlertDialog.Description></AlertDialog.Header><form@@ -94,6 +116,26 @@<Label for="token-name">Name</Label><Input id="token-name" bind:value={name} placeholder="e.g. laptop CLI" required /></div>+ <div class="space-y-2">+ <Label for="token-scope">Access</Label>+ <Select.Root type="single" bind:value={scope}>+ <Select.Trigger id="token-scope" class="w-full">+ {scopeOptions.find((o) => o.value === scope)?.label}+ </Select.Trigger>+ <Select.Content>+ {#each scopeOptions as option (option.value)}+ <Select.Item value={option.value}>{option.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ {#if scope === 'traceway:write'}+ <WarningCallout title="Write tokens change shared data">+ An agent holding this token can archive issues, resolve pages, snooze alerts and edit+ post-mortems as you. It only works in organizations where an admin turned on agent+ writes, and it must expire within 90 days.+ </WarningCallout>+ {/if}<div class="space-y-2"><Label for="token-expiry">Expiration</Label><Select.Root type="single" bind:value={expiry}>diff --git a/frontend/src/routes/account/personal-access-tokens.svelte b/frontend/src/routes/account/personal-access-tokens.svelteindex c5255b5f..76f0069f 100644--- a/frontend/src/routes/account/personal-access-tokens.svelte+++ b/frontend/src/routes/account/personal-access-tokens.svelte@@ -58,7 +58,8 @@</script><InfoCallout>- Authenticate the Traceway CLI or scripts without a browser. Treat tokens like passwords.+ Authenticate the Traceway CLI, MCP clients or scripts without a browser. Tokens are read only+ unless you create them with write access. Treat tokens like passwords.</InfoCallout>{#if personalAccessTokensState.loading}@@ -81,6 +82,7 @@<Table.Row class="hover:bg-transparent"><Table.Head>Name</Table.Head><Table.Head>Prefix</Table.Head>+ <Table.Head>Access</Table.Head><Table.Head>Created</Table.Head><Table.Head>Last used</Table.Head><Table.Head>Expires</Table.Head>@@ -94,6 +96,13 @@<Table.Cell><code class="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{token.prefix}…</code></Table.Cell>+ <Table.Cell>+ {#if token.scope === 'traceway:write'}+ <StatusPill tone="warning" label="Read and write" />+ {:else}+ <Badge variant="outline">Read only</Badge>+ {/if}+ </Table.Cell><Table.Cell>{formatDate(token.createdAt)}</Table.Cell><Table.Cell>{#if token.lastUsedAt}diff --git a/frontend/src/routes/device/+page.svelte b/frontend/src/routes/device/+page.svelteindex a96eaded..c88a16b0 100644--- a/frontend/src/routes/device/+page.svelte+++ b/frontend/src/routes/device/+page.svelte@@ -34,7 +34,7 @@let status = $state<Status>('loading');let error = $state('');- let info = $state<{ userCode: string; clientName: string } | null>(null);+ let info = $state<{ userCode: string; clientName: string; write: boolean } | null>(null);let manualCode = $state('');const userCode = $derived(page.url.searchParams.get('user_code'));@@ -88,7 +88,11 @@status = 'expired';return;}- info = { userCode: data.user_code, clientName: data.clientName || 'a device' };+ info = {+ userCode: data.user_code,+ clientName: data.clientName || 'a device',+ write: data.scope === 'traceway:write'+ };status = 'confirm';} catch {status = 'error';@@ -190,8 +194,15 @@{:else if status === 'confirm' && info}<div class="space-y-4"><p class="text-center text-muted-foreground">- <strong>{info.clientName}</strong> is requesting access to your Traceway account.+ <strong>{info.clientName}</strong> is requesting+ {info.write ? 'read and write' : 'read-only'} access to your Traceway account.</p>+ {#if info.write}+ <WarningCallout title="This login can change data">+ It can archive issues, acknowledge and resolve pages, snooze alerts and edit+ post-mortems as you, in organizations where an admin turned on agent writes.+ </WarningCallout>+ {/if}<div class="py-4 text-center font-mono text-4xl font-semibold tracking-[0.3em]">{info.userCode}</div>diff --git a/frontend/src/routes/oauth/authorize/+page.svelte b/frontend/src/routes/oauth/authorize/+page.svelteindex 1db452a2..7f37c931 100644--- a/frontend/src/routes/oauth/authorize/+page.svelte+++ b/frontend/src/routes/oauth/authorize/+page.svelte@@ -12,6 +12,7 @@} from '$lib/components/ui/card';import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { WarningCallout } from '$lib/components/ui/warning-callout';import { CircleAlert, ShieldCheck } from '@lucide/svelte';import { authState } from '$lib/state/auth.svelte';import { themeState } from '$lib/state/theme.svelte';@@ -36,9 +37,12 @@state: page.url.searchParams.get('state') ?? '',codeChallenge: page.url.searchParams.get('code_challenge'),codeChallengeMethod: page.url.searchParams.get('code_challenge_method'),- resource: page.url.searchParams.get('resource') ?? ''+ resource: page.url.searchParams.get('resource') ?? '',+ scope: page.url.searchParams.get('scope') ?? ''});+ const wantsWrite = $derived(params.scope.split(/\s+/).includes('traceway:write'));+const redirectHost = $derived.by(() => {try {return new URL(params.redirectUri ?? '').host || params.redirectUri;@@ -96,7 +100,8 @@state: params.state,code_challenge: params.codeChallenge,code_challenge_method: params.codeChallengeMethod,- resource: params.resource+ resource: params.resource,+ scope: params.scope}: { client_id: params.clientId, redirect_uri: params.redirectUri, state: params.state };const res = await fetch(`/api/oauth/${approve ? 'approve' : 'deny'}`, {@@ -177,10 +182,19 @@<p class="text-center text-muted-foreground"><strong>{clientName}</strong> is requesting access to your Traceway account.</p>+ {#if wantsWrite}+ <WarningCallout title="Read and write access">+ It will be able to read your projects' telemetry and also archive issues, acknowledge+ and resolve pages, snooze alerts and edit post-mortems as you, in organizations where+ an admin turned on agent writes.+ </WarningCallout>+ {/if}<p class="text-center text-sm text-muted-foreground">- It will be able to read your projects' telemetry and act with your permissions. The- application identified itself with this name; only approve if you just started- connecting it, and it will send you back to <strong>{redirectHost}</strong>.+ {wantsWrite+ ? 'Every change it makes is recorded in the organization activity log.'+ : "It will be able to read your projects' telemetry but not change anything."} The application+ identified itself with this name; only approve if you just started connecting it, and it will+ send you back to <strong>{redirectHost}</strong>.</p><div class="flex gap-2"><Button class="flex-1" onclick={() => resolve(true)}>diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelteindex dd1816fb..9ebd29e8 100644--- a/frontend/src/routes/settings/+page.svelte+++ b/frontend/src/routes/settings/+page.svelte@@ -8,6 +8,7 @@import OrgSwitcher from '$lib/components/traceway/org-switcher.svelte';import OrganizationTab from './organization-tab.svelte';import UsersTab from './users-tab.svelte';+ import AgentAccessTab from './agent-access-tab.svelte';import type { Component } from 'svelte';import { LoadingCircle } from '$lib/components/ui/loading-circle';@@ -100,6 +101,7 @@<div class="space-y-4"><OrganizationTab /><UsersTab organizationId={currentOrganizationId!} />+ <AgentAccessTab organizationId={currentOrganizationId!} />{#if BillingTab}<BillingTab organizationId={currentOrganizationId!} />{/if}diff --git a/frontend/src/routes/settings/agent-access-tab.svelte b/frontend/src/routes/settings/agent-access-tab.sveltenew file mode 100644index 00000000..9924184f--- /dev/null+++ b/frontend/src/routes/settings/agent-access-tab.svelte@@ -0,0 +1,195 @@+<script lang="ts">+ import { untrack } from 'svelte';+ import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle+ } from '$lib/components/ui/card';+ import { Switch } from '$lib/components/ui/switch';+ import { Label } from '$lib/components/ui/label';+ import * as Table from '$lib/components/ui/table';+ import { Badge } from '$lib/components/ui/badge';+ import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { PaginationFooter } from '$lib/components/ui/pagination-footer';+ import { WarningCallout } from '$lib/components/ui/warning-callout';+ import TableContainer from '$lib/components/traceway/table-container.svelte';+ import EmptyState from '$lib/components/traceway/empty-state.svelte';+ import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';+ import { toast } from 'svelte-sonner';+ import { formatDateTime } from '$lib/utils/formatters';+ import { organizationState, type AgentWriteEvent } from '$lib/state/organization.svelte';++ let { organizationId }: { organizationId: number } = $props();++ let saving = $state(false);+ // Overridden while a change is saving, and set back if it fails, so the+ // switch never shows a state the server did not accept.+ let writeEnabled = $derived(organizationState.agentWriteEnabled);+ let events = $state<AgentWriteEvent[]>([]);+ let loading = $state(true);+ let error = $state('');+ let page = $state(1);+ let pageSize = $state(20);+ let total = $state(0);+ let totalPages = $state(0);++ async function loadActivity() {+ loading = true;+ error = '';+ try {+ const res = await organizationState.loadAgentActivity(organizationId, page, pageSize);+ events = res.data;+ total = res.pagination.total;+ totalPages = res.pagination.totalPages;+ } catch (e: unknown) {+ error = e instanceof Error ? e.message : 'Failed to load agent activity';+ } finally {+ loading = false;+ }+ }++ // Only a change of organization reloads from page 1; loadActivity reads+ // page and pageSize, which must not become dependencies of this effect.+ $effect(() => {+ if (organizationId) {+ untrack(() => {+ page = 1;+ loadActivity();+ });+ }+ });++ async function toggle(enabled: boolean) {+ saving = true;+ try {+ await organizationState.setAgentWriteEnabled(organizationId, enabled);+ toast.success(enabled ? 'Agent write access turned on' : 'Agent write access turned off', {+ position: 'top-center'+ });+ } catch (e: unknown) {+ writeEnabled = organizationState.agentWriteEnabled;+ toast.error(e instanceof Error ? e.message : 'Failed to update agent access');+ } finally {+ saving = false;+ }+ }++ function describeRoute(event: AgentWriteEvent): string {+ return `${event.method} ${event.path.replace(/^\/api/, '')}`;+ }++ function credentialLabel(event: AgentWriteEvent): string {+ if (event.credentialKind === 'pat') {+ return event.credentialName ? `Token "${event.credentialName}"` : 'Personal access token';+ }+ if (event.credentialRef === 'traceway-cli-write') return 'Write CLI';+ return event.credentialName ? `MCP client "${event.credentialName}"` : 'MCP client';+ }+</script>++<Card>+ <CardHeader>+ <CardTitle>Agent Access</CardTitle>+ <CardDescription>+ Control whether write tokens, the traceway-write CLI and the write MCP server can change data+ in this organization. Read access is always available to members.+ </CardDescription>+ </CardHeader>+ <CardContent class="space-y-6">+ <div class="flex items-start justify-between gap-4">+ <div class="space-y-1">+ <Label for="agent-write-toggle">Allow agent writes</Label>+ <p class="text-sm text-muted-foreground">+ Agents can archive issues, acknowledge and resolve pages, snooze or toggle alert rules,+ run monitors, edit post-mortems and mark slow endpoints. They never get more access than+ the person who created the token.+ </p>+ </div>+ <Switch+ id="agent-write-toggle"+ checked={writeEnabled}+ disabled={saving}+ onCheckedChange={(checked) => {+ writeEnabled = checked;+ toggle(checked);+ }}+ />+ </div>++ {#if organizationState.agentWriteEnabled}+ <WarningCallout title="Agent writes are on">+ Anyone in this organization with a write token can let an AI agent change shared data. Every+ write is listed below.+ </WarningCallout>+ {/if}++ <div class="space-y-3">+ <h3 class="text-sm font-medium">Agent activity</h3>+ {#if loading}+ <div class="flex justify-center py-8"><LoadingCircle size="lg" /></div>+ {:else if error}+ <ErrorRetryBox message={error} onRetry={loadActivity} />+ {:else if events.length === 0}+ <EmptyState message="No agent writes yet." />+ {:else}+ <TableContainer>+ <Table.Root>+ <Table.Header>+ <Table.Row class="hover:bg-transparent">+ <Table.Head>When</Table.Head>+ <Table.Head>Who</Table.Head>+ <Table.Head>Credential</Table.Head>+ <Table.Head>Project</Table.Head>+ <Table.Head>Action</Table.Head>+ <Table.Head>Result</Table.Head>+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each events as event (event.id)}+ <Table.Row>+ <Table.Cell class="whitespace-nowrap"+ >{formatDateTime(event.createdAt, { format: 'short' })}</Table.Cell+ >+ <Table.Cell>{event.userEmail}</Table.Cell>+ <Table.Cell>{credentialLabel(event)}</Table.Cell>+ <Table.Cell>{event.projectName || event.projectId}</Table.Cell>+ <Table.Cell>+ <code class="rounded bg-muted px-1.5 py-0.5 font-mono text-xs"+ >{describeRoute(event)}</code+ >+ </Table.Cell>+ <Table.Cell>+ {#if event.statusCode < 400}+ <Badge variant="outline">{event.statusCode}</Badge>+ {:else}+ <Badge variant="destructive">{event.statusCode}</Badge>+ {/if}+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </TableContainer>+ <PaginationFooter+ currentPage={page}+ {totalPages}+ {pageSize}+ totalItems={total}+ onPageChange={(p) => {+ page = p;+ loadActivity();+ }}+ onPageSizeChange={(size) => {+ pageSize = size;+ page = 1;+ loadActivity();+ }}+ {loading}+ itemLabel="write"+ />+ {/if}+ </div>+ </CardContent>+</Card>diff --git a/plugins/tw-write/.claude-plugin/plugin.json b/plugins/tw-write/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..eb920a50--- /dev/null+++ b/plugins/tw-write/.claude-plugin/plugin.json@@ -0,0 +1,11 @@+{+ "name": "tw-write",+ "description": "Traceway write skill: /tw-write:traceway-write lets an agent archive issues, acknowledge pages, snooze alerts, run monitors and write post-mortems through the traceway-write CLI. Installed separately from the read-only tw plugin.",+ "version": "1.0.0",+ "author": {+ "name": "Traceway"+ },+ "homepage": "https://tracewayapp.com",+ "repository": "https://github.com/tracewayapp/traceway",+ "license": "MIT"+}diff --git a/plugins/tw-write/skills/traceway-write/SKILL.md b/plugins/tw-write/skills/traceway-write/SKILL.mdnew file mode 100644index 00000000..91e47a59--- /dev/null+++ b/plugins/tw-write/skills/traceway-write/SKILL.md@@ -0,0 +1,192 @@+---+name: traceway-write+description: 'Operate a Traceway instance with write access. Use when the user wants an agent to change something in Traceway: archive or unarchive issues, acknowledge or resolve on-call pages, snooze, enable or disable alert rules, run a monitor now, create or edit a post-mortem, or mark an endpoint as expected-slow. Requires the separate traceway-write CLI or the /mcp/write server, a write credential, and an organization admin who turned on agent writes.'+---+<!-- GENERATED FILE: assembled from cli/pkg/mcpserver/knowledge by cli/tools/skillgen. Edit the chunks there and run just gen-skills in cli/. -->++# Traceway with write access++This skill drives the `traceway-write` CLI (or the write MCP server) to make the routine changes an on-call engineer makes: archive issues, acknowledge and resolve pages, snooze or toggle alert rules, run monitors, write post-mortems and mark slow endpoints.++To explain how a part of Traceway works before or after a change (what acknowledging a page does to escalation, how a snooze differs from disabling a rule, how a monitor opens an incident), use the `traceway-learn` skill. It is the full product guide. Over MCP the same guide is the `traceway://knowledge/learn` resources.++For pure investigation (debugging an issue, latency analysis), the read-only `traceway` skill has the deeper playbooks. Its commands work the same way here: every read command of `traceway` also exists in `traceway-write`.++> If a `traceway-write` MCP server is connected (stdio `traceway-write mcp`, or `https://<instance>/mcp/write`), prefer its tools over shelling out. Its resources carry this skill's knowledge, and its tool names are listed in the table below.++## Setup++### 1. Install the write CLI++`traceway-write` is a separate binary with its own login, so a read-only `traceway` install can never be upgraded to write in place.++```bash+curl -fsSL https://cli.tracewayapp.com/install.sh | sh -s -- --write+traceway-write version+```++Prebuilt archives are on the [releases page](https://github.com/tracewayapp/traceway/releases) under `cli/vX.Y.Z` tags as `traceway-write_<version>_<os>_<arch>.tar.gz`. From source: `cd traceway/cli && go build -tags write -o bin/traceway-write ./cmd/traceway`.++### 2. Log in with write access++Ask the user to run the browser login themselves (in Claude Code: `! traceway-write login --url https://<instance>`). The approval page says the login asks for read and write access.++```bash+traceway-write login --url https://<instance>+```++Headless alternative: the user creates a **Read and write** personal access token (Account > Personal Access Tokens, prefix `tww_`, expires within 90 days) and stores it without echoing it:++```bash+printf '%s' "$TRACEWAY_WRITE_TOKEN" | traceway-write login --url https://<instance> --token-stdin+```++A read token (`twp_`) stored in `traceway-write` still cannot write: the server refuses every write with "This credential is read-only".++### 3. Organization opt-in++An organization owner or admin must turn on **Settings > Agent Access > Allow agent writes**. Until then writes answer 403 "Agent write access is turned off for this organization". Do not try to work around it: tell the user who can turn it on.++### 4. Select a project++```bash+traceway-write projects list+traceway-write projects use <project-id>+```++### MCP instead of the CLI++- Local stdio: `claude mcp add traceway-write -- traceway-write mcp` (uses the `traceway-write login`).+- Remote: add `https://<instance>/mcp/write` as an HTTP MCP server. The client runs OAuth and the consent page asks for read and write access. The plain `/mcp` server never exposes write tools, even to a write token.++## Operating with write access++Write access lets an agent take the routine actions an on-call engineer takes during and after an incident. It is opt-in at three levels, and every level has to agree before a write goes through:++1. **The credential.** Only write credentials can write: a `tww_` personal access token, a `traceway-write login`, or an MCP client connected to the `/mcp/write` server. A `twp_` token, a `traceway login` and the `/mcp` server are read only, whatever the person's role.+2. **The organization.** An admin has to turn on Settings > Agent Access. Until then every agent write is refused with a 403 that says so.+3. **The person.** The write runs with the role of the person who created the credential, under the same rules as the dashboard. A `readonly` member's write token cannot archive issues, change alerts, run monitors or edit post-mortems. Acknowledging and resolving pages needs no write role, so any member's write token can do that.++Every write a write credential makes in the organization, accepted or refused because Agent Access is off, is recorded in the organization's agent activity log with the person, the credential, the project and the result.++### What an agent can change++| Action | CLI (`traceway-write`) | MCP tool | Reversible |+|---|---|---|---|+| Archive or unarchive issues | `exceptions archive <hash>...` / `unarchive` | `archive_exceptions` / `unarchive_exceptions` | Yes |+| Acknowledge a page | `pages ack <id>` | `acknowledge_page` | No, but harmless: it only stops escalation |+| Resolve a page | `pages resolve <id> [--archive-issue]` | `resolve_page` | No |+| Enable or disable an alert rule | `alerts enable <id>` / `alerts disable <id>` | `set_notification_rule_enabled` | Yes |+| Snooze an alert rule | `alerts snooze <id> --minutes N` (0 clears) | `snooze_notification_rule` | Yes, it expires on its own |+| Run a monitor now | `monitors run <id>` | `run_check` | Nothing to undo |+| Write a post-mortem | `post-mortems create` / `update <id>` | `create_post_mortem` / `update_post_mortem` | Edits are kept in the activity log |+| Mark an endpoint expected-slow | `endpoints mark-slow <endpoint> --offset-ms N --reason ...` (0 removes) | `set_slow_endpoint` | Yes |++Everything else (creating rules and channels, editing schedules and policies, status pages and public incident updates, members, tokens, project settings, deleting anything) stays in the dashboard. Those routes refuse agent credentials outright.++### Rules for every write++- **Only on request.** Investigating, debugging, summarizing or "taking a look" never implies a write. The user has to ask for the change.+- **Say it before doing it.** One line naming the action, the record and the new value: "Snoozing rule 12 (Endpoint P95 on GET /api/search) for 60 minutes." The CLI asks for confirmation on a TTY and needs `--yes` otherwise. MCP clients run their own approval step.+- **Prefer the reversible option.** Snooze rather than disable. Acknowledge rather than resolve while the problem is still live. Archive an issue rather than resolving its page with `--archive-issue` if you are unsure the page is done.+- **Report what changed and how to undo it.**+- **Treat a 403 as an answer.** "This credential is read-only" or "Agent write access is turned off" is a policy decision. Do not retry, switch credentials or look for another route. Tell the user what it said and who can change it.++### Playbooks++#### Someone got paged++1. `pages list` (status `active`) to find the page, then `pages show <id>` for the rule, subject and who was notified.+2. Investigate with the read tools. For an issue page, the page carries the exception hash: follow the debug flow.+3. When the user says they are on it: `pages ack <id>`. Escalation stops for everyone.+4. When the cause is fixed and confirmed: `pages resolve <id>`, with `--archive-issue` only if the user wants the issue archived too.++#### An alert is flapping during a known incident++1. `alerts list` to find the rule id and confirm it is the noisy one.+2. `alerts snooze <id> --minutes 60` (or as long as the user asks). The rule is muted and comes back on its own.+3. Tell the user when the snooze ends. Disable a rule only when the user wants it off until someone turns it back on.++#### Confirming a fix++1. `monitors run <id>` for the affected monitor.+2. Wait about one interval, then `monitors show <id>`: the latest run and whether the open incident resolved.+3. For an issue, `exceptions show <hash>` and check that no occurrence is newer than the deploy. Archive it only when the user agrees it is fixed.++#### Writing a post-mortem++1. Gather facts with the read tools: the incident window from `monitors show`, the issues and their first and last occurrences, the pages and who acknowledged them, the slow endpoints and the trace of a failing request.+2. Draft the document in markdown with these sections: Summary, Impact (who and how much, with numbers), Timeline (UTC, from first signal to resolution), Root cause, Resolution, Follow-up actions (each with an owner if known). Only state what the telemetry or the user confirmed, and mark open questions as open.+3. Show the draft to the user. Create it only after they approve: `post-mortems create --title "..." --content-file draft.md --tag <tag> --incident <id>`.+4. Later edits: `post-mortems show <id>` first, then `post-mortems update <id> --content-file revised.md --expected-updated-at <updatedAt from that show>` with the full revised body. If someone edited it in between, the update fails with a conflict: show it again and reapply the change. `--unlink-incident` removes a wrong incident link.++#### An endpoint is slow by design++1. Confirm with the user that the latency is accepted, and get the reason.+2. Check the current p95 with `endpoints list --search "<endpoint>"`.+3. `endpoints mark-slow "<endpoint>" --offset-ms <a bit above p95> --reason "<why>"`. Raw percentiles do not change. Apdex and impact stop penalizing up to the offset.++## Command reference++Every `traceway` read command works in `traceway-write` (`exceptions list|show|occurrence`, `logs query`, `endpoints list|chart|show|slow`, `tasks show`, `ai-traces show`, `sessions show`, `traces show`, `metrics query`, `pages list|show`, `alerts list`, `monitors list|show`, `post-mortems list|show`). The write commands:++| Command | MCP tool | What it changes |+|---|---|---|+| `traceway-write exceptions archive <hash>... [--yes]` | `archive_exceptions` | Hides issues from the default list |+| `traceway-write exceptions unarchive <hash>... [--yes]` | `unarchive_exceptions` | Brings them back |+| `traceway-write pages ack <id>` | `acknowledge_page` | Stops escalation for a page |+| `traceway-write pages resolve <id> [--archive-issue]` | `resolve_page` | Closes a page, optionally archiving its issue |+| `traceway-write alerts enable <id>` / `disable <id>` | `set_notification_rule_enabled` | Turns a rule on or off |+| `traceway-write alerts snooze <id> --minutes N` | `snooze_notification_rule` | Silences a rule for N minutes; 0 clears |+| `traceway-write monitors run <id>` | `run_check` | Queues an immediate monitor run |+| `traceway-write post-mortems create --title T [--content-file F] [--tag X] [--incident N]` | `create_post_mortem` | New post-mortem |+| `traceway-write post-mortems update <id> [--title] [--content-file --expected-updated-at] [--tag] [--incident \| --unlink-incident]` | `update_post_mortem` | Edits only the flags passed. A new body needs the `updatedAt` it was based on |+| `traceway-write endpoints mark-slow <endpoint> --offset-ms N --reason R` | `set_slow_endpoint` | Accepted latency for an endpoint; 0 removes |++Every write command prints what it is about to do and asks for confirmation on a TTY. In scripts and agents pass `--yes` (or set `TRACEWAY_ASSUME_YES=1`) only after the user asked for that exact change. Output, flags, exit codes and error envelopes are the same as the read CLI: JSON when piped, `--fields` to trim, exit code 4 for auth and permission errors.++## Resolving Dashboard URLs++Users paste dashboard URLs (`https://<instance>/<route>`) as references in any flow. Resolve by route family:++| URL path | Identifies | How to fetch it |+|---|---|---|+| `/issues/<hash>` and `/issues/<hash>/events` | Exception group (hash = 16 hex chars) | `traceway exceptions show <hash>` |+| `/issues/<hash>/<occurrenceId>` (UUID) | One occurrence within the group | `traceway exceptions occurrence <occurrenceId> --recorded-at <t>` where `t` is the URL's `?t=` param. Direct and fast; also returns the occurrence's `sessionId` and session recording. No URL? get `recordedAt` from `traceway exceptions show <hash>` occurrences |+| `/endpoints/<endpoint>` | Endpoint group; the segment is the URL-encoded endpoint name (`GET%20%2Fapi%2Fusers%2F%3Aid` is `GET /api/users/:id`) | Decode it, then `traceway endpoints list --search "<decoded name>"` (the group has no id; `endpoints show` is for one request, see the next row) |+| `/endpoints/<endpoint>/<endpointId>` | One request (transaction) of that endpoint | `traceway endpoints show <endpointId> --recorded-at <t>` (`t` = the URL's `?t=` param). Returns the request, its span waterfall, and any linked exception/messages |+| `/tasks/<task>` | Background task group | No CLI for the group; for one run use the next row |+| `/tasks/<task>/<taskId>` | Single task run | `traceway tasks show <taskId> --recorded-at <t>` (`t` = the URL's `?t=` param) |+| `/sessions/<sessionId>` | Session (the exceptions that fired during it; replay stays dashboard-only) | `traceway sessions show <sessionId> --started-at <t>`. The URL has no `?t=`; use the session's start, the URL's `from=`, or a linked occurrence's `recordedAt` (it falls inside the window). Occurrences reference sessions via their `sessionId` |+| `/ai-traces/<traceName>` | AI trace group | No CLI for the group; for one trace use the next row |+| `/ai-traces/<traceName>/<traceId>` | Single AI trace | `traceway ai-traces show <aiTraceId> --recorded-at <t>` (the UUID in the URL, not a 32 hex trace id) (`t` = the URL's `?t=` param); returns token/cost stats + the conversation |+| `/logs` | Logs page (its filters are not stored in the URL) | `traceway logs query` with flags taken from the user's description |+| `/issues`, `/endpoints`, `/metrics`, `/` | List and dashboard pages | The matching `list` / `query` command |++**Time window**: most dashboard URLs carry `?preset=<p>` or `?from=<iso>&to=<iso>` (sticky across pages); honor them instead of the default window.++- `preset` values `5m 30m 60m 3h 6h 12h 24h 3d 7d` map directly to `--since`; the CLI has no month unit, so map `1M` to `--since 30d` and `3M` to `--since 90d`.+- `from`/`to` are ISO timestamps; pass via `--from`/`--to`, appending `Z` (or the correct offset) when missing, since the CLI requires RFC3339.+- No time params means the page was on its default; pick `--since` per the ground rules.++`preset`/`from`/`to` set the *window* for list/group views. Detail URLs additionally carry **`?t=<iso>`**, the single record's timestamp, URL-encoded. That `t` value is exactly what the by-id commands need as `--recorded-at` (or `--started-at` for sessions). See "Fast by-id lookups" next.++## Fast by-id lookups (always pass the timestamp)++The by-id detail commands (`exceptions occurrence`, `endpoints show`, `tasks show`, `ai-traces show`, `sessions show`, `traces show`) **require** the record's timestamp (`--recorded-at`, or `--started-at` for sessions). Telemetry tables are partitioned by day: with the timestamp the lookup is bounded to a small window and ClickHouse prunes to a few partitions; without it the server scans every partition (slow cold load). The flag is mandatory for exactly this reason, so never omit it. It can be approximate (within ±24h), and you can recover or estimate it when it isn't handed to you; see "When you don't have the timestamp" below.++Where the timestamp comes from, in order of preference:++1. **A dashboard URL**: the `?t=<iso>` param is the record's `recordedAt`; URL-decode it and pass it verbatim. (Sessions have no `t`; use the session start, `from=`, or a linked occurrence's `recordedAt`.)+2. **A list/group you already fetched**: every `exceptions show` occurrence carries `recordedAt`. Capture the id and its `recordedAt` together, then drill in.+3. **A notification**: see below.++Query order when you hold an id: resolve its `recordedAt` first (URL, group, or notification), then call the by-id command with it.++### When you don't have the timestamp++The flag is required, so you must supply *something*, but it can be approximate. The lookup window is **±24h** around what you pass (**±48h** for `traces show`), and if the record isn't in that window the server falls back to an unbounded scan. So a timestamp within a day of the truth stays fast; a wrong guess still returns the right record, just slower. Resolve it in this order:++1. **Recover it from an API.** For an occurrence whose hash you know (e.g. `/issues/<hash>/<occurrenceId>` pasted without `?t=`), run `traceway exceptions show <hash>` and read that occurrence's `recordedAt`. The hash endpoint needs no timestamp. A group's `firstSeen`/`lastSeen` from `exceptions list` bound when its occurrences happened (`lastSeen` ≈ the most recent one).+2. **Estimate from context.** A notification's send time, the issue's `firstSeen`/`lastSeen`, or the URL's `preset`/`from` window all put you inside ±24h. That is good enough for a fast lookup.+3. **Ask the user.** If nothing pins it down (e.g. a bare occurrence/endpoint id with no hash, no time, and no list to recover from), ask roughly when it happened ("around when did this fire? within a day is enough") and pass that. Don't invent a placeholder like "now" when the issue is old; that defeats the pruning and can miss the ±24h window entirely.diff --git a/skills/traceway-learn/SKILL.md b/skills/traceway-learn/SKILL.mdnew file mode 100644index 00000000..74ecf663--- /dev/null+++ b/skills/traceway-learn/SKILL.md@@ -0,0 +1,83 @@+---+name: traceway-learn+description: 'The full guide to Traceway, the observability platform. Explains every part of the product and how it is meant to be used: issues and exception grouping, endpoints and the impact score, tasks, spans and traces, logs, metrics and dashboards, sessions, AI traces, profiles, monitors, incidents, status pages, post-mortems, alert rules and channels, on-call teams, schedules, overrides, escalation policies and pages, contact methods, roles, organization views, settings and agent access. Use when the user asks how a Traceway page or feature works, where to find something, what a term means, or how to set up a workflow such as paging or a status page.'+---+<!-- GENERATED FILE: assembled from cli/pkg/mcpserver/knowledge/learn by cli/tools/skillgen. Edit the chunks there and run just gen-skills in cli/. -->++# Learn Traceway++Traceway is an observability platform. Applications send telemetry: OpenTelemetry over OTLP/HTTP from backends, and the Traceway SDKs from browser and mobile apps. Traceway turns it into issues, request and task analytics, traces, logs, metrics and dashboards, session replay, AI cost tracking and profiles. On top of that it runs uptime monitors, public status pages, alerting and on-call paging.++This guide explains every part of the product: what each page shows, the terms it uses, how teams are meant to use it, and how an agent reads or changes it through the `traceway` CLI or the MCP server.++## How to use this guide++- Answer "how does X work", "where do I find X" and "what does X mean" from the topic files below. Read only the one or two the question needs.+- Quote the exact names the dashboard uses (tab names, buttons, rule types), so the user can find them.+- When the user wants live data, switch to the `traceway` skill (or the MCP tools): it holds the debugging and performance playbooks.+- When the user wants something changed, the `traceway-write` skill covers the changes agents are allowed to make. Everything else is done in the dashboard, and the topic files say so.+- When the user wants an application instrumented, use the `traceway-setup` skill.++## Core ideas++- **Organization** owns people, projects, dashboards, on-call and status pages. **Project** is one application, and almost every page is scoped to it. A trace can cross several projects of one organization.+- **Roles**: `owner`, `admin`, `user`, `readonly`, with per-project overrides for `user` and `readonly` members.+- **Time windows**: every telemetry page is bounded by a range kept in the URL (`?preset=24h`, or `?from=&to=`). Presets: 5m, 30m, 60m, 3h, 6h, 12h, 24h, 3d, 7d, 1M, 3M. CLI and MCP reads take `--since` or `--from/--to`.+- **Spans are the primitive.** Endpoints, tasks, AI traces and issues are spans promoted at ingest. One **trace id** links a request to its downstream calls, logs and exceptions.+- **Alert, page, incident** are different things. An **alert** is a rule sending a notification. A **page** is an on-call escalation that keeps going until someone acknowledges it. An **incident** is a period when a monitor was down (or one recorded by hand), with an optional public story on a status page.++## Topics++| Topic | File | MCP resource | Covers |+|---|---|---|---|+| Issues | [issues.md](issues.md) | `traceway://knowledge/learn/issues` | Exceptions, fingerprinting, the issue and occurrence pages, archiving, regressions |+| Endpoints and tasks | [endpoints-and-tasks.md](endpoints-and-tasks.md) | `traceway://knowledge/learn/endpoints-and-tasks` | P50, P95, P99, impact score, Apdex, expected-performance marks, requests, background tasks |+| Spans, traces and logs | [traces-and-logs.md](traces-and-logs.md) | `traceway://knowledge/learn/traces-and-logs` | The span explorer, whole-trace waterfalls, distributed traces, log search, live tail |+| Metrics and dashboards | [metrics-and-dashboards.md](metrics-and-dashboards.md) | `traceway://knowledge/learn/metrics-and-dashboards` | Metric names and tags, aggregations and rate, dashboards, widgets, templates, starring |+| Sessions, AI traces, profiles | [sessions-and-ai.md](sessions-and-ai.md) | `traceway://knowledge/learn/sessions-and-ai` | Session replay, LLM calls, conversations, flagged content, flame graphs |+| Monitors and status pages | [monitors.md](monitors.md) | `traceway://knowledge/learn/monitors` | HTTP, TCP and browser checks, runs, incidents, public status pages, post-mortems |+| Alerts | [alerts.md](alerts.md) | `traceway://knowledge/learn/alerts` | Every rule type and its settings, channels, cooldown, snooze, history |+| On-call | [on-call.md](on-call.md) | `traceway://knowledge/learn/on-call` | Teams, schedules, layers, overrides, escalation policies, pages, contact methods |+| Organization and access | [organization.md](organization.md) | `traceway://knowledge/learn/organization` | Projects, roles, the home page, organization views, Connection, Account, Settings, agent access |++## Page map++| Page | Path | Topic |+|---|---|---|+| Dashboard (home) | `/` | organization.md |+| Issues | `/issues`, `/issues/<hash>` | issues.md |+| Logs | `/logs` | traces-and-logs.md |+| Endpoints | `/endpoints`, `/endpoints/<endpoint>` | endpoints-and-tasks.md |+| Tasks | `/tasks` | endpoints-and-tasks.md |+| Spans | `/spans`, `/spans/<traceId>` | traces-and-logs.md |+| Profiles | `/profiles` | sessions-and-ai.md |+| Sessions | `/sessions` (browser and mobile projects) | sessions-and-ai.md |+| AI Traces | `/ai-traces` | sessions-and-ai.md |+| Dashboards | `/dashboards` | metrics-and-dashboards.md |+| Monitors | `/monitors` (tabs Monitors, Status Pages, Post-Mortems) | monitors.md |+| Public status page | `/status/<slug>` | monitors.md |+| Alerts | `/notifications` (tabs Channels, Rules, History) | alerts.md |+| On-Call | `/on-call` (tabs Pages, Overview, Teams, Schedules, Policies) | on-call.md |+| Connection | `/connection` | organization.md |+| Account | `/account` | organization.md, on-call.md |+| Settings | `/settings` (owners and admins) | organization.md |+| Organization | `/organization` (Servers, Issues, Monitors, On-Call, Projects) | organization.md |+| Project setup | `/setup` | organization.md |++Browser and mobile projects only show Issues, Sessions, Alerts, On-Call and Connection.++## Common questions++| Question | Answer in |+|---|---|+| Why did two errors land in the same issue, or one error split in two? | issues.md, Fingerprinting |+| What does the impact score mean and why is this endpoint Critical? | endpoints-and-tasks.md |+| What happens when I acknowledge a page? Who gets paged next? | on-call.md, Pages and Escalation policies |+| Who is on call right now, and how do I swap a shift? | on-call.md, Schedules and Overrides |+| Snooze or disable a noisy alert? | alerts.md, Disable versus snooze |+| Why is my monitor down after one failure, or not down after several? | monitors.md, States and runs |+| How do I publish uptime to customers? | monitors.md, Status pages |+| Where do I write up the incident? | monitors.md, Post-mortems |+| Why is a span missing from the waterfall? | traces-and-logs.md |+| Why does my counter metric only go up? | metrics-and-dashboards.md, Aggregations |+| Can an agent change things in Traceway? | organization.md, How agents get access |diff --git a/skills/traceway-learn/alerts.md b/skills/traceway-learn/alerts.mdnew file mode 100644index 00000000..9d23329c--- /dev/null+++ b/skills/traceway-learn/alerts.md@@ -0,0 +1,117 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/alerts.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Alerts++Alerts are how Traceway tells people that something happened. They live under **Alerts** in the project sidebar (`/notifications`), in three tabs kept in `?tab=`:++| Tab | What it holds |+|---|---|+| **Channels** (default) | Where notifications go. Create a channel first, then attach rules to it. |+| **Rules** | When to notify. Each rule watches one condition and sends to exactly one channel. A channel can serve many rules. |+| **History** | Every notification that was sent, with its status |++Rules and channels belong to a project and only see that project's data. Channels have their own On/Off switch, and a rule only runs while its channel is on. Changing them needs write access on the project. Browser and mobile projects only offer the New Issue rule type.++## Channels++| Type | Configuration | What it sends |+|---|---|---|+| **Email** | 1 to 10 recipient addresses | An HTML email per alert |+| **Slack** | Incoming webhook URL, optional channel override and username | An attachment coloured by severity: blue info, orange warning, red critical, green recovery |+| **Webhook** | URL, method (POST or PUT), optional headers, optional HMAC secret | JSON with `subject`, `body`, `severity`, `ruleType`, `ruleName`, `url`, `timestamp`. With a secret, `X-Traceway-Signature: sha256=<hex>` |+| **GitHub** | Fine-grained token with Issues read and write, owner, repo, optional labels | A GitHub issue. These issues can start the Auto-Fix agent in the repository. |+| **Pushover** | User key and app token, optional device, priority (normal, high, or emergency with a retry of 30 s or more, an expiry up to 10800 s and an optional callback URL), sound, HTML formatting, TTL | A push notification with the dashboard link |+| **Telegram** | Bot token and chat id | A message, cut at 4096 characters with the link kept |+| **Escalation policy** | An escalation policy of the same organization | Nothing by itself: it opens an on-call **page** that escalates until someone acknowledges (`on-call.md`) |++SMS is not a channel type. It is a personal on-call contact method.++Every channel has a **Test** button that sends "Traceway Test Notification". On an escalation channel, Test opens a **real page** and notifies whoever is on call. Resolve that page when done. Testing again while it is still open is refused.++Alert subjects look like `[<Project>] New error: TypeError` or `[<Project>] Check "api" is down`. Exception alerts carry the exception id, hash, occurred-at time, app version, server, the endpoint or task, the stack trace, the attributes and a link to `/issues/<hash>`. Those three fields (hash, exception id, occurred at) are what an agent needs to open the occurrence (see the `notifications` knowledge in the read skill).++## Rule settings shared by every type++| Setting | Meaning |+|---|---|+| Name | Up to 200 characters, shown in every notification |+| Channel | Exactly one |+| Cooldown | Minimum time between notifications for the same condition. Default 15 minutes. |+| Severity | **Auto** (derived from how bad the condition is) or a fixed Critical, Warning or Info. Recovery notices are always Info. |+| Enabled | New rules start enabled. A rule runs only while both it and its channel are enabled. |++## Rule types++The numbers in brackets are what the evaluator uses when a setting is missing. The **New Rule** form starts every type at the same values (5%, 5 minutes, 10 requests, 500 ms, `*`), so set each field on purpose.++| Rule | Fires when | Settings | Auto severity |+|---|---|---|---|+| **New Issue** | An exception hash is seen for the first time, or again for the first time after it was archived | Ignore patterns: comma-separated, case-insensitive substrings matched against the error type (the first stack line up to its first `:`). `*` is stripped, not a wildcard. | Critical |+| **Error Regression** | An archived (resolved) issue occurs again | None | Critical |+| **Error Rate** | The 5xx share across all endpoints exceeds a percentage | Threshold 5%, lookback 5 min, min requests 10 | Warning, Critical at 2x |+| **Error Count** | Errors in the window reach a count (captured messages are not counted) | Threshold 100, lookback 60 min | Warning, Critical at 5x |+| **Endpoint Error Rate** | One endpoint's 5xx share exceeds a percentage | A specific endpoint (`*` matches nothing here), threshold 2%, lookback 10 min, min requests 20 | Warning, Critical at 2x |+| **Endpoint P95** / **Endpoint P99** | The percentile exceeds a threshold | Endpoint or `*` for all, threshold 500 ms, lookback 5 min | Warning |+| **Apdex Drop** | Apdex falls below a threshold | Threshold 0.85, lookback 15 min, min requests | Warning, Critical below 0.5 |+| **Throughput Drop** | Requests drop versus the baseline window just before, scaled to the same length. No baseline traffic, no alert. | Drop 50%, lookback 15 min, baseline 60 min | Warning, Critical at 80% or more |+| **Impact Score Critical / High / Medium** | An endpoint newly enters the level (0.75, 0.50, 0.25) over the trailing 24 hours. Fires once on entry, again only after it leaves and comes back. The first run after a restart or edit only records the baseline. | Min requests 50 | Critical / Warning / Info |+| **Task Duration** | A task's P95 duration exceeds a threshold | Task or `*`, threshold 30000 ms, lookback 30 min | Warning |+| **Task Failure Rate** | The share of task runs with an exception on their own span exceeds a percentage | Task or `*`, threshold 10%, lookback 60 min, min executions 5 | Warning, Critical at 2x |+| **Metric Threshold** | An aggregated metric violates a comparison. No data in the window, no alert. | Metric, aggregation (avg, max, min, sum, p95, p99, last), operator (gt, gte, lt, lte, eq), value 90, lookback 5 min | Warning, Critical when 20% past the value |+| **No Data** | No telemetry of a kind for N minutes. `any` fires only when all four kinds are silent. | Data type (any, endpoints, exceptions, metrics, tasks), 10 min | Critical |+| **AI Trace Cost** | One AI call costs at least the threshold | Trace name or `*`, $0.50 | Warning, Critical at 3x |+| **AI Conversation Cost** | One conversation's cost over 24 hours reaches the threshold | $5 | Warning, Critical at 3x |+| **AI Flagged Content** | An AI call matches a flagged term. The terms come from the project's AI settings. | Optional term list (empty means any flagged match) | Warning |+| **Monitor Down** | Any monitor in the project goes down, plus a recovery notice when it comes back | None | Critical, recovery Info |++The aggregation in Metric Threshold spans every series of the metric with no tag filter, so prefer `max` (or `min` for lower-is-bad metrics) where one bad host could hide in an average.++Apdex uses fixed bands: satisfied up to 750 ms, tolerating up to 1500 ms, anything slower or a 5xx is frustrated. Apdex = (satisfied + tolerating / 2) / total.++## When rules run++- **On ingest**: New Issue, Error Regression, AI Trace Cost, AI Conversation Cost, AI Flagged Content. These fire within seconds.+- **On state change**: Monitor Down, the moment a probe flips the monitor.+- **Polled**: everything else, every 60 seconds by default (self-hosted: `NOTIFICATION_POLL_SECONDS`).++Cooldowns differ by kind:++- **Polled rules** have one cooldown per rule. After it fires, it is not evaluated again until the cooldown ends. This cooldown survives restarts.+- **Ingest and monitor rules** cool down per item: per exception hash, trace name, conversation or monitor. Two different new errors a minute apart both alert. The same error does not alert again within its cooldown. This memory is in process only, so a restart can let the same item alert once more.+- The cooldown cannot be 0. Empty or 0 becomes 15 minutes.+- **Editing** a rule resets its cooldown and its per-item memory, so the new settings apply at once. Toggling it does not.++Delivery goes through a durable queue. Failed sends are retried after 1, 5, 15 and 60 minutes, five attempts in all. A queued message keeps the channel settings it was sent with.++## Disable versus snooze++- **Disable** turns a rule off until someone turns it back on. The dashboard asks for confirmation.+- **Snooze** mutes a rule for a set time and it comes back on its own. The dashboard offers 30 minutes and 1, 4, 8 or 24 hours. Clearing the snooze turns it back on early.+- A snoozed or disabled rule is **not evaluated at all**, so nothing is queued while it is muted and it does not catch up afterwards.++During a known incident or a deploy, snooze the noisy rule rather than disabling it: a snooze cannot be forgotten in the off position.++The Rules table shows each rule's status as **On**, **Off** or **Snoozed**.++## History++The History tab lists every notification with severity, rule, subject (linking to the page it is about), channel, status and time. It has search and a time range. Statuses:++| Status | Meaning |+|---|---|+| Sent | Delivered. On an escalation channel, a page was opened. |+| Failed | All retries failed. The error is kept. |+| Deduped | An escalation alert folded into a page that was already open |++History opens on the last 7 days.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List rules with enabled and snoozed state | `traceway alerts list` | `list_notification_rules` |+| Turn a rule on or off (write) | `traceway-write alerts enable <id>` / `disable <id>` | `set_notification_rule_enabled` |+| Snooze a rule (write) | `traceway-write alerts snooze <id> --minutes N` (0 clears) | `snooze_notification_rule` |++Creating and editing rules and channels, the History tab and the Test buttons stay in the dashboard. Channels hold credentials and webhook URLs.++To resolve an alert someone pasted, the read skill's `notifications` section explains how to go from an exception or performance alert to the data behind it.diff --git a/skills/traceway-learn/endpoints-and-tasks.md b/skills/traceway-learn/endpoints-and-tasks.mdnew file mode 100644index 00000000..1d130d77--- /dev/null+++ b/skills/traceway-learn/endpoints-and-tasks.md@@ -0,0 +1,81 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/endpoints-and-tasks.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Endpoints and tasks++Both pages are hidden for browser and mobile projects. Both are built from spans promoted at ingest (`traces-and-logs.md`), so a request or a task run always opens its own span waterfall.++## Endpoints (`/endpoints`)++Every HTTP request a backend serves, grouped by method and route template (`GET /api/users/:id`).++**The list**++| Column | Meaning |+|---|---|+| Endpoint | Method and route. Badges: **Stream** (SSE or WebSocket: left out of latency and Apdex, scored on errors only), **Healthcheck** (the project drops healthy healthcheck requests, so only those with status 400 or more are kept), **Non Root** or **Mixed** (all or some requests have a parent span, usually an upstream service in the same trace) |+| Calls | Request count |+| Typical | P50 |+| Slow | P95 |+| Awful | P99 |+| Impact | The impact level (below). The default sort. |++- Filters: search, HTTP method, and Root (all, root, non-root).+- The **Performance** chart above the table shows total time as a stacked area of the top 5 endpoints plus Other (drag across it to zoom the range), or P50, P95 or P99 as a bar chart of the top 8 endpoints on the current table page.+- **Healthchecks**: the project settings (**Edit Project > Healthchecks**) can drop healthy healthcheck requests, with extra healthcheck paths.+- Requests that return 404 without matching a route are grouped as `UNMATCHED`, so scanners do not create one endpoint per probed path. A 404 from a real route keeps its route.++**Impact score**: one number from 0 to 1 per endpoint that ranks the endpoint hurting users the most first. It is the **worst** of five components:++1. Apdex degradation: 1 minus Apdex.+2. Error-rate floor, where bad means slow or 5xx: over 10% gives 0.25, over 20% gives 0.50, over 33% gives 0.75.+3. P99 floor: over 3 s gives 0.25, over 6 s gives 0.50, over 8 s gives 0.75.+4. Client error (4xx) floor, with more than 10 requests and ignoring `UNMATCHED`: over 25% gives 0.50, over 50% gives 0.75.+5. A volume-aware floor: a smaller error share with a large number of bad requests still ranks high.++| Level | Score |+|---|---|+| Critical | 0.75 and up |+| High | 0.50 and up |+| Medium | 0.25 and up |+| Good | below 0.25 |++Every endpoint has an **impact reason** naming the dominant factor: "P99 latency is 9.2s", "N errors with X% error rate", "X% of requests returning 4xx errors", "X% of requests are slow or failing", or "Endpoint is healthy". Stream endpoints get error-only versions such as "Streaming endpoint is healthy".++**Apdex** uses fixed bands: satisfied up to 750 ms and not a 5xx, tolerating up to 1500 ms, anything slower or a 5xx is frustrated. Apdex = (satisfied + tolerating / 2) / total. 1.0 is perfect. Below about 0.85, users notice.++**Expected performance (slow endpoint marks)**: some endpoints are allowed to be slow, such as a report export or a batch upload. On the endpoint page, **Expected Performance** sets an offset in milliseconds and a reason. The offset is added to the Apdex bands and the P99 floor, so the endpoint stops being penalized up to that latency. Raw percentiles are never adjusted. An offset of 0 removes the mark. The header then shows "+N ms offset". Setting it needs write access on the project.++**The endpoint page** (`/endpoints/<endpoint>`)++- Tiles: average, median, P95 and P99 response time, Apdex, average error rate, average throughput (requests per minute). Stream endpoints show connections, error rate and throughput instead.+- The request table: recorded at, duration, status, body size, client IP, server, version and attributes, sortable. Search attribute values and add attribute filters (equals, not equals, contains, not contains) to find the requests of one tenant or user.++**A request** (`/endpoints/<endpoint>/<id>`)++- Details: endpoint, status, duration, recorded at, server, version, client IP, body size, attributes.+- **Exception Occurred**, linking to the issue, and captured **Messages**.+- The **Spans** waterfall: database queries, outgoing HTTP calls and other work inside the request, nested by parent. Large traces start folded, with **Expand all** and **Collapse all**. Each span opens its attributes. **Open the whole trace** jumps to the trace page.+- **Logs** for the trace, and the **Distributed Trace** card.++## Tasks (`/tasks`)++Background work outside a request: queue consumers (`CONSUMER` spans from any queue driver), scheduled commands (root `console.command` spans), cron jobs and scripts.++- **The list**: task name, runs, typical (P50), slow (P95), sorted by runs. Search and the Root filter. There is no impact score. Rank by count times (P95 minus P50) for a rough idea of where time goes.+- **The task page**: average, median, P95 and P99 duration and throughput, then the runs: recorded at, duration, client IP, server, version, attributes.+- **A run**: details, the exception if one happened, messages, the span waterfall and logs.+- A run **failed** when an exception was recorded on its own span. That is what the Task Failure Rate alert counts.++A queue worker whose span is parented to the request that enqueued it shares that request's trace id, so the distributed trace card shows the endpoint and the task together.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| Endpoints with percentiles and impact | `traceway endpoints list --since 24h [--order-by impact\|count\|p95\|lastSeen] [--search S]` | `list_endpoints` |+| Latency over time (find when it changed) | `traceway endpoints chart [--metric-type total_time\|p50\|p95\|p99] [--interval-minutes N]` | `endpoints_chart` |+| One request with its spans and errors | `traceway endpoints show <id> --recorded-at <t>` | `get_endpoint_request` |+| An endpoint's expected-performance mark | `traceway endpoints slow <endpoint>` | `get_slow_endpoint_config` |+| One task run | `traceway tasks show <id> --recorded-at <t>` | `get_task` |+| Mark an endpoint slow (write) | `traceway-write endpoints mark-slow <endpoint> --offset-ms N --reason R` | `set_slow_endpoint` |++There is no task list command. Find a task's runs through its exceptions, its trace id or the dashboard. Latency percentiles only come from endpoints, never from `metrics query`. The `traceway` skill's performance flow covers a full latency investigation.diff --git a/skills/traceway-learn/issues.md b/skills/traceway-learn/issues.mdnew file mode 100644index 00000000..f5a86775--- /dev/null+++ b/skills/traceway-learn/issues.md@@ -0,0 +1,66 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/issues.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Issues and exceptions++An **issue** is a group of exceptions (or captured messages) that share one fingerprint. The issues list ranks root causes, not repetitions: a bug in a hot path that throws ten thousand times is one row with a count of ten thousand.++## What creates an issue++- An unhandled exception or panic during a traced request or task.+- An error recorded on a span as an OpenTelemetry `exception` event.+- An exception or a message captured explicitly through a Traceway SDK (browser, mobile).++There are two kinds:++- **Errors** have a stack trace.+- **Messages** are captured strings with no exception. They group by their exact text, so variable data belongs in attributes. `"payment failed for order 123"` makes a new issue per order.++## Fingerprinting++Every error gets a **fingerprint**: a 16-hex-character hash of its normalized stack trace. The hash is the issue's identity. It is in the URL (`/issues/<hash>`), and archiving, regressions and alerts all key on it.++Before hashing, values that change between occurrences of the same bug are removed: the error message (only the type is kept), ids, UUIDs, hex addresses, IPs, emails, long numbers, goroutine numbers, absolute paths (only `file:line` stays), URL origins, module versions, JVM line numbers, columns (except on line 1, where minified bundles need them), and resolved JavaScript function names.++So the same failure keeps one issue across servers, environments, versions and users. A new issue appears when the failure changes: a different error type or a different code path. Line numbers count for most languages, so moving code inside a file can split an issue after a deploy (JVM frames are the exception). Uploading source maps or debug symbols for the first time rewrites the frames, so later occurrences form a new issue.++## The issues page (`/issues`)++- **Columns**: Issue (error type and first line), Trend (hourly sparkline), Events (count), Last Seen. Sort by Events or Last Seen (the default). Sort by last seen to see what is happening now.+- **Search**: a case-insensitive substring of the stack trace, scoped to **All**, **Issues** (errors only) or **Messages**.+- **Time range**: defaults to 24 hours. An issue is listed when it occurred in the range.+- **Archived issues** are hidden. The page has no toggle to show them.+- **Bulk archive**: select rows (up to 100) and **Archive**. When the selected issues have open on-call pages, the dialog offers to resolve them too (checked by default).++## The issue page (`/issues/<hash>`)++- The stack trace with **Formatted** and **Raw** views. Formatted folds library and system frames (JavaScript, Flutter, iOS, Java, Go). A **Message** badge marks captured messages.+- First seen, last seen, total occurrences, and the **Archive** button.+- The on-call team that owns the project and who is on call now.+- **Last Event**: when, server, version, trace id, attributes, and the **related endpoint, task or AI trace** it happened in, with its status, duration and a link. Browser issues show the replay clip from just before the error, or a **View full session** button.+- A **Distributed Trace** card when other endpoints, tasks, AI traces or exceptions share the trace id.+- On browser issues, **Session Context**: the console logs and user actions around the error, synced to the replay.+- The first 10 events, then **View all N events** (`/issues/<hash>/events`, 50 per page). Each event opens its own occurrence page.++**Occurrence** pages (`/issues/<hash>/<exceptionId>`) show one occurrence with the same event card. When debugging, fix the **last** occurrence, not the group: it is the one with the current code and data.++## Lifecycle++1. **Active**: it occurred.+2. **Archived**: someone marked it fixed or accepted. It is hidden from the list.+3. **Back**: an archived issue that occurs again after its archive time shows in the list again by itself. It stays archived until someone unarchives it, so it hides again only if it is archived again. On that first re-occurrence the **New Issue** rule fires once. The **Error Regression** rule fires on it and on every later occurrence while the issue is still archived, limited by its cooldown.++Archive an issue once it is fixed, so that a regression alerts. Unarchiving has no button in the dashboard. Agents with write access can do it, and the issue also comes back by itself if it occurs again.++## Attributes++An occurrence carries the key-value attributes in scope when it happened. Under a trace it also carries the span's attributes. Request URL, query, body and headers can be attached when the SDK is configured to record them.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List issues | `traceway exceptions list --since 24h [--search S] [--include-archived]` | `list_exceptions` |+| One issue with occurrences | `traceway exceptions show <hash>` | `get_exception` |+| One occurrence | `traceway exceptions occurrence <id> --recorded-at <t>` | `get_exception_occurrence` |+| Archive or unarchive (write) | `traceway-write exceptions archive\|unarchive <hash>...` | `archive_exceptions` / `unarchive_exceptions` |++Search is always a case-insensitive substring of the stack trace. The list comes back newest activity first (`lastSeen`); `--order-by firstSeen` or `count` changes that. `--include-archived` is the only way to list archived issues. The `traceway` skill's debug flow walks an issue from hash to root cause.diff --git a/skills/traceway-learn/metrics-and-dashboards.md b/skills/traceway-learn/metrics-and-dashboards.mdnew file mode 100644index 00000000..432c1a59--- /dev/null+++ b/skills/traceway-learn/metrics-and-dashboards.md@@ -0,0 +1,67 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/metrics-and-dashboards.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Metrics and dashboards++## Metrics++A metric point is a name (`system.cpu.utilization`, `orders.created`), a numeric value, a timestamp and tags (`server_name`, `state`, `direction`, ...).++- **Where they come from**: OpenTelemetry meters in the application (counters, histograms, gauges), runtime instrumentation (Go, Node.js and others), and host metrics from the Traceway OTel Agent or an OpenTelemetry Collector with the hostmetrics receiver (`system.*` names: CPU, memory, disk, filesystem, network, processes).+- **Histograms** are stored as two series, `<name>.avg` and `<name>.count`.+- **Tags** come from the data point's attributes, plus an allowlist of resource attributes Traceway lifts: `host.name`, `host.id`, `os.type`, `cloud.region`, `container.name`, `k8s.cluster.name`, `k8s.pod.name`, `k8s.node.name`, `postgresql.database.name` and a few more. The `server_name` tag comes from `service.name`. The allowlist also covers `k8s.namespace.name`, `k8s.deployment.name`, `cloud.provider`, `cloud.availability_zone` and `process.*`.+- **Resolution**: on ClickHouse it follows the range so long ranges stay fast: raw points up to 6 hours, 1-minute rollups up to 72 hours, 1-hour rollups up to 30 days, daily beyond. SQLite and DuckDB always read raw points.+- **Stored types**: gauges, sums and histograms. Exponential histograms and summaries are dropped.++Aggregations:++| Aggregation | Use |+|---|---|+| `avg`, `min`, `max`, `sum`, `count`, `last` | Gauges and per-bucket values. `max` is the honest choice when one bad series could hide behind healthy ones in an `avg`. |+| `rate` | Cumulative counters such as `system.network.io` and `system.disk.io`. Each series is differenced against its previous sample, resets are dropped, and the result is per second (`By` becomes `By/s`). Charting a counter as `avg` only climbs forever. |++A widget source can also be **inverted** (1 minus the value). The agent reports `system.cpu.utilization` per state, and `idle` inverted is the busy share.++Dashboards and agent queries have no percentile aggregation over metric points. Only the Metric Threshold alert rule can compute `p95` or `p99` of a metric. Latency percentiles come from endpoints and tasks (`endpoints-and-tasks.md`).++## Dashboards (`/dashboards`)++A dashboard is a set of metric widgets that belongs to the **organization**, not to one project. It is applied to any number of projects and shows as a tab on each of them. An edit made in one project is live in all of them.++The active tab's menu: **Rename Dashboard** (names are unique in the organization), **Edit as JSON**, **Export JSON**, **Apply to Projects**, **Remove from this Project** (it stays elsewhere), **Delete Dashboard** (everywhere, permanently).++**Adding**: ⌘K (Ctrl K) or **Add or find dashboards...** opens one search over the dashboards of every organization the user belongs to (selecting one applies it here, or copies it in from another organization), the template marketplace (selecting one installs a copy) and every metric name seen in the organization (selecting one opens the widget editor prefilled). An empty project shows **Browse Dashboards & Templates**.++**Templates**:++| Template | Metrics it expects |+|---|---|+| OTelemetry Server Agent | Host CPU, memory, disk and network from the Traceway OTel Agent |+| Go Application | Go runtime and process metrics |+| Traceway ClickHouse | `traceway.ch.*` from a monitored Traceway instance |+| Traceway DuckDB | `traceway.duckdb.*` from a monitored Traceway instance |++**Widgets**: Line Chart, Area Chart, Stacked Area, Bar Chart, Single Value, Gauge and Table. Each has one or more sources: a metric name, an aggregation, optional tag filters (equals), an optional group-by that draws one series per tag value, and optionally inverted. Several sources overlay on one chart. Hover for values, drag across a chart to zoom in.++**Instance filter**: the picker in the header narrows every widget to one `server_name` seen in the range. It lives in the URL (`?server=<name>`), is not saved to the dashboard, and is where a row on the organization's Servers page leads.++**Starring**: the star on a widget pins it to the project's home page, where starred widgets can be resized and reordered. Stars are per project.++**As code**: every dashboard is one JSON document (`schemaVersion`, `name`, `widgets` in display order, each with `id`, `title`, `widgetType`, `config.sources`). Edit it in place, export it, or import a single dashboard or a whole organization bundle. The import API has an upsert mode that matches by name, so CI can keep dashboards in sync from files. Keep widget ids when editing so home page stars survive.++**Grafana import**: paste a Grafana export. Time series and graph panels become line charts, stat becomes single value, gauge stays a gauge, and Prometheus queries become metric sources. Anything that does not convert faithfully is listed as a warning, never silently dropped.++Editing dashboards and widgets needs an organization role above `readonly`. Starring, tab order and home page layout follow the effective project role. The Dashboards page is hidden for browser and mobile projects.++## Reading it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| A metric series | `traceway metrics query --name <metric> --aggregation avg --since 1h [--tag key=value] [--group-by tag] [--interval-minutes N]` | `query_metrics` |++- An unknown metric name returns an empty series, so probing names is safe.+- A grouped query keeps the first 200 groups and says `truncatedGroups: true` when it cut some.+- The server widens buckets so no series has more than 2000 points, and returns the bucket size it used as `intervalMinutes`.+- Agents get `avg`, `sum`, `count`, `min` and `max`. `rate`, `last` and inverted sources are dashboard only, so read a counter's increase by comparing buckets.+- `query_metrics` refuses `p50`, `p95` and `p99`. The CLI accepts them, but the server computes `avg` instead.+- There is no metric-name discovery tool. Try likely names (an unknown one returns an empty series), or look at a dashboard.++Creating, editing and applying dashboards stays in the dashboard.diff --git a/skills/traceway-learn/monitors.md b/skills/traceway-learn/monitors.mdnew file mode 100644index 00000000..4ccb8da0--- /dev/null+++ b/skills/traceway-learn/monitors.md@@ -0,0 +1,148 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/monitors.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Monitors, incidents, status pages and post-mortems++Monitors answer the question telemetry cannot: is the service reachable from the outside? Traces and logs only exist while requests arrive. A monitor keeps probing on a schedule, so the team learns the site is down before a user tells them.++Everything here lives under **Monitors** in the project sidebar (hidden for browser and mobile projects), in three tabs kept in `?tab=`:++| Tab | Who sees it | What it holds |+|---|---|---|+| Monitors | Every member | The project's checks. "New Monitor" needs write access on the project. |+| Status Pages | Organization owners and admins | Public uptime pages for the organization |+| Post-Mortems | Every member | The project's internal incident write-ups |++The sidebar badge counts the project's monitors that are down right now. The organization's **Monitors** page lists every monitor across all projects with the incident history (see `organization.md`).++## Check types++| Type | What it does | Configuration |+|---|---|---|+| **HTTP** | Requests a URL, like Postman would | URL (http or https), method (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS), headers, auth (none, basic, bearer, or a custom header), a body for POST, PUT, PATCH and DELETE (Content-Type defaults to `application/json`), follow redirects (on by default), skip TLS verification (off by default) |+| **TCP** | Opens a connection to a host and port | Host, port, optional TLS, an optional payload to send, and an optional "expect response containing" string (up to 64 KB is read) |+| **Browser** | Runs a real `@playwright/test` spec in headless Chromium | The script (up to 100 KB, edited on the check) and optional environment variables. Only runs where the operator turned browser checks on. Never available on Traceway Cloud. |++HTTP expected results, all optional:++- **Status codes**: a list such as `200, 204`. Left empty, anything below 400 passes.+- **Body contains** a substring, or **body matches** a regex. Only the first 1 MB of the body is checked.+- **Max response time** in milliseconds.+- **Min TLS days remaining**: fails the run when the certificate expires sooner. This is how a team catches a certificate about to expire. TCP checks over TLS have the same option.++When several assertions fail, the run's error lists all of them separated by `; `.++Shared settings on every check:++| Setting | Range | Default |+|---|---|---|+| Interval | 30 seconds to 24 hours (the UI offers 30s, 1m, 2m, 5m, 10m, 15m, 30m, 1h, 6h, 24h) | 1 minute |+| Timeout | 1 to 120 seconds | 30 seconds |+| Failures before down | 1 to 10 consecutive failures | 2 |++The type cannot change after creation. Saving an edit schedules a run right away. On Traceway Cloud, checks can only target public addresses. Self-hosted instances allow private and LAN targets unless the operator sets `SYNTHETICS_ALLOW_PRIVATE_TARGETS=false`.++## States and runs++| Status | Meaning |+|---|---|+| **Pending** | No result yet (stored as `unknown`) |+| **Up** | The last run passed |+| **Down** | The last N runs failed, where N is the failure threshold |+| **Paused** | The check is disabled. Pausing drops queued runs. It does not resolve an open incident. |++- One success sets the check Up immediately and resets the failure counter.+- A failure only turns the check Down once consecutive failures reach the threshold. This is flap damping: one flaky probe does not page anyone at 3am.+- **Missed** runs: a queued run that is not picked up within its window (the interval, capped at 5 minutes) is recorded as `missed` instead of running late. Missed runs never change the state and are left out of uptime and latency. If Traceway itself was down, the charts show a gap, never a made-up 100%.+- HTTP and TCP probes run on the Traceway server. Browser runs run on the server or on a remote runner, shown as "via <name>" in the run history. There are no probe regions.+- A failed browser run stores a screenshot and the Playwright output. Both open from the run history.++## The monitor page++Covers the last 30 days. It has no time picker.++- **Tiles**: uptime, average latency, interval, and recent incidents (red while one is ongoing).+- **Availability strip**: green all up, red all down, amber mixed, grey no data. The tooltip shows up, total and missed counts.+- **Latency chart**: average latency per bucket.+- **Run history**: filter by All, Up, Down or Missed. Each row has the time, the executor, the result, the latency, the status code (not for browser checks) and the full error.+- **Incidents**: each with its time range, error, Resolved or Ongoing, and a **Write post-mortem** link (or **Post-mortem** once one exists).+- **Actions** (write access): Run now, Pause or Resume, Edit, Delete. Deleting removes the run history and incidents and resolves the on-call pages the monitor opened.++The monitor list shows name, type, status, 30-day uptime (green at 99.9% or more, amber at 99% or more, red below), average latency and last run. It can be searched and filtered by type.++**Run now** queues an immediate run. It is unavailable while the check is paused, and refused while a run is already queued ("A run for this check is already queued.") or for a browser check when the server has browser checks turned off. Such browser checks also skip their scheduled runs. Use it to confirm a fix without waiting for the next interval. The result appears in the run history within seconds.++## Alerting on monitors++A **Monitor Down** alert rule covers every monitor in the project. It fires when a monitor goes down and sends a recovery notice (always Info, green in Slack) when it comes back. Pending to Up sends nothing. Pointed at an escalation channel, it opens an on-call page per monitor, and recovery resolves that page on its own. See `alerts.md` and `on-call.md`.++## Incidents++An incident is a span of time when something was down, with an optional public story: a title and a timeline of updates.++**Automatic incidents** come from monitors:++- Going down opens one, holding the probe's error, with an automatic **Investigating** update. Recovery resolves it with a **Resolved** update.+- The default title is "<monitor name> is down". Anyone with admin rights can rename it to something users understand, such as "Checkout is failing for some card payments". Clearing the title brings the default back.+- The monitor owns the lifecycle. An automatic incident cannot be resolved by hand, re-timed or deleted.+- The probe's error message stays internal. It never reaches a public status page.++**Manual incidents** record outages the monitors missed, or maintenance windows:++- Created with **Record Incident** on a status page's incident history (admins only). A title is required, plus an optional first update, a start time (backdating is fine) and an optional resolved time.+- Resolve one by posting a **Resolved** update or setting the resolved time. Clearing the resolved time reopens it. Manual incidents can be deleted, and a linked post-mortem survives.+- They never change a monitor's uptime numbers.++**Timeline updates** carry a status, **Investigating**, **Identified**, **Monitoring**, **Update** or **Resolved**, and a message of up to 2000 characters. They are public content, so posting, renaming and deleting need an organization owner or admin. Every member can read the incident history.++Where incidents are managed:++- **Status Pages tab > Incidents** on a page: the full paginated history of that page's monitors plus its manual incidents. Expand a row to rename it, post updates, open or write the post-mortem, and resolve or delete manual incidents.+- **The monitor page**: that monitor's incidents.+- **Organization > Monitors**: every incident in the organization that was open at any point in the selected range.++## Status pages++A status page publishes the uptime of selected monitors at `/status/<slug>`, with no login. Only organization owners and admins create and edit them.++| Field | Rules |+|---|---|+| Title | Required, up to 200 characters |+| Slug | 3 to 60 lowercase letters, digits and hyphens, unique |+| Description | Optional, up to 500 characters |+| Logo | PNG or JPEG up to 1 MB, uploaded after saving. SVG is refused. |+| Custom domain | Self-hosted only (see below). Optional hostname such as `status.acme.com`, unique, never the Traceway host itself. On Traceway Cloud leave it empty and frame the page instead. |+| Publicly accessible | On by default. A private page answers 404, the same as an unknown slug. |+| Monitors | 1 to 50. The dashboard picker offers the current project's monitors. |++What visitors see:++- A banner: "All systems operational", or a red "Some systems are experiencing issues" when a monitor is down.+- Per monitor: Operational, Major outage, or No recent data (paused monitors), its 90-day uptime, and 90 daily bars in UTC: **Operational** (green, 99.5% or more), **Partial outage** (amber), **Major outage** (red, no successful run) and **No data** (grey). Narrow screens show 60 or 30 days.+- **Past Incidents**: the last 90 days of incidents (up to 30), grouped by day, each with its title and timeline updates.+- No latency numbers and no internal error messages. Always a light theme.++The data is cached for 30 seconds and the page refreshes itself every minute. Any edit to the page or its incidents clears the cache. Status pages can be framed by any site. To serve one on a company domain, a self-hosted instance points a CNAME at Traceway behind a TLS proxy that passes the Host header through and sets **Custom domain**. On Traceway Cloud, or when touching the proxy is not an option, host a small HTML file that frames `/status/<slug>` full window.++## Post-mortems++Internal write-ups of an incident: what happened, the impact, the timeline, the root cause and the follow-ups. They belong to one project, so opening one under a different project answers not found. They never appear on a status page.++- **Creating**: a dialog asks only for a title, creates the document and opens the editor. It can be started from the Post-Mortems tab, from an incident on the monitor page, or from an incident on a status page's history (which pre-links that incident).+- **Editor**: rich text with a **Rich text / Markdown** toggle. Type `/` for headings, lists, tables and code blocks. Content is Markdown, up to 200 KB.+- **Tags**: lowercased, up to 20 per document, 50 characters each.+- **Incident link**: optional, one post-mortem per incident. The picker offers the project's own monitor incidents plus the organization's manual status page incidents that have no post-mortem yet. Linked incidents show a link to the document everywhere they appear. Deleting the incident or monitor only severs the link.+- **Activity**: every create and edit with who, when and which parts changed (title, content, tags, incident). Saving without a change records nothing.+- **Finding them**: search matches title, content and tags, and clicking tags filters by all of them together. When a similar incident hits, last time's fix is one search away.+- **Permissions**: every member with project access reads them. Creating, editing and deleting need write access on the project.++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List monitors with their current status | `traceway monitors list` | `list_checks` |+| One monitor with its incidents | `traceway monitors show <id>` | `get_check` |+| List post-mortems | `traceway post-mortems list [--search S] [--tag T]` | `list_post_mortems` |+| Read a post-mortem | `traceway post-mortems show <id>` | `get_post_mortem` |+| Run a monitor now (write) | `traceway-write monitors run <id>` | `run_check` |+| Create or edit a post-mortem (write) | `traceway-write post-mortems create\|update` | `create_post_mortem` / `update_post_mortem` |++Creating or editing monitors, status pages, incidents and public timeline updates stays in the dashboard. Status pages and updates are public, so a person should decide what the world reads.diff --git a/skills/traceway-learn/on-call.md b/skills/traceway-learn/on-call.mdnew file mode 100644index 00000000..e63e8ad8--- /dev/null+++ b/skills/traceway-learn/on-call.md@@ -0,0 +1,133 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/on-call.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# On-call: teams, schedules, escalation and pages++On-call turns an alert into a person's phone ringing. An alert alone posts to a channel and hopes someone is watching. A **page** keeps escalating until a human acknowledges it.++## How the pieces fit++An alert rule whose channel is an **escalation policy** fires. Instead of sending a message it opens a **page**. The page walks the policy step by step. Each step's targets resolve to people through a **schedule** (whoever is on call), a **team** (every member) or a direct **user**. Each person is reached through their own **contact methods**, in the order their personal **notification rules** say.++Two ideas to hold on to:++- **The page is the unit of work, not the message.** A rule that fires two hundred times opens one page. Re-fires bump its event counter and never restart the escalation clock.+- **Escalation stops on acknowledge, not on delivery.** Sending a message proves nothing. Traceway keeps climbing the policy until someone acknowledges or the policy runs out.++Setup order: create a team, build its schedule, create a policy whose first step targets the schedule, add an **Escalation policy** channel on the Alerts page and attach rules to it, then have every responder add contact methods. A responder with no contact methods is still paged on their account email.++## Where it lives++**On-Call** in the project sidebar (`/on-call`), with a badge counting the project's open pages. Five tabs:++| Tab | What it shows |+|---|---|+| **Pages** (default) | The page queue. Filters: All active (open or acknowledged), Open, Acknowledged, Resolved. Columns: severity, subject, level ("L2 of 3", "exhausted", "repeat N"), age, events, status, who acknowledged or resolved, actions. Rows can be selected for bulk acknowledge or resolve. |+| **Overview** | Per team and per schedule: who is on call now, until when, and who is next |+| **Teams** | Teams with members, owned projects and schedules |+| **Schedules** | Schedules with their rendered timeline and overrides |+| **Policies** | Escalation policies with their chain |++Teams, schedules and policies belong to the **organization**, so the page has an organization switcher. Pages belong to a project. The organization's **On-Call** page lists pages from every project (`organization.md`). The issue page shows the team that owns the project and who is on call for it now.++## Teams++A team is a named group of people that owns projects. Each project is owned by at most one team. Fields: name (unique in the organization), description, members, owned projects. Member order only affects how the team is listed: a policy step that targets a team pages every member at once. Deleting a team deletes its schedules, and is refused while a policy targets the team or one of its schedules.++## Schedules++A schedule answers one question: who is on call right now. It belongs to a team and has its own **timezone** (an IANA name, defaulting to the organization's). Set the timezone to where the people live. Handoffs and restrictions are in that timezone and hold their wall-clock time through daylight saving.++A schedule is built from **layers**. Each layer is an independent rotation:++| Field | Meaning |+|---|---|+| Rotation | `daily`, `weekly`, or custom (every N days, 1 to 365) |+| Handoff time | When the shift changes hands, HH:MM |+| Handoff day | The weekday of the handoff, for weekly rotations |+| Rotation start | The date the rotation counts from |+| Members | The people to rotate through, in order, one per period |+| Restrictions | Optional windows that limit when the layer covers anything |++Restrictions are **daily** (for example 18:00 to 09:00, wrapping past midnight) or **weekly** (for example Saturday 00:00 to Monday 09:00). With none, the layer covers every minute. If a handoff falls inside a window, the person changes mid-window.++**Stacking**: a later layer wins over earlier ones where they overlap. Exactly one person is on call at any moment: the highest layer covering it. If no layer covers a moment, nobody is on call and a step targeting the schedule reaches nobody.++**Overrides** temporarily replace whoever the layers picked, for an appointment, a swapped weekend or a vacation. They beat every layer, and the newest override wins where two overlap. An override lasts at most 30 days. The person covering must be an organization member but does not have to be in the schedule. **Any member** can create one, not only admins. It can be deleted by its creator, the person it covers, or an admin. Overrides end on their own, so there is no need to edit the rotation and remember to put it back.++The **timeline** shows a row per layer and a final **Schedule** row, which is who actually gets paged. Overrides appear in the Schedule row as dashed shifts marked Override. A red line marks now. Ranges are Day, Week, 2 Weeks and Month, up to 62 days.++Limits: 20 layers per schedule, 50 members per layer, 10 restrictions per layer. A schedule used by a policy cannot be deleted until the step is removed. A member removed from the organization is removed from every layer (a layer left empty is dropped) and their overrides are deleted. Team, schedule and policy names are unique in the organization.++Common shapes:++- **One rotation**: one weekly layer over everybody.+- **Business hours and out of hours**: two layers with opposite restrictions. The second, smaller group covers nights and weekends.+- **Primary and secondary**: two schedules, and a policy whose second step targets the secondary.++## Escalation policies++A policy is the ordered list of who to wake, and how long to wait for each.++- **Steps**: 1 to 10. Each holds 1 to 10 targets and a delay: "escalate after N minutes if not acknowledged" (1 to 1440, default 5).+- **Targets**: a **schedule** (whoever is on call when the step runs, overrides included), a **team** (every member), a **user**, or a **channel** (any notification channel of the organization except an escalation one, to post the page to Slack, a webhook or email alongside the people). Within one step each person is notified once.+- **Repeat**: 0 to 5. After the last step, its delay passes and the chain starts again from step 1, that many more times. After that the escalation is **exhausted**: nothing more is sent, but the page stays open.+- **Urgency**: **Auto** (critical becomes high, everything else low), **Always high** or **Always low**. It picks which of a responder's two notification chains runs. It is fixed when the page opens, so a low-severity re-fire never downgrades a page.++A page keeps a copy of its policy from the moment it opened, so editing a policy never changes pages already escalating. A policy used by a channel cannot be deleted.++## Pages++| Status | Meaning |+|---|---|+| **Open** | Nobody has taken it. Escalation is running. |+| **Acknowledged** | Someone is on it. Escalation stopped and every queued delivery is cancelled, including the later steps of personal notification chains. |+| **Resolved** | Finished. The dedup key is released, so the same condition can open a fresh page. |++- **Deduplication**: while a page is unresolved, the same rule and item (endpoint, metric, task, exception hash, monitor...) bump the existing page instead of opening a new one. Rules with no item dedup at rule level, so one noisy rule is one page. This is what stops a flapping error from becoming a pager storm.+- **Escalation**: step 1 is notified within a second or so. Later steps follow after their delays.+- **Acknowledge and resolve need no write access.** A read-only responder paged at 3am can still take the incident and close it.+- **Resolve and archive**: resolving a page opened by a New Issue or Error Regression rule can also archive its issue (that part needs write access). Archiving an issue in turn offers to resolve its open pages.+- **Auto-resolve**: a Monitor Down page resolves itself when the monitor recovers. A blip at night that recovers needs no human.+- **The page detail** shows the subject with severity, urgency and status, the rule, event count and last event, the alert body, the escalation chain with the current step marked (or "Escalation exhausted"), and the **delivery timeline**: every delivery with its step, target, method and status (pending, sent, failed, cancelled). That timeline is what to read when someone says they never got paged. Personal phone numbers and email overrides are masked there.++**Acknowledging without logging in**: every delivery to a person carries its own acknowledge link (`/ack/twk_...`). Opening it shows a summary of the page and an **Acknowledge** button, with no login. Opening the link is read only, so an email scanner cannot acknowledge by accident. The link can only acknowledge that one page, it is credited to the person it was sent to, and it stops working once the page is resolved. Deliveries to a channel target get the ordinary dashboard link instead, since a shared room has no single owner.++Page messages start with `[Page]`, or `[Page - escalation L2]` for later steps, and end with the acknowledge link.++## Contact methods and notification rules++Personal settings under **Account** (tabs **Contact Methods** and **Notification Rules**). Only the person can see or change their own.++| Contact method | Configuration |+|---|---|+| Email | Optional address. Blank uses the account email. |+| Slack | Incoming webhook URL, optional channel and username |+| Pushover | User key and app token |+| Telegram | Bot token and chat id |+| SMS | E.164 phone number such as `+12025550123`. Only offered when the server has Twilio configured. |++- SMS numbers must be verified before they are paged: a 6-digit code that expires in 10 minutes, with 5 attempts and at most 3 codes per hour.+- Every method has an enable toggle and a **Test** button ("If you received this, pages will reach you here.").+- **Notification rules** are two ordered chains, **High urgency** and **Low urgency**. Each step is "notify <method> after N minutes" (0 to 120, up to 10 steps). A typical high chain: Slack at 0, push at 2, SMS at 5. The whole chain is scheduled when the page reaches the person, and acknowledging cancels the steps that have not fired. If the first method cannot be used, the rest move earlier so the first usable one goes out at once.+- No chain means every enabled, verified method at once. No methods at all means the account email.++## Permissions++| Action | Who |+|---|---|+| View teams, schedules, policies, who is on call | Any organization member |+| Create or edit teams, schedules and policies | Organization owner or admin |+| Create an override | Any organization member |+| Delete an override | Its creator, the person it covers, or an admin |+| View, acknowledge and resolve pages | Anyone with read access to the project |+| Contact methods and notification rules | The person themselves |++## Reading and changing it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| List pages | `traceway pages list [--status active\|open\|acknowledged\|resolved]` | `list_pages` |+| One page with its escalation and delivery log | `traceway pages show <id>` | `get_page` |+| Acknowledge (write) | `traceway-write pages ack <id>` | `acknowledge_page` |+| Resolve, optionally archiving the issue (write) | `traceway-write pages resolve <id> [--archive-issue]` | `resolve_page` |++Teams, schedules, overrides, policies and contact methods are dashboard only, both to read and to change. To answer "who is on call", send the user to **On-Call > Overview**, or to the issue page, which shows the on-call person for that project.diff --git a/skills/traceway-learn/organization.md b/skills/traceway-learn/organization.mdnew file mode 100644index 00000000..fbeae360--- /dev/null+++ b/skills/traceway-learn/organization.md@@ -0,0 +1,90 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/organization.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Organization, projects, access and settings++## Organizations and projects++- An **organization** is the tenant. It owns members and roles, projects, dashboards, teams, schedules, escalation policies and status pages. Nothing is shared across organizations. A user can belong to several, with one role in each.+- A **project** is one application boundary and belongs to exactly one organization. Telemetry is isolated per project, and almost every page is scoped to the current project. Switch projects from the switcher in the top-left header, where projects are grouped under their organization.+- **Frameworks**: a backend project is always **OpenTelemetry**, whatever the language. Browser projects are React, Svelte, Vue.js or jQuery, and mobile projects are Flutter, React Native, Android or iOS. Browser and mobile projects get a smaller sidebar: Issues, Sessions, Alerts, On-Call and Connection, with no endpoints, tasks, spans, logs, profiles, dashboards, AI traces or monitors. Their home page opens Issues.+- **Recommended split**: one backend project for all server-side signals (APIs, workers, schedulers, AI calls, logs, metrics, the host agent), with a distinct `service.name` per process. One project per independently deployed browser app and per independently released mobile app. Prefer more projects over more organizations: the organization views, dashboards, on-call and status pages are all organization-wide.++## Roles++| Role | Access |+|---|---|+| `owner` | Everything, including managing the organization |+| `admin` | Everything in every project, plus members, settings, teams, schedules, policies and status pages |+| `user` | Read and write in the organization's projects |+| `readonly` | Read only. Can still acknowledge and resolve on-call pages and create schedule overrides. |++Admins can override the role per project for `user` and `readonly` members (Settings > Team Members, expand a member). Owners and admins always have full access. The **effective role** on a project is the owner or admin role, else the override, else the organization role. A read-only effective role hides the project token.++A token or agent login never has more access than the person who created it.++## Home page (`/`)++The project's landing page, for backend projects. It answers "is anything wrong right now?":++- **Starred** widgets from dashboards, always over the last 24 hours. They can be reordered, resized and unstarred.+- **Endpoints**: the worst endpoints by impact over 24 hours (Good ones hidden), with Calls, Typical (P50), Slow (P95) and Impact.+- **Issues**: the 10 latest issues in 24 hours, messages excluded.+- A project with no data yet shows **Connect Your Application** with setup steps and **Check Again**. An account with no projects shows **Create Your First Project** with **Set Up Projects**, which opens the guided setup at `/setup`.++From an agent, the same question is the `whats_broken` recipe: recent exceptions, error logs and the worst endpoints by impact.++## Organization views (`/organization`)++For organizations with more than one project: open the organization itself in the switcher. Login lands here when the first organization has several projects. A single-project organization has no organization pages. Every member can open them, read-only included, and they only show projects the person can already see. If one project cannot be read, the rest still render with a notice.++| Page | What it shows |+|---|---|+| **Servers** | Every server reporting metrics in the last 30 minutes, one row per `server_name` per project: CPU, memory, disk, network, last signal, and host, OS, cloud and Kubernetes details. Health: **Critical** (CPU or memory 95% or more, disk 90% or more), **Warning** (CPU 80%, memory 85%, disk 80%), **Stale** (nothing for 3 minutes), **Healthy**. Filter by health and project, group by project or Kubernetes cluster. A row opens that server's dashboard. Needs host metrics from the OTel Agent or a collector. |+| **Issues** | Issues from every project in the range (24 hours by default), with the project, trend, events and last seen |+| **Monitors** | Every monitor with status, 30-day uptime and latency, and the incident history across monitors and status pages (3 months by default) |+| **On-Call** | Pages from every project (1 month by default), filtered by status and searchable, refreshed every minute |+| **Projects** | Every project with its framework and the person's effective access |++Servers and Monitors are hidden when every project is a browser or mobile app.++## Connection (`/connection`)++The setup guide for the current project: the project token, the OTLP endpoint and the snippet for the chosen language and framework. Two tabs:++- **AI**: install the skills with `npx skills add tracewayapp/traceway --all` and paste a ready-made prompt with the URL and token. The `traceway-setup` skill instruments the application.+- **Manual**: step-by-step setup.++Browser and mobile projects also get **Source Map Upload** (browser and Android) or **Symbol Upload** (Flutter and iOS) with an upload token for CI, hidden from read-only members. Regenerating it invalidates the old one.++## Account (`/account`)++Per-person settings:++- **Personal Access Tokens**: name, prefix, access, created, last used, expires. Access is **Read only** (`twp_`, the default, can be non-expiring) or **Read and write** (`tww_`, expires within 1 to 90 days, and only writes where an admin turned on Agent Access). A token is shown once.+- **Contact Methods** and **Notification Rules** for on-call (`on-call.md`).++## Settings (`/settings`, owners and admins)++Stacked sections, with an organization switcher for people who manage several:++- **Organization Details**: the name, and the timezone (**Update Timezone**), which sets the timestamps every member sees and the default for new schedules.+- **Team Members**: name, email, role, status, per-project role overrides. **Pending Invitations**. Invitations carry a role.+- **Agent Access**: the **Allow agent writes** switch and the **Agent activity** log (when, who, credential, project, action, result). See below.++Per-project settings open from the project switcher (**Edit Project**), not from Settings: **Project** (name, framework), **Healthchecks** (drop healthy healthcheck requests, extra healthcheck paths), **Profiles** (extra pprof labels), **AI** (flagged term packs and custom terms), and the **Danger Zone**.++## How agents get access++- The `traceway` CLI and the `/mcp` server are **read only** for product data. The one exception is `traceway setup apply`, which submits an approved project setup plan with a `tws_` setup token. Logins use a browser device flow, `--password`, or a personal access token.+- **Writes are opt in at three levels**, all of which must agree:+ 1. A write credential: a `tww_` token, a `traceway-write` login, or the `/mcp/write` server.+ 2. An organization owner or admin turns on **Settings > Agent Access**.+ 3. The person behind the credential has the role the change needs, as in the dashboard. A `readonly` member can still acknowledge and resolve pages, but not make the other writes.+- Agent credentials only reach the routes the CLI and MCP use. Account, member, token and settings routes refuse them, as do creating rules, channels, monitors, schedules and status pages, and every delete.+- Every agent write, accepted or refused by the switch, is in the agent activity log for 90 days.++The writes agents can make are archiving and unarchiving issues, acknowledging and resolving pages, enabling, disabling and snoozing alert rules, running a monitor, creating and editing post-mortems, and marking an endpoint slow. The `traceway-write` skill covers how to make them safely.++| Task | CLI | MCP tool |+|---|---|---|+| List projects | `traceway projects list` | `list_projects` |+| Pick the current project | `traceway projects use <id>` | the `project_id` param on any tool |diff --git a/skills/traceway-learn/sessions-and-ai.md b/skills/traceway-learn/sessions-and-ai.mdnew file mode 100644index 00000000..4b3bb200--- /dev/null+++ b/skills/traceway-learn/sessions-and-ai.md@@ -0,0 +1,49 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/sessions-and-ai.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Sessions, AI traces and profiles++## Sessions (`/sessions`)++Only in the sidebar of browser and mobile projects. A session is the recording of one user's visit, usually the life of one open tab: what they clicked, typed, scrolled and saw, with the console logs and network calls alongside.++- The browser SDK records sessions when `recordAllSessions: true` is set. Without it, only a short clip from just before each exception is kept, shown on the issue page.+- A session ends after 15 minutes of inactivity, at 60 minutes in total, or when the page unloads. The server does not rely on the closing message arriving: it ends the session at the last activity it saw.+- **Attributes**: the SDK stamps `url`, `path`, `referrer`, `userAgent`, `language`, `platform`, `viewport`, `screen` and `timezone`. The server adds `client.ip`. The app adds its own with `setAttributes` (for example `userId`, `email`, `tenant`).+- **The list**: search a session id, IP or attribute value. Attribute filters use equals (case sensitive), not equals, contains or not contains (case insensitive), and all filters must match. Columns: session, attributes (click one to filter), started, duration, version. Filters are kept in the URL.+- **A session**: started, duration, app version, attributes, the replay player (rrweb for web, video for Flutter) with speed and fullscreen, **Logs** and **Actions** tabs synced to the replay, and **Exceptions in this session**, each linking to its issue.+- From an issue, **View full session** opens the session the exception happened in.++Replay itself is dashboard only. Read: `traceway sessions show <id> --started-at <t>`, MCP `get_session`, which return the session and its exceptions.++## AI traces (`/ai-traces`)++Hidden for browser and mobile projects. One record per LLM call, from any OpenTelemetry span with `gen_ai.*` attributes, whether it is a root span or a child of a request or job (a span that is already an endpoint or task stays one, so model calls belong on their own child spans).++Each call records: model, provider, duration, input, output, cached, reasoning and total tokens, input, output and total cost, finish reason, operation, user id, tool calls, server, version, attributes, its spans and the full conversation (prompt and completion, rendered as a chat).++Three tabs:++| Tab | What it shows |+|---|---|+| **Traces** | Calls grouped by trace name (the agent or workflow): calls, typical and slow duration, total tokens, total cost, last seen. Sorted by cost. A trace name opens tiles (average, median and P95 duration, total cost, total tokens) and its calls (model, tokens in and out, cost, provider), and each call opens its detail. |+| **Conversations** | Calls grouped into conversations: user, turns, tools, models, tokens, cost, last seen. Conversations above the 95th percentile of cost or turns are highlighted. Filter by flagged only, model or tool, and search conversation ids, users, models, tools and flagged terms. A **Flagged terms** button edits the project's terms in place. A conversation opens a chat timeline with tool calls inline, per-turn cost, and a Raw JSON view. |+| **Users** | Searchable. Per user: conversations, calls, median turns, average cost per conversation, total cost, flagged conversations, last seen |++A call's conversation id is `gen_ai.conversation.id`, else `session.id`, else the trace id, so one agent run inside a request still groups its calls.++**Flagged content**: at ingest, prompts and completions are matched (whole word, case insensitive) against the language packs and custom terms chosen in the project settings **AI** tab. Packs: English (default), German, Spanish, French, Italian, Portuguese, Serbian. Custom terms: up to 200, one per line. Changes apply to calls ingested afterwards. Flagged calls carry the matched terms, and the **AI Flagged Content** alert rule can notify on them.++Cost alerts: **AI Trace Cost** for one expensive call, **AI Conversation Cost** for a conversation that gets expensive over 24 hours (`alerts.md`).++Read: `traceway ai-traces show <id> --recorded-at <t>`, MCP `get_ai_trace` (one call with its conversation). Lists, conversations and users are dashboard only.++## Profiles (`/profiles`)++Hidden for browser and mobile projects. Continuous profiles per service. Use them after a waterfall says the time is in the application's own code and the question is which function.++- **The list**: service, profile type, profiles, samples, total, trend, last seen.+- **A service**: profile types CPU, In-Use, Alloc, In-Use Obj, Alloc Obj, Goroutines, Mutex, Block, Wall and Lock (depending on the language). Filter by labels, group by app version or server, and show CPU as cores or per second.+- A trend chart (drag to pick a range), a **flame graph** with search and a collapse-recursion option, a function detail (sandwich) view, and **top functions** with flat and cumulative time.+- **Compare** against a baseline version or server, as a differential flame graph (hotter or cooler) or side by side. This is how to see what a release made slower.+- **Download .pprof** for local tools.++Profiles are dashboard only. There is no CLI or MCP tool.diff --git a/skills/traceway-learn/traces-and-logs.md b/skills/traceway-learn/traces-and-logs.mdnew file mode 100644index 00000000..a2c846d5--- /dev/null+++ b/skills/traceway-learn/traces-and-logs.md@@ -0,0 +1,87 @@+<!-- GENERATED FILE: copied from cli/pkg/mcpserver/knowledge/learn/traces-and-logs.md by cli/tools/skillgen. Edit there and run just gen-skills in cli/. -->+# Spans, traces and logs++## Spans are the primitive++Traceway is OpenTelemetry native. A **trace** is one logical operation (a request, a queued job, an LLM call) as it moves through the system. It is a tree of **spans** that share one **trace id** (32 hex characters). Each span has a span id, a parent span id (empty for a root), a name, a kind (`SERVER`, `CLIENT`, `INTERNAL`, `PRODUCER`, `CONSUMER`), a start time, a duration, a status, attributes and events.++At ingest, some spans are also copied into the tables the list pages read. The copy keeps the span's ids:++| Span | Becomes |+|---|---|+| An HTTP `SERVER` span (or a root `INTERNAL` span with HTTP attributes) that is an entry point: no HTTP server span above it in the same export batch, so nested HTTP spans exported separately can each become an endpoint | An **endpoint** request (`endpoints-and-tasks.md`) |+| A `CONSUMER` span, or a root span with `console.command` | A **task** run |+| A span with `gen_ai.*` attributes, unless it already became an endpoint or task | An **AI trace** (`sessions-and-ai.md`) |+| An `exception` event (or `exception.*` attributes) on any span | An **issue** occurrence (`issues.md`) |+| Everything else | A span in the waterfall |++So an endpoint's waterfall is just the spans of its trace below its own span, and everything connected to it is whatever shares its trace id. An exception belongs to the nearest endpoint, task or AI trace above the span it happened on.++Two rules worth knowing when something seems missing:++- **Span reads are bound to 24 hours** either side of the entity being viewed. A span recorded further away is not shown on that page.+- **Orphans**: a span whose parent never arrived is shown under the trace's root entity, marked "Parent span is unavailable". It nests normally once the parent arrives.++## Spans page (`/spans`)++A search over every span of the project. Hidden in the sidebar for browser and mobile projects.++- **Filters**: span name (contains, case insensitive), service, kind, status (unset, ok, error), minimum and maximum duration, trace id, and up to 10 exact attribute matches (`key = value`).+- **Sort**: start time or duration, either direction.+- **Time range**: defaults to the last 60 minutes, and can be up to 31 days. A search that takes too long answers with a warning to narrow the range or add filters.+- The service filter lists the busiest 100 services in the range.++## The trace page (`/spans/<traceId>`)++The whole trace as one waterfall, across every service and **every project of the organization**, because the services of one trace usually report to different projects. Other organizations stay out.++- Each row names its service. Bars are coloured per service once a trace crosses services, and error spans are marked.+- Clicking a span opens its attributes, service, kind, status and scope. Attributes load when the popover opens.+- Large traces: over 500 spans, any node with more than 50 children starts folded, with a pill counting the hidden spans and an error marker when one of them failed. **Expand all** and **Collapse all** sit in the header. Over the row cap, the page keeps errors first, then entry points, then the slowest spans, and says the trace is partial.+- The trace's logs are listed alongside, from every project of the organization, with a service column.+- The URL needs `?at=` (any time near the trace) and can carry `?span=` to highlight one span.++## Distributed trace card++On endpoint request pages, task run pages and issue events, a **Distributed Trace** card lists every endpoint, task, AI trace and exception that shares the trace id, across the projects the user can open, nested by span parentage. It only appears when there is more than one such node. Each node has a project badge and a **View** button. A browser request and the backend request it called share the trace id through W3C `traceparent` propagation, so they appear together. For the whole span tree, use **Open the whole trace** on the waterfall.++Reading it from an agent: `traceway traces show <trace-id> --recorded-at <t>`, MCP `get_trace`. `--recorded-at` is the timestamp of the occurrence or node the trace id came from.++## Logs (`/logs`)++OpenTelemetry log records with a timestamp, severity, service (`service.name`), body, trace id and span id, and three attribute layers:++- **Resource** attributes describe the process (`service.version`, `host.name`, `deployment.environment`).+- **Scope** attributes describe the logger or instrumentation library.+- **Log** attributes belong to one record (`user.id`, `order.id`).++Severity is a number, grouped into levels: TRACE 1 to 4, DEBUG 5 to 8, INFO 9 to 12, WARN 13 to 16, ERROR 17 to 20, FATAL 21 and up. The severity dropdown is a threshold: `WARN+` keeps warnings and worse.++Filters, which all combine:++- **Search**, by **Message** (the body), **Service** or **Trace ID**. On ClickHouse a single-word body search is a fast whole-word match that is case sensitive (`timeout` does not find `Timeout` or `timeouts`). Anything longer, and every search on SQLite and DuckDB, is a case-insensitive substring match.+- **Severity**: All levels, or a threshold from TRACE+ to FATAL.+- **Attribute filters** (**Add filter**): any `resource.*`, `scope.*` or log attribute key, with equals, not equals, contains or not contains. Not equals is how teams mute a noisy logger. Each filter is a pill, red for exclusions. Expanding a log row lets you click its body, trace id, span id or scope to filter on them.+- **Time range**: presets or custom, 24 hours by default. Results are newest first by default (timestamp, level and service are sortable), and **Load 50 more** fetches more.++Filters are kept in the URL, so a filtered view can be shared.++**Live** turns the page into a live tail. It polls every 5 seconds, prepends new records and keeps up to 2000 rows. It works with preset ranges only, honours every filter, holds the scroll position while reading, and changing the sort stops it.++Structured message templates (Serilog, `Microsoft.Extensions.Logging` and others) are rendered inline: `{Provider}` in the body is replaced by the matching attribute and highlighted. A placeholder with no attribute stays as written.++**Logs and traces**: a log written inside an active span carries that span's trace and span ids. Every endpoint request, task run and AI trace page has a **Logs** panel with that trace's logs from the same project, and the trace page lists them from the whole organization.++Retention: 90 days on ClickHouse. Self-hosted SQLite and DuckDB keep 30 days by default, and an operator can also cap the row count.++## Reading it from an agent++| Task | CLI | MCP tool |+|---|---|---|+| Search logs | `traceway logs query --since 1h [--min-severity 17] [--service S] [--search text] [--trace-id T]` | `query_logs` |+| Logs of one request | `traceway logs query --trace-id <trace-id> --since 24h` | `query_logs` with `trace_id` |+| A whole distributed trace | `traceway traces show <trace-id> --recorded-at <t>` | `get_trace` |++The span explorer and the waterfall attributes popover are dashboard only. For one request's spans, open the endpoint or task request (`get_endpoint_request`, `get_task`), which returns its span waterfall.++A trace id is usually the fastest route to a root cause: one id gives the request, its downstream calls, its logs and its exceptions.diff --git a/skills/traceway/SKILL.md b/skills/traceway/SKILL.mdindex fe8cd19c..2031ecba 100644--- a/skills/traceway/SKILL.md+++ b/skills/traceway/SKILL.md@@ -18,11 +18,13 @@ Drive a Traceway instance from the terminal with the `traceway` CLI. The first w> The CLI is under active development. If a flag documented here does not appear in `traceway <command> --help`, trust the binary.> If a `traceway` MCP server is connected, prefer its tools over shelling out to the CLI: they wrap the same API with the same semantics, and this skill's knowledge is available as its resources. The server is this same binary (`traceway mcp`).+> This skill only reads. To change anything (archive issues, acknowledge or resolve pages, snooze alerts, run monitors, write post-mortems), the user installs the separate `traceway-write` CLI and the `traceway-write` skill.+> When the user asks how a part of Traceway works (schedules, escalation, status pages, alert rules, impact score and the rest), use the `traceway-learn` skill. It is the full product guide.## Ground Rules (All Flows)- **Reads are safe**: any `list` / `show` / `query` subcommand may run freely; they never mutate server state.-- **Writes require explicit user instruction**: `exceptions archive` / `unarchive` are the only mutating data commands; only run them when the user asks by name, with `--yes` in non-interactive contexts. "Look at this error" means read it, not archive it.+- **This CLI is read only**: `traceway` has no mutating commands, and its login can only read. Changes (archiving issues, acknowledging pages, snoozing alerts, editing post-mortems) need the separate `traceway-write` CLI and the `traceway-write` skill. "Look at this error" means read it, never change it.- **Output**: piped output defaults to JSON (table on a TTY). Prefer JSON + `jq`, and `--fields a,b,c` to trim responses. Keep `--page-size` at 10 to 20 for triage.- **Time windows**: always bound queries, default `--since 1h` for "now" questions, `--since 24h` otherwise. `--since` accepts `s`, `m`, `h`, lowercase `Nd` (no `1w`, no `7d2h`). Absolute windows via `--from` / `--to` (RFC3339).- **Exit codes**: 0 ok, 1 generic/API, 2 usage, 3 connection, 4 auth, 5 not found, 6 rate limited, 7 server 5xx. Errors emit `{"error":"<stable_id>","message":"...","hint":"...","exit_code":N}` on stderr; branch on the `error` field.@@ -37,7 +39,7 @@ Users paste dashboard URLs (`https://<instance>/<route>`) as references in any f|---|---|---|| `/issues/<hash>` and `/issues/<hash>/events` | Exception group (hash = 16 hex chars) | `traceway exceptions show <hash>` || `/issues/<hash>/<occurrenceId>` (UUID) | One occurrence within the group | `traceway exceptions occurrence <occurrenceId> --recorded-at <t>` where `t` is the URL's `?t=` param. Direct and fast; also returns the occurrence's `sessionId` and session recording. No URL? get `recordedAt` from `traceway exceptions show <hash>` occurrences |-| `/endpoints/<endpoint>` | Endpoint group; the segment is the URL-encoded endpoint name (`GET%20%2Fapi%2Fusers%2F%3Aid` is `GET /api/users/:id`) | Decode it, then `traceway endpoints list --search "<decoded name>"` (the group has no id; `endpoints show` is for one request — next row) |+| `/endpoints/<endpoint>` | Endpoint group; the segment is the URL-encoded endpoint name (`GET%20%2Fapi%2Fusers%2F%3Aid` is `GET /api/users/:id`) | Decode it, then `traceway endpoints list --search "<decoded name>"` (the group has no id; `endpoints show` is for one request, see the next row) || `/endpoints/<endpoint>/<endpointId>` | One request (transaction) of that endpoint | `traceway endpoints show <endpointId> --recorded-at <t>` (`t` = the URL's `?t=` param). Returns the request, its span waterfall, and any linked exception/messages || `/tasks/<task>` | Background task group | No CLI for the group; for one run use the next row || `/tasks/<task>/<taskId>` | Single task run | `traceway tasks show <taskId> --recorded-at <t>` (`t` = the URL's `?t=` param) |@@ -53,27 +55,27 @@ Users paste dashboard URLs (`https://<instance>/<route>`) as references in any f- `from`/`to` are ISO timestamps; pass via `--from`/`--to`, appending `Z` (or the correct offset) when missing, since the CLI requires RFC3339.- No time params means the page was on its default; pick `--since` per the ground rules.-`preset`/`from`/`to` set the *window* for list/group views. Detail URLs additionally carry **`?t=<iso>`** — the single record's timestamp, URL-encoded. That `t` value is exactly what the by-id commands need as `--recorded-at` (or `--started-at` for sessions). See "Fast by-id lookups" next.+`preset`/`from`/`to` set the *window* for list/group views. Detail URLs additionally carry **`?t=<iso>`**, the single record's timestamp, URL-encoded. That `t` value is exactly what the by-id commands need as `--recorded-at` (or `--started-at` for sessions). See "Fast by-id lookups" next.## Fast by-id lookups (always pass the timestamp)-The by-id detail commands — `exceptions occurrence`, `endpoints show`, `tasks show`, `ai-traces show`, `sessions show`, `traces show` — **require** the record's timestamp (`--recorded-at`, or `--started-at` for sessions). Telemetry tables are partitioned by day: with the timestamp the lookup is bounded to a small window and ClickHouse prunes to a few partitions; without it the server scans every partition (slow cold load). The flag is mandatory for exactly this reason — never omit it. It can be approximate (within ±24h), and you can recover or estimate it when it isn't handed to you; see "When you don't have the timestamp" below.+The by-id detail commands (`exceptions occurrence`, `endpoints show`, `tasks show`, `ai-traces show`, `sessions show`, `traces show`) **require** the record's timestamp (`--recorded-at`, or `--started-at` for sessions). Telemetry tables are partitioned by day: with the timestamp the lookup is bounded to a small window and ClickHouse prunes to a few partitions; without it the server scans every partition (slow cold load). The flag is mandatory for exactly this reason, so never omit it. It can be approximate (within ±24h), and you can recover or estimate it when it isn't handed to you; see "When you don't have the timestamp" below.Where the timestamp comes from, in order of preference:-1. **A dashboard URL** — the `?t=<iso>` param is the record's `recordedAt`; URL-decode it and pass it verbatim. (Sessions have no `t`; use the session start, `from=`, or a linked occurrence's `recordedAt`.)-2. **A list/group you already fetched** — every `exceptions show` occurrence carries `recordedAt`. Capture the id and its `recordedAt` together, then drill in.-3. **A notification** — see below.+1. **A dashboard URL**: the `?t=<iso>` param is the record's `recordedAt`; URL-decode it and pass it verbatim. (Sessions have no `t`; use the session start, `from=`, or a linked occurrence's `recordedAt`.)+2. **A list/group you already fetched**: every `exceptions show` occurrence carries `recordedAt`. Capture the id and its `recordedAt` together, then drill in.+3. **A notification**: see below.Query order when you hold an id: resolve its `recordedAt` first (URL, group, or notification), then call the by-id command with it.### When you don't have the timestamp-The flag is required, so you must supply *something* — but it can be approximate. The lookup window is **±24h** around what you pass (**±48h** for `traces show`), and if the record isn't in that window the server falls back to an unbounded scan. So a timestamp within a day of the truth stays fast; a wrong guess still returns the right record, just slower. Resolve it in this order:+The flag is required, so you must supply *something*, but it can be approximate. The lookup window is **±24h** around what you pass (**±48h** for `traces show`), and if the record isn't in that window the server falls back to an unbounded scan. So a timestamp within a day of the truth stays fast; a wrong guess still returns the right record, just slower. Resolve it in this order:-1. **Recover it from an API.** For an occurrence whose hash you know (e.g. `/issues/<hash>/<occurrenceId>` pasted without `?t=`), run `traceway exceptions show <hash>` and read that occurrence's `recordedAt` — the hash endpoint needs no timestamp. A group's `firstSeen`/`lastSeen` from `exceptions list` bound when its occurrences happened (`lastSeen` ≈ the most recent one).-2. **Estimate from context.** A notification's send time, the issue's `firstSeen`/`lastSeen`, or the URL's `preset`/`from` window all put you inside ±24h — good enough for a fast lookup.-3. **Ask the user.** If nothing pins it down (e.g. a bare occurrence/endpoint id with no hash, no time, and no list to recover from), ask roughly when it happened — "around when did this fire? within a day is enough" — and pass that. Don't invent a placeholder like "now" when the issue is old; that defeats the pruning and can miss the ±24h window entirely.+1. **Recover it from an API.** For an occurrence whose hash you know (e.g. `/issues/<hash>/<occurrenceId>` pasted without `?t=`), run `traceway exceptions show <hash>` and read that occurrence's `recordedAt`. The hash endpoint needs no timestamp. A group's `firstSeen`/`lastSeen` from `exceptions list` bound when its occurrences happened (`lastSeen` ≈ the most recent one).+2. **Estimate from context.** A notification's send time, the issue's `firstSeen`/`lastSeen`, or the URL's `preset`/`from` window all put you inside ±24h. That is good enough for a fast lookup.+3. **Ask the user.** If nothing pins it down (e.g. a bare occurrence/endpoint id with no hash, no time, and no list to recover from), ask roughly when it happened ("around when did this fire? within a day is enough") and pass that. Don't invent a placeholder like "now" when the issue is old; that defeats the pruning and can miss the ±24h window entirely.## Resolving a notification@@ -356,7 +358,6 @@ For free-form requests ("what's broken in prod?", "is /api/checkout slow?", "sho| `traceway exceptions list` | Grouped exceptions; `--search`, `--search-type text\|regex`, `--order-by lastSeen\|firstSeen\|count`, `--include-archived` || `traceway exceptions show <hash>` | One group: full stack trace + occurrences || `traceway exceptions occurrence <id> --recorded-at <t>` | One occurrence by id (fast): full detail + `sessionId` + recording |-| `traceway exceptions archive/unarchive <hash>...` | Mutating; explicit user request + `--yes` only || `traceway logs query` | Logs; `--search` (`--search-type body\|attribute`), `--service`, `--min-severity <n>`, `--trace-id` || `traceway endpoints list` | Per-endpoint p50/p95/p99 and counts; `--search`, `--order-by impact\|count\|p95\|lastSeen` || `traceway endpoints chart` | Latency over time for the top endpoints; `--metric-type total_time\|p50\|p95\|p99`, `--interval-minutes`. Use to find when latency changed |@@ -367,6 +368,10 @@ For free-form requests ("what's broken in prod?", "is /api/checkout slow?", "sho| `traceway sessions show <id> --started-at <t>` | One session by id + the exceptions that fired in it || `traceway traces show <id> --recorded-at <t>` | Distributed trace: every service node sharing the id || `traceway metrics query --name <metric>` | Time series; `--aggregation`, `--tag`, `--group-by`, `--interval-minutes` |+| `traceway pages list` / `pages show <id>` | On-call pages; `--status active\|open\|acknowledged\|resolved` |+| `traceway alerts list` | Alert rules: type, enabled, snoozed until |+| `traceway monitors list` / `monitors show <id>` | Uptime monitors, their status and incidents |+| `traceway post-mortems list` / `post-mortems show <id>` | Post-mortem documents; `--search`, `--tag` || `traceway profiles {list,use}`, `login`, `logout`, `version` | Profile and session management |The by-id `show`/`occurrence` commands take their id from a dashboard URL, a notification, or an `exceptions show` occurrence — and **require** the record's timestamp (`--recorded-at` / `--started-at`); see "Fast by-id lookups" above.diff --git a/website/app/product/agent-skills/page.tsx b/website/app/product/agent-skills/page.tsxindex 1dd3b16a..298e9dca 100644--- a/website/app/product/agent-skills/page.tsx+++ b/website/app/product/agent-skills/page.tsx@@ -36,6 +36,20 @@ const SKILLS = ["Installs the traceway CLI, then uses it: exceptions, logs, endpoints, and metrics, from bug report to root cause.",tags: ["CLI install", "Telemetry queries", "Debugging", "Issue triage"],},+ {+ label: "03 · Learn",+ name: "/traceway-learn",+ description:+ "The full guide to Traceway: issues, endpoints, traces, logs, monitors, status pages, alerts and on-call. Ask how anything works and get the answer.",+ tags: ["Product guide", "On-call", "Status pages", "Alert rules"],+ },+ {+ label: "04 · Operate",+ name: "/traceway-write",+ description:+ "Lets your agent act, not just read: archive issues, acknowledge pages, snooze rules, run monitors and draft post-mortems. Needs the write CLI and an admin opt-in.",+ tags: ["Write CLI", "On-call actions", "Post-mortems", "Admin opt-in"],+ },];const AGENTS = [@@ -233,11 +247,12 @@ export default function AgentSkillsPage() {<section className="wrap py-8"><Eyebrow>The skills</Eyebrow><h2 className="mt-4 max-w-[24ch]">- Two skills, <em>one install.</em>+ Four skills, <em>one install.</em></h2><p className="muted mt-4 max-w-[640px] text-pretty">Plain Markdown playbooks your agent loads on demand. One sets up- your project, the other queries and debugs it.+ your project, one queries and debugs it, one explains how every+ part of Traceway works, and one lets your agent take action.</p><dl className="mt-14 grid gap-6 md:grid-cols-2">@@ -361,7 +376,7 @@ export default function AgentSkillsPage() {items={[{q: "What exactly is an agent skill?",- a: "A SKILL.md file: Markdown instructions your agent loads when a task matches. Traceway ships two, one that sets up a project and one that queries and debugs it. Both live in the open-source repo.",+ a: "A SKILL.md file: Markdown instructions your agent loads when a task matches. Traceway ships four: one sets up a project, one queries and debugs it, one explains how every part of Traceway works, and one makes changes once an admin allows it. All four live in the open-source repo.",},{q: "Which agents are supported?",@@ -372,7 +387,7 @@ export default function AgentSkillsPage() {Codex, OpenCode, Gemini CLI, Copilot, and more.</p><p>- <code>npx skills add tracewayapp/traceway</code>{" "}+ <code>npx skills add tracewayapp/traceway --all</code>{" "}installs the skills for every agent it finds on yourmachine.</p>@@ -381,7 +396,7 @@ export default function AgentSkillsPage() {},{q: "Can an agent damage my production data?",- a: "No. The CLI is read-only apart from archiving exception groups, and that requires an explicit --yes flag.",+ a: "No. The traceway CLI only reads. The install also adds the traceway-write skill, but it changes nothing on its own: writes need the separate traceway-write CLI or a write token, and an organization admin who turned on Agent Access.",},{q: "Does this work with self-hosted Traceway?",diff --git a/website/app/product/cli/page.tsx b/website/app/product/cli/page.tsxindex d573faed..e1464508 100644--- a/website/app/product/cli/page.tsx+++ b/website/app/product/cli/page.tsx@@ -133,6 +133,8 @@ export default function CliPage() {</p><ul className="feat-bullets"><li>Exceptions, logs, endpoints, tasks, traces, metrics</li>+ <li>On-call pages, alert rules, monitors, post-mortems</li>+ <li>Read only. Writes need the separate traceway-write CLI</li><li>Tables on a TTY, JSON when piped</li><li>--fields trims responses to what was asked</li><li>Stable error identifiers and exit codes</li>diff --git a/website/app/product/mcp/page.tsx b/website/app/product/mcp/page.tsxindex c77d5dee..2315171c 100644--- a/website/app/product/mcp/page.tsx+++ b/website/app/product/mcp/page.tsx@@ -28,8 +28,6 @@ const TOOL_GROUPS = ["list_exceptions","get_exception","get_exception_occurrence",- "archive_exceptions",- "unarchive_exceptions",],},{@@ -52,10 +50,37 @@ const TOOL_GROUPS = ["get_trace",],},+ {+ label: "Operations",+ tools: [+ "list_pages",+ "get_page",+ "list_notification_rules",+ "list_checks",+ "get_check",+ "list_post_mortems",+ "get_post_mortem",+ ],+ },{label: "Projects",tools: ["list_projects"],},+ {+ label: "Write server, opt-in",+ tools: [+ "archive_exceptions",+ "unarchive_exceptions",+ "acknowledge_page",+ "resolve_page",+ "set_notification_rule_enabled",+ "snooze_notification_rule",+ "run_check",+ "create_post_mortem",+ "update_post_mortem",+ "set_slow_endpoint",+ ],+ },];export default function McpPage() {@@ -248,15 +273,17 @@ export default function McpPage() {<section className="wrap py-8"><Eyebrow>The tools</Eyebrow><h2 className="mt-4 max-w-[22ch]">- Sixteen tools. <em>Read-only by default.</em>+ Twenty-one read tools. <em>Writes are opt-in.</em></h2><p className="muted mt-4 max-w-[640px] text-pretty">Each tool wraps one API call and declares an output schema, so- results come back as validated structured content. Only the two- archive tools mutate anything, and only when you ask for it by name.+ results come back as validated structured content.{" "}+ <code>/mcp</code> only reads. The ten write tools live on a separate+ server, <code>/mcp/write</code>, for teams that want an agent to+ acknowledge pages, snooze alerts or write post-mortems.</p>- <dl className="mt-14 grid gap-6 sm:grid-cols-2 lg:grid-cols-4">+ <dl className="mt-14 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">{TOOL_GROUPS.map((group) => (<divkey={group.label}@@ -293,12 +320,12 @@ export default function McpPage() {<FeatureCardicon={<ShieldCheck className="h-5 w-5" />}title="Safe by default"- body="Every read tool is annotated read-only. Archiving needs an explicit request; investigating an error never touches it."+ body="/mcp never lists a write tool. /mcp/write needs a write token, an organization admin's opt-in and the role the change needs, and every agent write lands in an audit log."/><FeatureCardicon={<Boxes className="h-5 w-5" />}title="Prompts and resources"- body="The same investigation playbooks the Traceway skill ships, exposed as MCP prompts (debug_issue, investigate_performance) and knowledge resources."+ body="The same playbooks the Traceway skills ship, exposed as MCP prompts (debug_issue, investigate_performance) and knowledge resources, including a full guide to every part of Traceway."/><FeatureCardicon={<Lock className="h-5 w-5" />}@@ -392,11 +419,11 @@ export default function McpPage() {},{q: "Can an agent change my production data?",- a: "Only exception groups can be archived, and only with the archive tools, which are marked mutating and instruct agents to call them solely on explicit request. Everything else is read-only.",+ a: "Not through /mcp, which only reads. The separate /mcp/write server can archive issues, acknowledge and resolve pages, snooze or toggle alert rules, run monitors, write post-mortems and mark slow endpoints. It needs a write token, an organization admin has to turn on Agent Access, and every write is recorded. Deletes, settings, rules and channels stay in the dashboard.",},{q: "Does it work with self-hosted Traceway?",- a: "Yes. Every backend serves /mcp, and the OAuth issuer is derived from the request, so it works behind a reverse proxy with no extra configuration.",+ a: "Yes. Every backend serves /mcp and /mcp/write, and the OAuth issuer is derived from the request, so it works behind a reverse proxy with no extra configuration.",},{q: "Which clients are supported?",diff --git a/website/components/skill-install-command.tsx b/website/components/skill-install-command.tsxindex 6ff5f005..13462682 100644--- a/website/components/skill-install-command.tsx+++ b/website/components/skill-install-command.tsx@@ -4,7 +4,7 @@ import { useState } from "react";import { Check, Copy } from "lucide-react";import { cn } from "@/lib/utils";-const COMMAND = "npx skills add tracewayapp/traceway";+const COMMAND = "npx skills add tracewayapp/traceway --all";export function SkillInstallCommand({className,