The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
Migrate traceway-cli into monorepo as /cli
Fred Drake88831ea3ee83
diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.ymlnew file mode 100644index 00000000..88fc2ec3--- /dev/null+++ b/.github/workflows/cli.yml@@ -0,0 +1,37 @@+name: CLI++on:+ push:+ branches: [main]+ paths:+ - "cli/**"+ - ".github/workflows/cli.yml"+ pull_request:+ paths:+ - "cli/**"+ - ".github/workflows/cli.yml"++permissions:+ contents: read++jobs:+ build-test:+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: cli+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Go+ uses: actions/setup-go@v5+ with:+ go-version-file: cli/go.mod+ cache-dependency-path: cli/go.sum++ - name: Build+ run: go build ./...++ - name: Test+ run: go test ./...diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.ymlnew file mode 100644index 00000000..0e69e0a5--- /dev/null+++ b/.github/workflows/release-cli.yml@@ -0,0 +1,139 @@+name: Release CLI++on:+ workflow_dispatch:+ inputs:+ version:+ description: "Release version (X.Y.Z, no leading v)"+ required: true+ type: string+ change_1:+ description: "Changelog item 1 (optional)"+ required: false+ type: string+ change_2:+ description: "Changelog item 2 (optional)"+ required: false+ type: string+ change_3:+ description: "Changelog item 3 (optional)"+ required: false+ type: string+ change_4:+ description: "Changelog item 4 (optional)"+ required: false+ type: string+ change_5:+ description: "Changelog item 5 (optional)"+ required: false+ type: string++permissions:+ contents: write++jobs:+ release:+ runs-on: ubuntu-latest+ steps:+ - name: Validate version format+ run: |+ if ! [[ "${{ inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ echo "Error: version must be in X.Y.Z format (got '${{ inputs.version }}')"+ exit 1+ fi++ - name: Checkout+ uses: actions/checkout@v4+ with:+ fetch-depth: 0+ token: ${{ secrets.RELEASE_TOKEN }}++ - name: Check tag does not already exist+ run: |+ TAG="cli/v${{ inputs.version }}"+ if git rev-parse "$TAG" >/dev/null 2>&1; then+ echo "Error: tag $TAG already exists"+ exit 1+ fi++ - name: Setup Go+ uses: actions/setup-go@v5+ with:+ go-version-file: cli/go.mod+ cache-dependency-path: cli/go.sum++ - name: Build cross-platform binaries+ working-directory: cli+ env:+ VERSION: ${{ inputs.version }}+ CGO_ENABLED: "0"+ run: |+ set -euo pipefail+ mkdir -p dist+ # OS ARCH LABEL — LABEL is the user-facing arch name in the archive filename+ PAIRS=(+ "linux amd64 x86_64"+ "linux arm64 arm64"+ "darwin amd64 x86_64"+ "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 -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+ done+ rm -rf dist/staging+ ls -la dist++ - name: Generate checksums+ working-directory: cli/dist+ run: |+ sha256sum * > checksums.txt+ cat checksums.txt++ - name: Configure git+ run: |+ git config user.name "github-actions[bot]"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"++ - name: Tag release+ run: git tag "cli/v${{ inputs.version }}"++ - name: Push tag+ run: git push origin "cli/v${{ inputs.version }}"++ - name: Create GitHub Release+ env:+ GH_TOKEN: ${{ github.token }}+ C1: ${{ inputs.change_1 }}+ C2: ${{ inputs.change_2 }}+ C3: ${{ inputs.change_3 }}+ C4: ${{ inputs.change_4 }}+ C5: ${{ inputs.change_5 }}+ run: |+ NOTES=""+ for C in "$C1" "$C2" "$C3" "$C4" "$C5"; do+ if [ -n "$C" ]; then+ NOTES="${NOTES}- ${C}"$'\n'+ fi+ done+ if [ -z "$NOTES" ]; then+ NOTES="CLI v${{ inputs.version }}"+ fi+ gh release create "cli/v${{ inputs.version }}" \+ --title "CLI v${{ inputs.version }}" \+ --notes "$NOTES" \+ cli/dist/*diff --git a/CLAUDE.md b/CLAUDE.mdindex 801cb727..bfe6a6d1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7,6 +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`)- **Go Client SDK**: Distributed tracing SDK for Go applications (external repo)---@@ -28,11 +29,16 @@ Traceway is an error tracking and monitoring platform consisting of:| Frontend | `npm run build` | Production build || Frontend | `npm run check` | TypeScript checking || Backend | `cd backend && go run .` | API server (port 8082) |+| CLI | `cd cli && just build` | Builds `bin/traceway` |+| CLI | `cd cli && just test` | Runs unit tests |+| CLI | `cd cli && just check` | Lint + test + vulncheck (pre-commit gate) |+| CLI | `cd cli && just smoke-test` | Live E2E (needs `TRACEWAY_SMOKE_*` env vars) || Go Client | External repo at `/Users/dusanstanojevic/Documents/workspace/go-client` | Build with `go build ./...` |### Tech Stack- **Frontend**: SvelteKit 2.49, Svelte 5.45, Tailwind CSS v4, shadcn-svelte, Vite 7- **Backend**: Go 1.25, Gin 1.11, ClickHouse, PostgreSQL+- **CLI**: Go 1.26, Cobra 1.10, separate Go module (`github.com/tracewayapp/traceway/cli`); flake.nix dev shell, justfile entrypoints- **Client SDK**: Go 1.25, Gin middleware support### go-lightning Library (PostgreSQL ORM)diff --git a/cli/.claude/skills/integration-test/SKILL.md b/cli/.claude/skills/integration-test/SKILL.mdnew file mode 100644index 00000000..89a41f64--- /dev/null+++ b/cli/.claude/skills/integration-test/SKILL.md@@ -0,0 +1,179 @@+---+name: integration-test+description: Run a live-instance verification of traceway-cli that goes beyond the Go smoke suite — exercises real-data detail endpoints, TTY-default rendering, adaptive metric-name discovery, and emits a human-readable coverage report. Invoke ONLY when the user explicitly asks (e.g. "run integration tests", "verify the CLI against stormwind"). Never invoke automatically after edits or commits. Assumes the user is already authenticated and a default project is configured.+---++# integration-test — traceway-cli++A repeatable protocol for verifying the CLI end-to-end against a live Traceway server, focused on the things the Go smoke suite can't easily cover.++## Trigger++Invoke ONLY when the user explicitly asks. Never run as a side effect of edits, commits, or builds.++## Relationship to the Go smoke suite++The `just smoke-test` target (`test/smoke/*_test.go`, build tag `smoke`) is the primary regression check. Against a live instance it already covers:++- JSON shape of every list endpoint and `profiles list`.+- Output-format coverage (json/table/yaml) for projects, profiles, exceptions, endpoints, logs.+- Client-side enum validation (`--search-type`, `--order-by`, `--sort-direction`, `--aggregation`, `--tag`).+- Time-range parsing edges (`--since 7D`, missing `--to`, `--since` + absolute mix, far-future windows).+- `metrics query` missing `--name`, bogus name → empty series, malformed tag.+- `exceptions show <zeros>` → exit 5 `not_found`.+- `--profile no-such-profile` → exit 4; `--project 0…0` → non-zero, no panic, no `connection_failed`.++**Do not re-implement these here.** If they regress, that's a Go-test bug, not a skill failure.++What this skill adds beyond `just smoke-test`:++1. **Real-data detail endpoints** — `exceptions show <captured-hash>`, populated `metrics query --name <real>` with every aggregation + group-by.+2. **Adaptive metric-name discovery** — walk a candidate list until one populates.+3. **TTY-vs-pipe default** — table rendering to a real terminal.+4. **Coverage matrix report** — a human-readable artifact, on demand.+5. **Safety doctrine** — the forbidden-verb blocklist and `confirmMutation` env hygiene, applied to every probe.++## Hard constraints++**Read-only. No exceptions.** Even if a subcommand looks safe by name, check `--help` for mutating flags before running.++### Forbidden verbs and flags++Skip any subcommand whose name or `--help` mentions:++- `archive`, `unarchive`, `resolve`, `unresolve`, `mute`, `ack`, `acknowledge`+- `create`, `delete`, `update`, `set`, `put`, `post`, `add`, `remove`, `rm`+- `assign`, `claim`, `close`, `reopen`+- `login`, `logout`, `token`, `rotate`, `regenerate`+- `--archive`, `--resolve`, `--delete`, `--write`, `--mutate`, `--apply`, `--commit`++If a new subcommand is ambiguous (`sync`, `refresh`, `replay`, `export`), do not run it — list it under "skipped — manual review". If `--dry-run` exists, **still skip** write-shaped subcommands.++### Mutation safeguards++The CLI gates mutations via `confirmMutation` (`cmd/traceway/querycommon.go`). The harness MUST:++- Never pass `--yes`.+- `unset TRACEWAY_ASSUME_YES` at the top of the script.+- Run with stdin from `/dev/null`.++So that if a forbidden verb slips through, the gate refuses with exit 2 `usage_error` instead of hanging on a prompt.++## Pre-flight++Run in order. Stop if any fails.++1. Build: `nix develop --command go build -o ./bin/traceway ./cmd/traceway`.+2. Config exists (don't print — JWT inside): `test -f "${XDG_CONFIG_HOME:-$HOME/.config}/traceway/config.json"`.+3. Reachability + capture `TW_PROJECT_ID`:+ ```bash+ ./bin/traceway projects list --output json | jq -e 'type=="array" and length>=1' >/dev/null+ TW_PROJECT_ID=$(./bin/traceway projects list --output json | jq -r '.[0].id')+ ```++`projects list --output json` returns a **bare array**, not a `{data, pagination}` envelope.++## Detail-endpoint probes++### `exceptions show <captured-hash>`++1. Capture a real hash:+ ```bash+ HASH=$(./bin/traceway exceptions list --since 720h --page-size 1 --output json | jq -r '.data[0].exceptionHash // empty')+ ```+ If empty, retry against other projects via `--project <id>`. If still empty, skip with reason `no exception found across all projects`.+2. With a real hash: three output formats + `--help`. JSON shape: `{group: {...}, occurrences: [...], pagination: {...}}` — assert `.group and .occurrences`.+3. Capture `.occurrences[0].traceId` if present for the logs probe below.++### `metrics query --name <real-metric>` (adaptive)++Probe these names in order until one returns a populated `series`:++```+system.cpu.utilization+system.network.io+system.network.errors+system.network.dropped+http.server.duration+traceway.requests+```++If none populates, skip the live block with reason `no live metric name found`.++For the first metric that populates:++- Three output formats + `--help`.+- All aggregations: `avg`, `sum`, `count`, `min`, `max`, `p50`, `p95`, `p99`.+- `--interval-minutes 15`.+- `--group-by direction` for network metrics (splits `__all__` into `receive`/`transmit`).++JSON shape: `{results: [{name, unit, series: {<tag-key>: [{timestamp, value}, ...]}}]}` — `series` is a map keyed by group tag, default key `__all__`.++### `logs query --trace-id <captured>`++If a real trace id was captured above, run `logs query --trace-id $TRACE --since 720h`. Assert exit 0 and `{data, pagination}` shape.++## TTY-vs-pipe default++If `script` is available:+```bash+script -q /dev/null ./bin/traceway projects list | head -20+```+Expect a table. Piping without `script` should yield JSON. Mark as "not verified" if `script` is absent.++## Subcommand skip lists++Mutating (skip with reason `forbidden verb`):+`exceptions archive`, `exceptions unarchive`, `login`, `logout`, `profiles use` (local mutation), `projects use` (local mutation of `state.json`).++Not in the CLI (skip with reason `subcommand not in CLI`) — kept so the report shows the gap if they ship:+`endpoints show`, `sessions list`, `sessions show`, `traces show`, `ai-traces list`, `ai-traces show`.++## Observation and reporting++Classify each invocation:++| Result | Classification |+|---|---|+| exit 0, valid JSON, expected keys present | **pass** |+| exit 0 but stdout empty when data expected, or JSON invalid / missing keys | **fail — schema** |+| exit non-zero, clean message, expected error | **pass — error case** |+| exit non-zero with panic or stack trace | **fail — crash** |+| exit non-zero on a happy path | **fail — unexpected error** |+| stderr non-empty on a passing command | **warn — noisy** |+| > 10s on a list call | **warn — slow** |++Drive the run from one ephemeral `/tmp/*.sh` script (not committed). Top of script:++```bash+#!/usr/bin/env bash+set -u # never set -e+unset TRACEWAY_ASSUME_YES+exec </dev/null # no TTY for the suite+LOG=$(mktemp /tmp/traceway-it.XXXXXX.log)+```++Capture exact invocation, exit code, and first 20 lines of stdout/stderr per probe to `$LOG`.++End-of-run markdown report:++1. **Summary**: `N pass, M fail, W warn, S skipped` + wall-clock.+2. **Failures table**: command, classification, one-line excerpt.+3. **Warnings table**: same shape.+4. **Skipped table**: command + reason.+5. **Coverage matrix**: dimensions exercised per probed command (`—` for not exercised).+6. **Smoke-suite pointer**: note whether `just smoke-test` was run in this session and its result, so the report stands alone.+7. **Log path**: location of `$LOG`.++Do not inline the full log.++## What this skill does not do++- It does not duplicate `just smoke-test`. Assume that suite's coverage is green; if you suspect regressions there, run smoke separately.+- It does not write or update the CLI's Go test files.+- It does not perform any login, token rotation, profile creation, or credential mutation.+- It does not gate commits or CI.++## When to expand++If a new read subcommand ships, add a probe block. If a new mutating subcommand ships, add it to the forbidden list. If a regression pattern shows up that is deterministic and stateless, push it down to `test/smoke/*_test.go` — not into this skill.diff --git a/cli/.claude/skills/traceway-cli.md b/cli/.claude/skills/traceway-cli.mdnew file mode 100644index 00000000..7814ef99--- /dev/null+++ b/cli/.claude/skills/traceway-cli.md@@ -0,0 +1,345 @@+---+name: traceway-cli+description: How to use the `traceway` CLI to query a Traceway observability instance (exceptions, logs, distributed traces, metrics, endpoints, sessions). Use whenever the user asks about errors, exceptions, crashes, logs, latency, slow endpoints, performance, traces, spans, metrics, sessions, or "what's broken in prod". Assumes the user is already authenticated and a default project is configured — do not run `traceway login` unprompted. Read operations are safe to run freely; write operations require explicit user instruction.+---++# Using the traceway CLI++`traceway` is a command-line client for [Traceway](https://github.com/tracewayapp/traceway), an open-source observability platform (OpenTelemetry-native: logs, metrics, distributed traces, exception tracking, session replay). This skill teaches you how to drive the CLI productively.++> The CLI is under active development. If a documented flag here doesn't appear in `traceway <command> --help`, trust the binary, not this doc, and tell the user the doc is stale.++## When to invoke this skill++Invoke whenever the user's request involves looking *into* their running systems for diagnostic information:++- "What's erroring in prod right now?"+- "Show me the stack trace for the last 5 occurrences of X"+- "Why is `/api/checkout` slow?"+- "Find logs around trace `abc...`"+- "Did the deploy at 14:00 break anything?"+- "Pull the trace for request `xyz`"+- "What metrics are above their normal range?"++Do **not** invoke for:+- Generic Go/programming questions+- Questions about Traceway as a product (architecture, pricing) — those aren't CLI work+- Setting up credentials or first-time login++## Read vs write — default posture++**Read operations are safe.** You may run any of the query/list/show subcommands without asking, including with broad time windows or pagination. They never mutate server state.++**Write operations require explicit user instruction.** Subcommands that archive, resolve, mute, acknowledge, or otherwise change server state must be requested by name. Do not infer "the user wants this archived" from context. If the user says "look at this exception", they want to read it, not resolve it.++## Top-level invocation++```+traceway [global-flags] <subcommand> [subcommand-flags] [args]+```++### Global flags (apply everywhere)++| Flag | Purpose |+|---|---|+| `--profile <name>` | Select a credential/base-url profile from `~/.config/traceway/config.json` (singular file — both auth and profile metadata live there). Omit to use the current profile. |+| `--project <id>` | Override the configured project. Most commands need a project; assume the current profile has one set. |+| `--output json\|table\|yaml` | Output format. Default is **table when stdout is a TTY, JSON otherwise.** When you pipe through `jq` or capture output, JSON is automatic — you rarely need to set this flag. |+| `--fields <a,b>` | Comma-separated field projection for table/JSON output (e.g. `--fields id,name`). |+| `--yes` | Skip confirmation for mutating commands. Don't pass this unless the user explicitly asked you to mutate. |+| `--help` / `-h` | Print help. |++> The CLI currently has **no** `--base-url` or `--verbose`/`-v` global flag. If you need a different server, switch profiles. If a call returns empty, widen the time window or re-check the project — the CLI doesn't expose HTTP-level tracing.++### Output format guidance for LLM use++- **Always prefer JSON.** Pipe it into `jq` and pull only the fields you need. This keeps context small.+- Avoid `--output table` when capturing output programmatically — column widths and headers will inflate your context window.+- Use `--output yaml` only when the user explicitly asks; it's for humans.++## Subcommand reference++The CLI is organized by resource. Most resources have `list` (paginated search) and `show <id>` (detail) verbs.++### `projects`++List the projects available on the server. Useful for discovering project IDs when the user has more than one project or when no default is configured.++```+traceway projects list+```++The JSON form returns a **bare array** (no `data`/`pagination` envelope, unlike most other list endpoints). Currently observed fields: `id` (uuid), `name`. Other metadata you might expect (`slug`, `createdAt`, etc.) is not exposed by this subcommand yet.++You usually do **not** need this — the default profile has a project already. Only run it when:+- The user says "what projects are there?"+- A query fails with "no project configured" and you need to pick one.++### `exceptions` — the most-used subcommand++Grouped exception/error tracking. Each "group" is identified by a stack-trace hash. The list endpoint returns groups; the show endpoint returns occurrences within a group.++```+traceway exceptions list [--from RFC3339] [--to RFC3339] [--since 1h]+ [--search "pattern"] [--search-type text|regex]+ [--include-archived]+ [--order-by lastSeen|firstSeen|count]+ [--page 1] [--page-size 50]+```++Time window:+- Prefer `--since 1h` / `--since 24h` for relative windows. Default to `--since 1h` if the user says "right now" or "recently".+- `--since` accepts `s`, `m`, `h`, and `Nd` units (`7d` works and is parsed client-side as `7 * 24h`). Compound forms like `7d2h` are not accepted. Capital `D` (`7D`) exits 2 with `invalid_time_range`.+- Use `--from` / `--to` for absolute windows. Both are RFC3339 (`2026-05-15T10:00:00Z`).++Pagination: `--page` defaults to `1` and `--page-size` to `50`. Bare invocations like `exceptions list --since 24h` succeed without any pagination flags. Passing `--page 0` is still rejected server-side with HTTP 400 (the CLI passes the bad value through unchanged).++Result shape (JSON):+```jsonc+{+ "data": [+ {+ "exceptionHash": "9a8b...",+ "stackTrace": "...", // top of stack; full trace via `show`+ "count": 142,+ "firstSeen": "2026-05-13T...",+ "lastSeen": "2026-05-14T...",+ "hourlyTrend": [{ "timestamp": "...", "count": 7 }]+ }+ ],+ "pagination": { "page": 1, "pageSize": 50, "total": 312, "totalPages": 7 }+}+```++```+traceway exceptions show <exceptionHash> [--page 1] [--page-size 20]+```++Returns the exception group plus an array of recent `occurrences`. Each occurrence has at least `recordedAt`, `attributes`, and optional `distributedTraceId` / `sessionId` (verify the exact shape against your build — schema is still settling). A bogus hash exits with code `5` and `not_found`.++**Forbidden without explicit instruction:** `exceptions archive` and `exceptions unarchive`. These are the only mutating exception subcommands in the current CLI — there is no `resolve` / `mute` yet.++### `logs`++Full-text + structured search across logs.++```+traceway logs query [--from RFC3339] [--to RFC3339] [--since 1h]+ [--search "pattern"] [--search-type body|attribute]+ [--service <name>]+ [--min-severity <uint8>] # OTel severity number, see table+ [--trace-id <uuid>]+ [--order-by timestamp] [--sort-direction asc|desc]+ [--page 1] [--page-size 50]+```++**Severity is a number, not a name.** The flag is `--min-severity`, not `--severity`, and it takes an OpenTelemetry severity number. Mapping:++| Severity | Number |+|------------|--------|+| `TRACE` | 1 |+| `DEBUG` | 5 |+| `INFO` | 9 |+| `WARN` | 13 |+| `ERROR` | 17 |+| `FATAL` | 21 |++So "errors and above" is `--min-severity 17`. Do **not** write `--severity error` — that flag does not exist and the CLI will refuse it.++The current CLI does not have a `--attr key=value` filter — attribute-based filtering is done via `--search ... --search-type attribute`.++Result shape: `{data: [...] | null, pagination: {page, pageSize, total, totalPages}}`. When data is present, rows have at least `timestamp`, OTel severity fields, body, and a `traceId` if attached. Empty results come back as `data: null`, not `[]`.++Recipe — pull logs around an exception:+```bash+traceway exceptions show $HASH --output json | jq -r '.occurrences[0].distributedTraceId' \+ | xargs -I{} traceway logs query --trace-id {} --page 1 --output json+```++### `endpoints` — HTTP endpoint performance++```+traceway endpoints list [--since 24h]+ [--search "/api/"]+ [--order-by impact|count|p95|lastSeen]+ [--sort-direction asc|desc]+ [--page 1] [--page-size 50]+```++Returns endpoints with latency percentiles and request counts. Best for "what's slow?" questions.++There is **no `endpoints show` subcommand** in the current CLI — only `list`. If a user asks for a per-endpoint breakdown, use `--search "<endpoint-name>"` against `list`.++Note `--order-by` does not include `p99`, `errorRate`, or `requests` as choices — the only sort fields right now are `impact`, `count`, `p95`, `lastSeen`. The default (`impact`) is usually what you want.++Recipe — find the worst endpoint right now:+```bash+traceway endpoints list --since 1h --order-by p95 --page 1 --page-size 1 --output json \+ | jq '.data[0]'+```++### `metrics`++Custom metric queries. Traceway does not have a query DSL like PromQL — instead, you specify metric name + aggregation + filters + groupBy as flags.++```+traceway metrics query --name <metric.name>+ [--aggregation avg|sum|count|min|max|p50|p95|p99]+ [--from RFC3339] [--to RFC3339] [--since 1h]+ [--interval-minutes <n>]+ [--tag key=value] # repeatable, exact match filter+ [--group-by <tag>] # one tag only+```++`--name` is required; omitting it exits with code 2 and `usage_error`.++**There is no `metrics list` / `metrics discover` subcommand.** The CLI cannot enumerate available metric names — the user has to provide one, or you have to guess from OpenTelemetry semantic conventions. Names observed live: `system.cpu.utilization`, `system.network.io`, `system.network.errors`, `system.network.dropped`. If the user is checking system telemetry, those four are the likeliest starting points; if they're checking app-level metrics, ask.++A bogus metric name returns exit 0 with `series: {}` (clean empty, not an error). Use that to probe whether a name exists.++`--aggregation <invalid-value>` exits 2 with `usage_error` (client-side enum validation). The other enum flags — `--search-type`, `--order-by`, `--sort-direction` — behave the same way: invalid values exit 2 before the request leaves the client.++Result shape — `series` is a **map keyed by group tag**, not an array:+```jsonc+{+ "results": [+ {+ "name": "system.network.io",+ "unit": "By",+ "series": {+ "__all__": [{ "timestamp": "2026-05-14T10:00:00-04:00", "value": 88645480308.55 }]+ }+ }+ ]+}+```++With `--group-by direction` on a network metric, the `series` keys become `"receive"` and `"transmit"` instead of `"__all__"`.++### Subcommands the CLI does not currently have++These are commonly requested but **not implemented** in the current binary. If a user asks for them, say so — don't fabricate flags.++- `traces show <traceId>` — span waterfall view. Trace IDs in `logs query` / `exceptions show` output are currently link-only.+- `sessions list` / `sessions show` — session replay listings.+- `ai-traces list` / `ai-traces show` — LLM observability.+- `endpoints show <name>` — per-endpoint detail (use `endpoints list --search`).+- `metrics list` / `metrics discover` — metric-name enumeration.++### `login` / `logout`++```+traceway login [--profile <name>]+traceway logout [--profile <name>]+traceway profiles use <name>+```++`login` prompts for base URL, email, password and stores a JWT in `~/.config/traceway/config.json`. `logout` removes a profile's stored credentials. `profiles use` switches the *local* current profile.++**Do not run any of these unprompted.** If a query returns 401 / "unauthorized" / "token expired", tell the user the session expired and ask them to run `traceway login`. Do not run it yourself. The same applies to `logout` and `profiles use` — even though `profiles use` only mutates local config, it can silently redirect every subsequent query to a different server.++## Common workflows++### "What's broken in prod right now?"++```bash+traceway exceptions list --since 1h --order-by lastSeen \+ --page 1 --page-size 10 --output json \+ | jq '.data[]? | {hash: .exceptionHash, count, lastSeen}'+```++Then drill into the top one:++```bash+traceway exceptions show $HASH --page 1 --output json | jq '.'+```++### "Why is this endpoint slow?"++```bash+# 1. confirm it's slow+traceway endpoints list --search "/api/checkout" --since 1h \+ --page 1 --output json | jq '.data[0]?'++# 2. find logs from that route. Filter by service if you know it; otherwise+# use --search-type attribute to match on a log attribute key=value.+traceway logs query --since 15m --service api --min-severity 13 \+ --page 1 --output json | jq '.data[]? | {timestamp, body, traceId}'+```++There is no `traces show` subcommand yet — once a trace ID is captured, the waterfall view has to be inspected via the web UI.++### "Show me errors for service X in the last hour"++The `exceptions list --search` is free-text against the message body, not a service filter. Pivot to `logs query` for service-scoped queries:++```bash+traceway logs query --service X --min-severity 17 --since 1h \+ --page 1 --output json \+ | jq '.data[]? | {timestamp, body, traceId}'+```++(`--min-severity 17` = ERROR; see severity table above.)++### "Did anything new break since 13:00?"++```bash+NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)+SINCE="2026-05-14T13:00:00Z"+traceway exceptions list --from "$SINCE" --to "$NOW" --order-by firstSeen \+ --page 1 --output json \+ | jq '.data[]? | select(.firstSeen >= "'"$SINCE"'") | {hash: .exceptionHash, firstSeen, count}'+```++Filter is server-side time-window; the jq pass extracts groups that *first appeared* in the window (vs old groups that just had new occurrences).++### "What system metrics are unusual?"++```bash+for m in system.cpu.utilization system.network.io system.network.errors system.network.dropped; do+ echo "=== $m ==="+ traceway metrics query --name "$m" --since 1h --output json \+ | jq '.results[0].series | to_entries[] | {tag: .key, last: .value[-1].value}'+done+```++## Error handling++| Error | What it means | What to do |+|---|---|---|+| `401 Unauthorized` / "token expired" | JWT no longer valid | Tell the user; do **not** run `traceway login` yourself |+| `connection refused` / DNS errors | Wrong base URL or server down | Try `traceway --profile <name> projects list` to confirm reachability; ask the user to check `~/.config/traceway/config.json` |+| `no project configured` | Current profile lacks a project | Run `traceway projects list`, ask the user to pick one |+| HTTP 400 `'Page' failed on the 'min' tag` | You explicitly passed `--page 0` (or another value `< 1`); the server rejects it. The CLI default is `1`, so omitting the flag works. | Drop `--page` or pass `--page 1`. |+| `invalid_time_range: unknown unit "D"` (or similar) | You used a unit `--since` doesn't accept (capital `D`, compound `7d2h`, week `1w`) | Use `s`, `m`, `h`, or lowercase `Nd`. |+| `data: null` (empty) | Not an error | Confirm the time window; widen with `--since 24h` or `--since 7d` |+| `pagination.total` very large | Many results | Narrow with a search, service, severity, or smaller time window — don't page through 1000s |++If you see a panic, stack trace, or unhandled error in stderr, **stop** and report it verbatim to the user. That's a CLI bug, not an observability finding.++## Discipline for LLM operators++1. **Bound your time windows.** Default to `--since 1h`. Never run a query without a time window — Traceway can fall back to all-time and return huge results.+2. **Keep `--page-size` small.** 10–20 is usually enough for first-pass triage. Don't pull 500 rows into context.+3. **Capture identifiers, don't repeat list calls.** When you find a useful hash / trace id / session id, save it to a shell variable and reuse.+4. **Use `jq` aggressively.** Pull only the fields you need. A full exception group can be many KB; you usually want just `exceptionHash`, `count`, `lastSeen`, and the first line of the stack trace.+5. **Read before you act.** When the user describes a problem, read several signals (exceptions + endpoints + recent logs) before forming a hypothesis. Single-source diagnoses are usually wrong.+6. **Don't infer write actions.** "Look at this error" means show it, not archive it.+7. **One vertical workflow > many broad queries.** Pick a hypothesis, follow it down: exception → trace → spans → logs. Repeat with another hypothesis only if the first doesn't fit.+8. **Stop and ask when ambiguous.** If "the auth service" could be one of three services in the project, ask. Don't paper over the ambiguity with a broader query.++## Glossary++- **Project** — Traceway tenant boundary. All queries scope to one project.+- **Exception group / hash** — A bucket of exceptions sharing the same normalized stack trace, identified by a SHA-256 hash. The list endpoint returns groups; the show endpoint returns occurrences in a group.+- **Occurrence** — A single instance of an exception within a group.+- **Trace ID** — UUID identifying one distributed trace (a request that crosses services). Used to correlate logs, spans, exceptions.+- **Span** — One unit of work within a trace, with a parent span forming a tree. Span ID identifies it.+- **Session ID** — UUID for a user session; sessions can be replayed and linked to the exceptions/traces that occurred during them.+- **Distributed Trace** — Full collection of spans for one trace ID, typically shown as a waterfall.+- **Endpoint** — An HTTP route on a service, identified by name (often method + path).+- **Severity** — OpenTelemetry severity number on a log record. Common values: `1` TRACE, `5` DEBUG, `9` INFO, `13` WARN, `17` ERROR, `21` FATAL. The CLI's `--min-severity` flag takes the number, not the name.++## When this doc is wrong++The flag names, subcommand structure, and default behaviors documented here track the *intended* CLI surface. If `traceway <command> --help` shows different flags, trust the binary. If a documented subcommand doesn't exist, the CLI doesn't have it yet — say so to the user rather than fabricating a workaround.diff --git a/cli/.envrc b/cli/.envrcnew file mode 100644index 00000000..a70aa849--- /dev/null+++ b/cli/.envrc@@ -0,0 +1,2 @@+use flake+[[ -f .envrc.local ]] && source_env .envrc.localdiff --git a/cli/.gitignore b/cli/.gitignorenew file mode 100644index 00000000..63a454a3--- /dev/null+++ b/cli/.gitignore@@ -0,0 +1,5 @@+.direnv/+.go/+bin/+.envrc.local+dist/diff --git a/cli/README.md b/cli/README.mdnew file mode 100644index 00000000..6d8bae21--- /dev/null+++ b/cli/README.md@@ -0,0 +1,141 @@+# traceway-cli++A Go CLI for the [Traceway](https://github.com/tracewayapp/traceway) observability platform — exceptions, logs, endpoints, metrics. Designed to be **first-class for both LLMs (invoking via shell tools) and humans** (with `gh`-style ergonomics).++## Install++This repo ships a Nix dev shell with Go 1.26, `just`, `gotestsum`, `golangci-lint`, `govulncheck`, and `gh`:++```bash+nix develop+just build # produces ./bin/traceway+```++Or vanilla Go:++```bash+go build -o bin/traceway ./cmd/traceway+```++## Quick start++```bash+# 1. log in (creates ~/.config/traceway/config.json + ~/.local/state/traceway/state.json)+traceway login --url https://cloud.traceway.com++# 2. pick a project (one-time; future calls use it implicitly)+traceway projects list+traceway projects use <project-id>++# 3. ask questions+traceway exceptions list --since 24h+traceway logs query --since 1h --search "OutOfMemory"+traceway endpoints list --since 1h+traceway metrics query --name http.server.duration --aggregation avg --since 1h+```++## Commands++| Command | Purpose |+|---|---|+| `traceway login` | Authenticate and store the JWT |+| `traceway logout` | Forget the stored JWT for a profile |+| `traceway profiles {list,use}` | Manage multiple Traceway accounts/instances |+| `traceway projects {list,use}` | List or select the active project |+| `traceway exceptions list` | Recent grouped exceptions |+| `traceway exceptions show <hash>` | A single exception group + occurrences |+| `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 metrics query` | Time-series metric queries |++Run `traceway <command> --help` for full per-command flags.++## Profiles++Multiple Traceway instances or accounts coexist via profiles. Configuration (URL, username) lives in `$XDG_CONFIG_HOME/traceway/config.json` so it can be checked in or managed declaratively (e.g. NixOS); credentials and the active project live in `$XDG_STATE_HOME/traceway/state.json`.++```bash+traceway login --url https://traceway.example.com --profile work+traceway profiles list+traceway profiles use work+traceway --profile personal exceptions list # one-off override+```++## Output formats++The `--output` flag picks the format. The default is `table` on a TTY and `json` otherwise — i.e. piping always gets machine-readable output.++| Format | Use |+|---|---|+| `table` | Human-friendly columns (default on TTY) |+| `json` | Compact JSON, one record per line. Default when stdout isn't a TTY |+| `yaml` | YAML rendering of the same data |++`--fields a,b,c` projects list responses to just those keys (the `pagination` wrapper passes through unchanged):++```bash+traceway exceptions list --output json --fields exceptionHash,count,lastSeen+```++## Errors++Every error writes a stable JSON envelope to stderr (in `json` / `yaml` modes — prose in `table` mode) and exits with one of:++| Exit | Meaning |+|---|---|+| 0 | Success |+| 1 | Generic / API error |+| 2 | Usage error (bad flags, missing confirmation, invalid time range) |+| 3 | Connection failure |+| 4 | Auth failure (`not_authenticated`, `token_expired`, `forbidden`) |+| 5 | Not found |+| 6 | Rate limited |+| 7 | Server (5xx) |++Envelope shape:++```json+{"error":"token_expired","message":"session expired or invalid","hint":"traceway login","exit_code":4}+```++The `error` field is a stable snake_case identifier. LLMs/scripts can branch on it.++## Mutations + confirmation++`exceptions archive` and `exceptions unarchive` require explicit consent because they change server state:++- Pass `--yes` to skip the prompt.+- Or set `TRACEWAY_ASSUME_YES=1` in the environment.+- Or run interactively and answer the `Continue? [y/N]` prompt.++Calling a mutating command from a non-TTY context (script, LLM tool call) without one of the opt-ins fails immediately with `usage_error` (exit 2) — no hung prompts.++## Smoke testing++Unit/CLI tests run by default and never touch a network:++```bash+just test+```++End-to-end tests against a real Traceway instance are gated behind a build tag and read connection info from env vars:++```bash+export TRACEWAY_SMOKE_URL=https://traceway.example.com+export [email protected]+export TRACEWAY_SMOKE_PASSWORD=...+export TRACEWAY_SMOKE_PROJECT_ID=...+just smoke-test+```++If any of those vars is missing, the smoke tests skip cleanly rather than fail.++## Contributing++```bash+just check # lint + test + vulncheck+```++The library at `pkg/client` deliberately has zero CLI dependencies — it's importable directly by other Go programs (e.g. a future MCP server).diff --git a/cli/cmd/traceway/endpoints.go b/cli/cmd/traceway/endpoints.gonew file mode 100644index 00000000..0c38ce3b--- /dev/null+++ b/cli/cmd/traceway/endpoints.go@@ -0,0 +1,105 @@+package main++import (+ "fmt"+ "time"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++var endpointsOrderBy = []string{"impact", "count", "p95", "lastSeen"}++func newEndpointsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "endpoints",+ Short: "Query HTTP endpoint performance",+ }+ cmd.AddCommand(newEndpointsListCmd())+ return cmd+}++func newEndpointsListCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "list",+ Short: "List endpoints with p50/p95/p99 latency stats",+ RunE: runEndpointsList,+ }+ addTimeRangeFlags(cmd)+ addPaginationFlags(cmd)+ cmd.Flags().String("search", "", "Free-text search filter for endpoint names")+ cmd.Flags().String("order-by", "impact", "Sort field (impact, count, p95, lastSeen)")+ cmd.Flags().String("sort-direction", "desc", "Sort direction: asc or desc")+ return cmd+}++func runEndpointsList(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }+ 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))+ }+ 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))+ }++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.ListEndpoints(ctx, sess.ProjectID, client.ListEndpointsRequest{+ TimeRange: tr,+ Pagination: page,+ Search: search,+ OrderBy: orderBy,+ SortDirection: sortDir,+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "ENDPOINT\tCOUNT\tP50\tP95\tP99\tIMPACT\tLAST SEEN")+ for _, e := range resp.Data {+ _, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\t%s\t%.2f\t%s\n",+ e.Endpoint, e.Count,+ formatDuration(e.P50Duration),+ formatDuration(e.P95Duration),+ formatDuration(e.P99Duration),+ e.Impact,+ e.LastSeen.Format("2006-01-02 15:04:05"),+ )+ }+ return tw.Flush()+ }+}++// formatDuration renders a Duration as a human-readable string.+// time.Duration's String() does this already (e.g. "50ms"); we just shorten+// for very small values.+func formatDuration(d time.Duration) string {+ if d == 0 {+ return "0"+ }+ return d.String()+}diff --git a/cli/cmd/traceway/endpoints_test.go b/cli/cmd/traceway/endpoints_test.gonew file mode 100644index 00000000..34d0b9d2--- /dev/null+++ b/cli/cmd/traceway/endpoints_test.go@@ -0,0 +1,53 @@+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestEndpointsList_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "data":[+ {"endpoint":"GET /api/projects","count":120,"p50Duration":50000000,"p95Duration":150000000,"p99Duration":300000000,"avgDuration":80000000,"lastSeen":"2026-05-13T12:00:00Z","impact":0.42,"impactReason":"high p95"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "endpoints", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "ENDPOINT") || !strings.Contains(out, "P50") || !strings.Contains(out, "P95") || !strings.Contains(out, "P99") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "/api/projects") || !strings.Contains(out, "120") {+ t.Errorf("table missing row data: %s", out)+ }+ // Latency should be human-formatted (50ms, not 50000000)+ if strings.Contains(out, "50000000") {+ t.Errorf("table should format ns as human duration: %s", out)+ }+}++func TestEndpointsList_jsonShape(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[{"endpoint":"GET /","count":1}],"pagination":{}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "endpoints", "list", "--output", "json")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stdout.String(), `"GET /"`) {+ t.Errorf("missing endpoint in JSON: %s", stdout.String())+ }+}diff --git a/cli/cmd/traceway/enumflag.go b/cli/cmd/traceway/enumflag.gonew file mode 100644index 00000000..afb5a6c5--- /dev/null+++ b/cli/cmd/traceway/enumflag.go@@ -0,0 +1,24 @@+package main++import (+ "fmt"+ "slices"+ "strings"+)++// validateEnumFlag checks that value is one of allowed. On mismatch it returns+// an error formatted for the usage_error envelope's Message field. The flag+// argument is the user-facing flag name (e.g. "--aggregation") and is included+// in the message so the user knows which input was rejected.+func validateEnumFlag(flag, value string, allowed []string) error {+ if slices.Contains(allowed, value) {+ return nil+ }+ return fmt.Errorf("%s must be one of: %s", flag, strings.Join(allowed, ", "))+}++// enumFlagHint returns a usage_error hint string suggesting the canonical form+// for an enum flag — e.g. "traceway metrics query --aggregation <avg|sum|...>".+func enumFlagHint(cmdPath, flag string, allowed []string) string {+ return fmt.Sprintf("%s %s <%s>", cmdPath, flag, strings.Join(allowed, "|"))+}diff --git a/cli/cmd/traceway/enumflag_test.go b/cli/cmd/traceway/enumflag_test.gonew file mode 100644index 00000000..46f704e3--- /dev/null+++ b/cli/cmd/traceway/enumflag_test.go@@ -0,0 +1,46 @@+package main++import (+ "strings"+ "testing"+)++func TestValidateEnumFlag_acceptsAllAllowed(t *testing.T) {+ allowed := []string{"avg", "sum", "p95"}+ for _, v := range allowed {+ if err := validateEnumFlag("--aggregation", v, allowed); err != nil {+ t.Errorf("validateEnumFlag(%q) = %v, want nil", v, err)+ }+ }+}++func TestValidateEnumFlag_rejectsUnknown(t *testing.T) {+ allowed := []string{"avg", "sum", "p95"}+ err := validateEnumFlag("--aggregation", "bogus", allowed)+ if err == nil {+ t.Fatal("expected error for unknown value")+ }+ msg := err.Error()+ if !strings.Contains(msg, "--aggregation") {+ t.Errorf("error %q should mention the flag name", msg)+ }+ for _, a := range allowed {+ if !strings.Contains(msg, a) {+ t.Errorf("error %q should list allowed value %q", msg, a)+ }+ }+}++func TestValidateEnumFlag_rejectsEmpty(t *testing.T) {+ if err := validateEnumFlag("--x", "", []string{"a", "b"}); err == nil {+ t.Fatal("empty value should not validate")+ }+}++func TestEnumFlagHint_format(t *testing.T) {+ got := enumFlagHint("traceway metrics query", "--aggregation", []string{"avg", "sum"})+ want := "traceway metrics query --aggregation <avg|sum>"+ if got != want {+ t.Errorf("enumFlagHint = %q, want %q", got, want)+ }+}diff --git a/cli/cmd/traceway/enumvalidation_test.go b/cli/cmd/traceway/enumvalidation_test.gonew file mode 100644index 00000000..82f96682--- /dev/null+++ b/cli/cmd/traceway/enumvalidation_test.go@@ -0,0 +1,188 @@+package main++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++// TestEnumFlagValidation_acceptsAndRejects asserts that every enum-shaped flag+// across the read commands accepts each documented value and rejects unknown+// input with a usage_error envelope and exit code 2 — the same shape the+// missing-required-flag path produces.+func TestEnumFlagValidation_acceptsAndRejects(t *testing.T) {+ type validCase struct {+ name string+ args []string+ }+ type rejectCase struct {+ name string+ args []string+ expectFlagInMsg string+ expectAllowed []string+ }++ emptyOK := func(_ http.ResponseWriter, _ *http.Request) {}++ tests := []struct {+ group string+ emptyJSON string+ valid []validCase+ reject []rejectCase+ }{+ {+ group: "exceptions list --search-type",+ emptyJSON: `{"data":[],"pagination":{}}`,+ valid: []validCase{+ {"text", []string{"exceptions", "list", "--search-type", "text", "--output", "json"}},+ {"regex", []string{"exceptions", "list", "--search-type", "regex", "--output", "json"}},+ },+ reject: []rejectCase{+ {+ name: "bogus",+ args: []string{"exceptions", "list", "--search-type", "bogus", "--output", "json"},+ expectFlagInMsg: "--search-type",+ expectAllowed: []string{"text", "regex"},+ },+ },+ },+ {+ group: "exceptions list --order-by",+ emptyJSON: `{"data":[],"pagination":{}}`,+ valid: []validCase{+ {"lastSeen", []string{"exceptions", "list", "--order-by", "lastSeen", "--output", "json"}},+ {"firstSeen", []string{"exceptions", "list", "--order-by", "firstSeen", "--output", "json"}},+ {"count", []string{"exceptions", "list", "--order-by", "count", "--output", "json"}},+ },+ reject: []rejectCase{+ {+ name: "bogus",+ args: []string{"exceptions", "list", "--order-by", "bogus", "--output", "json"},+ expectFlagInMsg: "--order-by",+ expectAllowed: []string{"lastSeen", "firstSeen", "count"},+ },+ },+ },+ {+ group: "logs query --search-type",+ emptyJSON: `{"data":[],"pagination":{}}`,+ valid: []validCase{+ {"body", []string{"logs", "query", "--search-type", "body", "--output", "json"}},+ {"attribute", []string{"logs", "query", "--search-type", "attribute", "--output", "json"}},+ },+ reject: []rejectCase{+ {+ name: "bogus",+ args: []string{"logs", "query", "--search-type", "bogus", "--output", "json"},+ expectFlagInMsg: "--search-type",+ expectAllowed: []string{"body", "attribute"},+ },+ },+ },+ {+ group: "logs query --sort-direction",+ emptyJSON: `{"data":[],"pagination":{}}`,+ valid: []validCase{+ {"asc", []string{"logs", "query", "--sort-direction", "asc", "--output", "json"}},+ {"desc", []string{"logs", "query", "--sort-direction", "desc", "--output", "json"}},+ },+ reject: []rejectCase{+ {+ name: "bogus",+ args: []string{"logs", "query", "--sort-direction", "sideways", "--output", "json"},+ expectFlagInMsg: "--sort-direction",+ expectAllowed: []string{"asc", "desc"},+ },+ },+ },+ {+ group: "endpoints list --order-by",+ emptyJSON: `{"data":[],"pagination":{}}`,+ valid: []validCase{+ {"impact", []string{"endpoints", "list", "--order-by", "impact", "--output", "json"}},+ {"count", []string{"endpoints", "list", "--order-by", "count", "--output", "json"}},+ {"p95", []string{"endpoints", "list", "--order-by", "p95", "--output", "json"}},+ {"lastSeen", []string{"endpoints", "list", "--order-by", "lastSeen", "--output", "json"}},+ },+ reject: []rejectCase{+ {+ name: "bogus",+ args: []string{"endpoints", "list", "--order-by", "bogus", "--output", "json"},+ expectFlagInMsg: "--order-by",+ expectAllowed: []string{"impact", "count", "p95", "lastSeen"},+ },+ },+ },+ {+ group: "endpoints list --sort-direction",+ emptyJSON: `{"data":[],"pagination":{}}`,+ valid: []validCase{+ {"asc", []string{"endpoints", "list", "--sort-direction", "asc", "--output", "json"}},+ {"desc", []string{"endpoints", "list", "--sort-direction", "desc", "--output", "json"}},+ },+ reject: []rejectCase{+ {+ name: "bogus",+ args: []string{"endpoints", "list", "--sort-direction", "sideways", "--output", "json"},+ expectFlagInMsg: "--sort-direction",+ expectAllowed: []string{"asc", "desc"},+ },+ },+ },+ }++ for _, group := range tests {+ t.Run(group.group, func(t *testing.T) {+ for _, vc := range group.valid {+ t.Run("accepts/"+vc.name, func(t *testing.T) {+ body := group.emptyJSON+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ emptyOK(w, r)+ _, _ = w.Write([]byte(body))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", vc.args...)+ if err != nil {+ t.Fatalf("args %v rejected: %v\nstderr: %s", vc.args, err, stderr.String())+ }+ })+ }++ for _, rc := range group.reject {+ t.Run("rejects/"+rc.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {+ t.Errorf("server should not be called for invalid enum input: args=%v", rc.args)+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", rc.args...)+ if err == nil {+ t.Fatalf("expected error for args %v", rc.args)+ }+ if !strings.Contains(stderr.String(), `"usage_error"`) {+ t.Errorf("expected usage_error envelope, got: %s", stderr.String())+ }+ if !strings.Contains(stderr.String(), rc.expectFlagInMsg) {+ t.Errorf("expected flag %q in error, got: %s", rc.expectFlagInMsg, stderr.String())+ }+ for _, want := range rc.expectAllowed {+ if !strings.Contains(stderr.String(), want) {+ t.Errorf("expected allowed value %q in error, got: %s", want, stderr.String())+ }+ }+ var ce *cliError+ if !errors.As(err, &ce) || ce.code != exitcode.Usage {+ t.Errorf("expected cliError(Usage=2), got %v", err)+ }+ })+ }+ })+ }+}diff --git a/cli/cmd/traceway/errors.go b/cli/cmd/traceway/errors.gonew file mode 100644index 00000000..dafed375--- /dev/null+++ b/cli/cmd/traceway/errors.go@@ -0,0 +1,100 @@+package main++import (+ "errors"+ "io"+ "net/url"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++// cliError carries an exit code alongside an error message. Command runners+// return *cliError to communicate which exitcode the CLI should terminate+// with. main() type-asserts on the returned error to extract the code.+type cliError struct {+ code int+ err error+}++func (e *cliError) Error() string { return e.err.Error() }+func (e *cliError) Unwrap() error { return e.err }++// newCLIError is a small constructor.+func newCLIError(code int, sentinel string) *cliError {+ return &cliError{code: code, err: errors.New(sentinel)}+}++// renderAPIError writes the appropriate envelope to errOut and returns a+// sentinel error so the cobra runner sees a non-nil result. The actual exit+// code is communicated via the envelope's ExitCode field; main() resolves it.+//+// loginContext = true means we're in the login command itself; an Unauthorized+// from there means "wrong username/password", not "session expired".+func renderAPIError(errOut io.Writer, mode output.Mode, err error, loginContext bool) error {+ env := classifyError(err, loginContext)+ _ = output.RenderError(errOut, mode, env)+ return newCLIError(env.ExitCode, env.Code)+}++func classifyError(err error, loginContext bool) output.ErrorEnvelope {+ switch {+ case errors.Is(err, client.ErrUnauthorized):+ if loginContext {+ return output.ErrorEnvelope{+ Code: "not_authenticated", Message: "invalid email or password",+ ExitCode: exitcode.Auth,+ }+ }+ hint := "traceway login"+ if flagProfile != "" {+ hint = "traceway login --profile " + flagProfile+ }+ return output.ErrorEnvelope{+ Code: "token_expired", Message: "session expired or invalid",+ Hint: hint,+ ExitCode: exitcode.Auth,+ }+ case errors.Is(err, client.ErrForbidden):+ return output.ErrorEnvelope{+ Code: "forbidden", Message: "permission denied",+ ExitCode: exitcode.Auth,+ }+ case errors.Is(err, client.ErrNotFound):+ return output.ErrorEnvelope{+ Code: "not_found", Message: "resource not found",+ ExitCode: exitcode.NotFound,+ }+ case errors.Is(err, client.ErrRateLimited):+ return output.ErrorEnvelope{+ Code: "rate_limited", Message: "rate limit exceeded — slow down or retry later",+ ExitCode: exitcode.RateLimited,+ }+ }+ var apiErr *client.APIError+ if errors.As(err, &apiErr) {+ if apiErr.StatusCode >= 500 {+ return output.ErrorEnvelope{+ Code: "server_error", Message: apiErr.Error(),+ ExitCode: exitcode.Server,+ }+ }+ return output.ErrorEnvelope{+ Code: "api_error", Message: apiErr.Error(),+ ExitCode: exitcode.Generic,+ }+ }+ var urlErr *url.Error+ if errors.As(err, &urlErr) {+ return output.ErrorEnvelope{+ Code: "connection_failed", Message: urlErr.Error(),+ Hint: "check that the Traceway URL is reachable and the network is up",+ ExitCode: exitcode.Connection,+ }+ }+ return output.ErrorEnvelope{+ Code: "internal", Message: err.Error(),+ ExitCode: exitcode.Generic,+ }+}diff --git a/cli/cmd/traceway/errors_test.go b/cli/cmd/traceway/errors_test.gonew file mode 100644index 00000000..4a0c6c94--- /dev/null+++ b/cli/cmd/traceway/errors_test.go@@ -0,0 +1,44 @@+package main++import (+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func TestClassifyError_tokenExpired_noTrailingSpaceWhenProfileEmpty(t *testing.T) {+ flagProfile = ""+ defer func() { flagProfile = "" }()++ env := classifyError(client.ErrUnauthorized, false)+ if env.Code != "token_expired" {+ t.Fatalf("Code = %q, want token_expired", env.Code)+ }+ if env.Hint == "" {+ t.Fatal("expected non-empty hint")+ }+ if strings.HasSuffix(env.Hint, " ") {+ t.Errorf("hint has trailing space: %q", env.Hint)+ }+ if strings.Contains(env.Hint, "--profile ") && !strings.Contains(env.Hint, "--profile X") {+ // Must not be "--profile " with empty value+ if strings.HasSuffix(env.Hint, "--profile ") || strings.HasSuffix(env.Hint, "--profile") {+ t.Errorf("hint references --profile with no value: %q", env.Hint)+ }+ }+}++func TestClassifyError_tokenExpired_includesProfileWhenSet(t *testing.T) {+ flagProfile = "stormwind"+ defer func() { flagProfile = "" }()++ env := classifyError(client.ErrUnauthorized, false)+ if !strings.Contains(env.Hint, "stormwind") {+ t.Errorf("hint should include profile name 'stormwind', got: %q", env.Hint)+ }+}++// silence unused-import warning in case output isn't actually used+var _ output.ErrorEnvelopediff --git a/cli/cmd/traceway/exceptions.go b/cli/cmd/traceway/exceptions.gonew file mode 100644index 00000000..96753ab4--- /dev/null+++ b/cli/cmd/traceway/exceptions.go@@ -0,0 +1,256 @@+package main++import (+ "context"+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++var (+ exceptionsOrderBy = []string{"lastSeen", "firstSeen", "count"}+ exceptionsSearchTypes = []string{"text", "regex"}+)++func newExceptionsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "exceptions",+ Short: "Query exception groups and occurrences",+ }+ cmd.AddCommand(newExceptionsListCmd())+ cmd.AddCommand(newExceptionsShowCmd())+ cmd.AddCommand(newExceptionsArchiveCmd())+ cmd.AddCommand(newExceptionsUnarchiveCmd())+ return cmd+}++func newExceptionsListCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "list",+ Short: "List recent exception groups",+ RunE: runExceptionsList,+ }+ addTimeRangeFlags(cmd)+ addPaginationFlags(cmd)+ cmd.Flags().String("search", "", "Free-text search filter")+ cmd.Flags().String("search-type", "text", "Search type: text or regex")+ cmd.Flags().Bool("include-archived", false, "Include archived exceptions")+ cmd.Flags().String("order-by", "lastSeen", "Sort field (lastSeen, firstSeen, count)")+ return cmd+}++func runExceptionsList(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }++ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }+ 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))+ }+ 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))+ }++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.ListExceptions(ctx, sess.ProjectID, client.ListExceptionsRequest{+ TimeRange: tr,+ Pagination: page,+ Search: search,+ SearchType: searchType,+ IncludeArchived: includeArchived,+ OrderBy: orderBy,+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "HASH\tCOUNT\tLAST SEEN\tFIRST SEEN\tFIRST LINE")+ for _, e := range resp.Data {+ hash := e.ExceptionHash+ if len(hash) > 12 {+ hash = hash[:12]+ }+ _, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\t%s\n",+ hash, e.Count,+ e.LastSeen.Format("2006-01-02 15:04:05"),+ e.FirstSeen.Format("2006-01-02 15:04:05"),+ firstLine(e.StackTrace),+ )+ }+ return tw.Flush()+ }+}++func newExceptionsShowCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "show <hash>",+ Short: "Show a single exception group with its occurrences",+ Args: cobra.ExactArgs(1),+ RunE: runExceptionsShow,+ }+ addPaginationFlags(cmd)+ return cmd+}++func runExceptionsShow(cmd *cobra.Command, args []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ page := resolvePagination(cmd)+ page.PageSize = pickDefault(page.PageSize, 20) // detail uses 20 by default++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.GetException(ctx, sess.ProjectID, args[0], page)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ // Group header, then occurrences table.+ if resp.Group != nil {+ _, _ = fmt.Fprintf(cmd.OutOrStdout(),+ "HASH: %s\nCOUNT: %d\nFIRST SEEN: %s\nLAST SEEN: %s\n\nSTACK TRACE:\n%s\n\nOCCURRENCES (%d):\n",+ resp.Group.ExceptionHash, resp.Group.Count,+ resp.Group.FirstSeen.Format("2006-01-02 15:04:05"),+ resp.Group.LastSeen.Format("2006-01-02 15:04:05"),+ resp.Group.StackTrace,+ len(resp.Occurrences),+ )+ }+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "ID\tRECORDED AT\tSERVER\tTRACE TYPE")+ for _, occ := range resp.Occurrences {+ traceType := occ.TraceType+ if traceType == "" {+ traceType = "-"+ }+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n",+ occ.Id.String(),+ occ.RecordedAt.Format("2006-01-02 15:04:05"),+ pickStr(occ.ServerName, "-"),+ traceType,+ )+ }+ return tw.Flush()+ }+}++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 := client.New(sess.URL, client.WithJWT(sess.JWT))+ 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 {+ if len(hash) <= n {+ return hash+ }+ return hash[:n]+}+diff --git a/cli/cmd/traceway/exceptions_test.go b/cli/cmd/traceway/exceptions_test.gonew file mode 100644index 00000000..72c6533b--- /dev/null+++ b/cli/cmd/traceway/exceptions_test.go@@ -0,0 +1,272 @@+package main++import (+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++// seedSessionFor configures config + state for a default profile pointing at+// baseURL with a stored JWT and a current_project_id.+func seedSessionFor(t *testing.T, baseURL string) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: baseURL, Username: "[email protected]"},+ }}+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "proj-1"}},+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }+}++func TestExceptionsList_jsonShape(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ _, _ = w.Write([]byte(`{+ "data":[+ {"exceptionHash":"h1","stackTrace":"t1","count":7,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"}+ ],+ "pagination":{"page":1,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagProject = "" })++ stdout, _, err := runCmd(t, "", "exceptions", "list", "--output", "json")+ if err != nil {+ t.Fatalf("exceptions list: %v", err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"h1"`) {+ t.Errorf("expected hash in output, got: %s", out)+ }+ if !strings.Contains(out, `"pagination"`) {+ t.Errorf("expected pagination passthrough, got: %s", out)+ }+}++func TestExceptionsList_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "data":[+ {"exceptionHash":"abcdef1234567890","stackTrace":"NullPointerException at line 42","count":7,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "exceptions", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ // First line is header+ if !strings.Contains(out, "HASH") || !strings.Contains(out, "COUNT") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "7") {+ t.Errorf("table missing count: %s", out)+ }+ // Hash should be truncated (first 12 chars by convention)+ if !strings.Contains(out, "abcdef123456") {+ t.Errorf("table missing truncated hash prefix: %s", out)+ }+}++func TestExceptionsList_noSession_writesEnvelope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ _, stderr, err := runCmd(t, "", "exceptions", "list", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"not_authenticated"`) {+ t.Errorf("expected not_authenticated envelope, got: %s", stderr.String())+ }+}++func TestExceptionsList_invalidTimeRange_writesEnvelope(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "exceptions", "list", "--output", "json", "--since", "1h", "--from", "2026-05-13T00:00:00Z", "--to", "2026-05-13T23:59:59Z")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"invalid_time_range"`) {+ t.Errorf("expected invalid_time_range envelope, got: %s", stderr.String())+ }+}++func TestExceptionsShow_passesHashInPath(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces/abc" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _, _ = w.Write([]byte(`{+ "group":{"exceptionHash":"abc","stackTrace":"trace","count":3,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"},+ "occurrences":[],+ "pagination":{"page":1,"pageSize":20,"total":0,"totalPages":0}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "exceptions", "show", "abc", "--output", "json")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"abc"`) {+ t.Errorf("expected hash in output: %s", out)+ }+}++func TestExceptionsShow_404_writesNotFoundEnvelope(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "exceptions", "show", "missing", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"not_found"`) {+ 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/login.go b/cli/cmd/traceway/login.gonew file mode 100644index 00000000..251b119b--- /dev/null+++ b/cli/cmd/traceway/login.go@@ -0,0 +1,164 @@+package main++import (+ "bufio"+ "context"+ "errors"+ "fmt"+ "io"+ "os"+ "strings"++ "github.com/spf13/cobra"+ "golang.org/x/term"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/internal/state"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++const defaultURL = "https://cloud.traceway.com"++// login-specific flag values+var (+ loginURL string+ loginUsername string+ loginPasswordFile bool+)++func newLoginCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "login",+ Short: "Authenticate against a Traceway instance and store the JWT",+ RunE: runLogin,+ }+ cmd.Flags().StringVar(&loginURL, "url", "", "Traceway base URL (default: existing or "+defaultURL+")")+ cmd.Flags().StringVar(&loginUsername, "username", "", "Email address (default: existing or interactive prompt)")+ cmd.Flags().BoolVar(&loginPasswordFile, "password-stdin", false, "Read password from stdin instead of prompting")+ return cmd+}++func runLogin(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }++ cfg, err := config.Load()+ if err != nil {+ return err+ }+ st, err := state.Load()+ if err != nil {+ return err+ }++ profileName := resolveProfileName(st)++ existingCfg, hasCfg := cfg.Profiles[profileName]+ existingState, hasState := st.Profiles[profileName]++ url := loginURL+ if url == "" {+ if hasCfg {+ url = existingCfg.URL+ } else {+ url = defaultURL+ }+ }++ username := loginUsername+ if username == "" {+ if hasCfg {+ username = existingCfg.Username+ }+ if username == "" {+ username, err = promptUsername(cmd.InOrStdin(), cmd.OutOrStdout())+ if err != nil {+ return err+ }+ }+ }++ password, err := readPassword(cmd.InOrStdin(), cmd.OutOrStdout(), loginPasswordFile)+ if err != nil {+ return err+ }++ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ c := client.New(url)+ jwt, err := c.Login(ctx, username, password)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, true)+ }++ if cfg.Profiles == nil {+ cfg.Profiles = map[string]config.Profile{}+ }+ cfg.Profiles[profileName] = config.Profile{+ URL: url,+ Username: username,+ }++ if st.Profiles == nil {+ st.Profiles = map[string]state.ProfileState{}+ }+ currentProject := ""+ if hasState {+ currentProject = existingState.CurrentProjectID+ }+ st.Profiles[profileName] = state.ProfileState{+ JWT: jwt,+ CurrentProjectID: currentProject,+ }+ // First profile ever → set CurrentProfile pointer. Don't override on subsequent logins.+ if st.CurrentProfile == "" {+ st.CurrentProfile = profileName+ }++ if err := cfg.Save(); err != nil {+ return err+ }+ if err := st.Save(); err != nil {+ return err+ }++ _, err = fmt.Fprintf(cmd.OutOrStdout(), "Logged in as %s on %s (profile: %s)\n", username, url, profileName)+ return err+}++func promptUsername(in io.Reader, out io.Writer) (string, error) {+ _, _ = fmt.Fprint(out, "Username: ")+ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return "", err+ }+ return strings.TrimSpace(line), nil+}++func readPassword(in io.Reader, out io.Writer, fromStdin bool) (string, error) {+ if fromStdin {+ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return "", err+ }+ return strings.TrimSpace(line), nil+ }+ // Interactive: read with no echo if stdin is a real terminal.+ if f, ok := in.(*os.File); ok && term.IsTerminal(int(f.Fd())) {+ _, _ = fmt.Fprint(out, "Password: ")+ bytes, err := term.ReadPassword(int(f.Fd()))+ _, _ = fmt.Fprintln(out)+ return string(bytes), err+ }+ // Fallback: line-based read (covers test injection).+ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return "", err+ }+ return strings.TrimSpace(line), nil+}diff --git a/cli/cmd/traceway/login_test.go b/cli/cmd/traceway/login_test.gonew file mode 100644index 00000000..1e813a25--- /dev/null+++ b/cli/cmd/traceway/login_test.go@@ -0,0 +1,178 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func TestLogin_passwordStdin_success(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) {+ if r.URL.Path != "/api/login" {+ t.Errorf("path = %q", r.URL.Path)+ }+ var req map[string]string+ _ = json.NewDecoder(r.Body).Decode(&req)+ if req["email"] != "[email protected]" {+ t.Errorf("email = %q", req["email"])+ }+ if req["password"] != "hunter2" {+ t.Errorf("password = %q", req["password"])+ }+ _, _ = w.Write([]byte(`{"token":"jwt.value"}`))+ }))+ defer srv.Close()++ _, _, err := runCmd(t, "hunter2\n",+ "login",+ "--url", srv.URL,+ "--username", "[email protected]",+ "--password-stdin",+ )+ if err != nil {+ t.Fatalf("login failed: %v", err)+ }++ cfg, err := config.Load()+ if err != nil {+ t.Fatalf("Load config: %v", err)+ }+ p, ok := cfg.Profiles["default"]+ if !ok {+ t.Fatal("default profile not saved in config")+ }+ if p.URL != srv.URL {+ t.Errorf("URL = %q", p.URL)+ }+ if p.Username != "[email protected]" {+ t.Errorf("Username = %q", p.Username)+ }++ st, err := state.Load()+ if err != nil {+ t.Fatalf("Load state: %v", err)+ }+ sp, ok := st.Profiles["default"]+ if !ok {+ t.Fatal("default profile not saved in state")+ }+ if sp.JWT != "jwt.value" {+ t.Errorf("JWT = %q", sp.JWT)+ }+ if st.CurrentProfile != "default" {+ t.Errorf("CurrentProfile = %q, want default (only profile should be auto-set)", st.CurrentProfile)+ }+}++func TestLogin_namedProfile_secondLogin_doesNotOverrideCurrent(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, _ *http.Request) {+ _, _ = w.Write([]byte(`{"token":"tok"}`))+ }))+ defer srv.Close()++ // First login → default profile.+ if _, _, err := runCmd(t, "p\n",+ "login", "--url", srv.URL, "--username", "[email protected]", "--password-stdin",+ ); err != nil {+ t.Fatalf("first login: %v", err)+ }+ // Second login → cloud profile. Should NOT change current profile pointer.+ if _, _, err := runCmd(t, "p\n",+ "login", "--profile", "cloud", "--url", srv.URL, "--username", "[email protected]", "--password-stdin",+ ); err != nil {+ t.Fatalf("second login: %v", err)+ }++ st, _ := state.Load()+ if st.CurrentProfile != "default" {+ t.Errorf("CurrentProfile = %q, want 'default' (was set on first login, second login must not override)", st.CurrentProfile)+ }+ cfg, _ := config.Load()+ if _, ok := cfg.Profiles["cloud"]; !ok {+ t.Error("cloud profile missing from config")+ }+}++func TestLogin_invalidCredentials_writesEnvelope(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, _ *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer srv.Close()++ _, stderr, err := runCmd(t, "wrong\n",+ "login", "--output", "json", "--url", srv.URL, "--username", "x", "--password-stdin",+ )+ if err == nil {+ t.Fatal("expected login to return an error")+ }+ if !strings.Contains(stderr.String(), `"error"`) {+ t.Errorf("expected JSON error envelope on stderr, got: %s", stderr.String())+ }+ if !strings.Contains(stderr.String(), `"not_authenticated"`) {+ t.Errorf("expected error code 'not_authenticated', got: %s", stderr.String())+ }+}++func TestLogin_refreshExistingProfile_keepsURLAndUsername(t *testing.T) {+ cfgDir := t.TempDir()+ stateDir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", cfgDir)+ t.Setenv("XDG_STATE_HOME", stateDir)++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"token":"newtoken"}`))+ }))+ defer srv.Close()++ // Seed config and state with an existing profile.+ cfg := &config.Config{+ Profiles: map[string]config.Profile{+ "default": {URL: srv.URL, Username: "[email protected]"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{+ "default": {JWT: "old"},+ },+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }++ // Refresh: only --password-stdin, no --url/--username.+ if _, _, err := runCmd(t, "newpw\n", "login", "--password-stdin"); err != nil {+ t.Fatalf("refresh: %v", err)+ }++ gotCfg, _ := config.Load()+ p := gotCfg.Profiles["default"]+ if p.URL != srv.URL {+ t.Errorf("URL changed: %q", p.URL)+ }+ if p.Username != "[email protected]" {+ t.Errorf("Username changed: %q", p.Username)+ }++ gotState, _ := state.Load()+ if gotState.Profiles["default"].JWT != "newtoken" {+ t.Errorf("JWT not refreshed: %q", gotState.Profiles["default"].JWT)+ }+}diff --git a/cli/cmd/traceway/logout.go b/cli/cmd/traceway/logout.gonew file mode 100644index 00000000..36a02abf--- /dev/null+++ b/cli/cmd/traceway/logout.go@@ -0,0 +1,73 @@+package main++import (+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func newLogoutCmd() *cobra.Command {+ return &cobra.Command{+ Use: "logout",+ Short: "Remove a profile's stored credentials",+ RunE: runLogout,+ }+}++func runLogout(cmd *cobra.Command, _ []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }+ st, err := state.Load()+ if err != nil {+ return err+ }++ name := resolveProfileName(st)++ _, inCfg := cfg.Profiles[name]+ _, inState := st.Profiles[name]+ if !inCfg && !inState {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "no_profile",+ Message: fmt.Sprintf("profile %q does not exist", name),+ ExitCode: exitcode.Auth,+ })+ return newCLIError(exitcode.Auth, "no_profile")+ }++ delete(cfg.Profiles, name)+ delete(st.Profiles, name)++ if st.CurrentProfile == name {+ // Pick any remaining profile as the new current; otherwise blank.+ st.CurrentProfile = ""+ for k := range cfg.Profiles {+ st.CurrentProfile = k+ break+ }+ // If nothing left in cfg, try state profiles.+ if st.CurrentProfile == "" {+ for k := range st.Profiles {+ st.CurrentProfile = k+ break+ }+ }+ }++ if err := cfg.Save(); err != nil {+ return err+ }+ if err := st.Save(); err != nil {+ return err+ }+ _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Logged out of profile %q\n", name)+ return nil+}diff --git a/cli/cmd/traceway/logout_test.go b/cli/cmd/traceway/logout_test.gonew file mode 100644index 00000000..bf3ceafc--- /dev/null+++ b/cli/cmd/traceway/logout_test.go@@ -0,0 +1,95 @@+package main++import (+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func TestLogout_removesProfile(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ cfg := &config.Config{+ Profiles: map[string]config.Profile{+ "default": {URL: "https://x", Username: "u"},+ "cloud": {URL: "https://y", Username: "v"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{+ "default": {JWT: "tok"},+ "cloud": {JWT: "tok2"},+ },+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }++ if _, _, err := runCmd(t, "", "logout"); err != nil {+ t.Fatalf("logout: %v", err)+ }+ gotCfg, _ := config.Load()+ if _, ok := gotCfg.Profiles["default"]; ok {+ t.Error("default profile should be removed from config")+ }+ if _, ok := gotCfg.Profiles["cloud"]; !ok {+ t.Error("cloud profile should be untouched in config")+ }+ gotState, _ := state.Load()+ if _, ok := gotState.Profiles["default"]; ok {+ t.Error("default profile should be removed from state")+ }+}++func TestLogout_resetsCurrentProfileWhenRemovingIt(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ cfg := &config.Config{+ Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ "cloud": {URL: "https://y"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{+ "default": {JWT: "tok"},+ "cloud": {JWT: "tok2"},+ },+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }++ _, _, err := runCmd(t, "", "logout")+ if err != nil {+ t.Fatal(err)+ }+ gotState, _ := state.Load()+ if gotState.CurrentProfile == "default" {+ t.Errorf("CurrentProfile should not still be 'default', got %q", gotState.CurrentProfile)+ }+}++func TestLogout_unknownProfile_returnsAuthError(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ _, stderr, err := runCmd(t, "", "logout", "--profile", "ghost", "--output", "json")+ if err == nil {+ t.Fatal("expected error for unknown profile")+ }+ if !strings.Contains(stderr.String(), `"error"`) {+ t.Errorf("expected JSON envelope, got: %s", stderr.String())+ }+}diff --git a/cli/cmd/traceway/logs.go b/cli/cmd/traceway/logs.gonew file mode 100644index 00000000..660310a5--- /dev/null+++ b/cli/cmd/traceway/logs.go@@ -0,0 +1,107 @@+package main++import (+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++var (+ logsSearchTypes = []string{"body", "attribute"}+ sortDirections = []string{"asc", "desc"}+)++func newLogsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "logs",+ Short: "Query log records",+ }+ cmd.AddCommand(newLogsQueryCmd())+ return cmd+}++func newLogsQueryCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "query",+ Short: "Query logs by time, service, severity, or trace",+ RunE: runLogsQuery,+ }+ addTimeRangeFlags(cmd)+ addPaginationFlags(cmd)+ cmd.Flags().String("service", "", "Filter by service name")+ cmd.Flags().Uint8("min-severity", 0, "Minimum OTel severity number (1=TRACE, 5=DEBUG, 9=INFO, 13=WARN, 17=ERROR, 21=FATAL)")+ cmd.Flags().String("trace-id", "", "Filter to a specific OpenTelemetry trace ID")+ cmd.Flags().String("search", "", "Free-text search in body")+ cmd.Flags().String("search-type", "body", "Search type: body or attribute")+ cmd.Flags().String("order-by", "timestamp", "Sort field")+ cmd.Flags().String("sort-direction", "desc", "Sort direction: asc or desc")+ return cmd+}++func runLogsQuery(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }+ page := resolvePagination(cmd)+ service, _ := cmd.Flags().GetString("service")+ minSev, _ := cmd.Flags().GetUint8("min-severity")+ traceID, _ := cmd.Flags().GetString("trace-id")+ search, _ := cmd.Flags().GetString("search")+ 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))+ }+ 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))+ }++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.QueryLogs(ctx, sess.ProjectID, client.QueryLogsRequest{+ TimeRange: tr,+ Pagination: page,+ ServiceName: service,+ MinSeverity: minSev,+ TraceId: traceID,+ Search: search,+ SearchType: searchType,+ OrderBy: orderBy,+ SortDirection: sortDir,+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "TIMESTAMP\tSEVERITY\tSERVICE\tBODY")+ for _, l := range resp.Data {+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n",+ l.Timestamp.Format("2006-01-02 15:04:05"),+ pickStr(l.SeverityText, "-"),+ pickStr(l.ServiceName, "-"),+ firstLine(l.Body),+ )+ }+ return tw.Flush()+ }+}diff --git a/cli/cmd/traceway/logs_test.go b/cli/cmd/traceway/logs_test.gonew file mode 100644index 00000000..ae76d8f0--- /dev/null+++ b/cli/cmd/traceway/logs_test.go@@ -0,0 +1,76 @@+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestLogsQuery_basic(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/logs" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _, _ = w.Write([]byte(`{+ "data":[+ {"id":"00000000-0000-0000-0000-000000000001","timestamp":"2026-05-13T12:00:00Z","severityText":"ERROR","severityNumber":17,"serviceName":"api","body":"failed to connect"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "logs", "query", "--output", "json")+ if err != nil {+ t.Fatalf("logs query: %v", err)+ }+ if !strings.Contains(stdout.String(), "failed to connect") {+ t.Errorf("expected log body in output: %s", stdout.String())+ }+}++func TestLogsQuery_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "data":[+ {"id":"00000000-0000-0000-0000-000000000001","timestamp":"2026-05-13T12:00:00Z","severityText":"ERROR","severityNumber":17,"serviceName":"api","body":"failed to connect"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "logs", "query", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "TIMESTAMP") || !strings.Contains(out, "SEVERITY") || !strings.Contains(out, "SERVICE") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "ERROR") || !strings.Contains(out, "api") || !strings.Contains(out, "failed") {+ t.Errorf("table missing row data: %s", out)+ }+}++func TestLogsQuery_passesServiceFilter(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // Decode body and assert serviceName was passed through+ buf := make([]byte, 4096)+ n, _ := r.Body.Read(buf)+ body := string(buf[:n])+ if !strings.Contains(body, `"serviceName":"api"`) {+ t.Errorf("expected serviceName=api in body, got: %s", body)+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ if _, _, err := runCmd(t, "", "logs", "query", "--service", "api"); err != nil {+ t.Fatal(err)+ }+}diff --git a/cli/cmd/traceway/main.go b/cli/cmd/traceway/main.gonew file mode 100644index 00000000..ebe60f69--- /dev/null+++ b/cli/cmd/traceway/main.go@@ -0,0 +1,30 @@+package main++import (+ "context"+ "errors"+ "fmt"+ "os"+ "os/signal"+ "syscall"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++func main() {+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer cancel()++ root := newRootCmd()+ if err := root.ExecuteContext(ctx); err != nil {+ var ce *cliError+ if errors.As(err, &ce) {+ os.Exit(ce.code)+ }+ if os.Getenv("TRACEWAY_DEBUG") == "1" {+ fmt.Fprintln(os.Stderr, "debug:", err)+ }+ os.Exit(exitcode.Usage)+ }+ os.Exit(exitcode.Success)+}diff --git a/cli/cmd/traceway/metrics.go b/cli/cmd/traceway/metrics.gonew file mode 100644index 00000000..6f064911--- /dev/null+++ b/cli/cmd/traceway/metrics.go@@ -0,0 +1,127 @@+package main++import (+ "fmt"+ "strings"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++// metricAggregations is the canonical list of aggregations the server accepts.+// Kept in lockstep with the --aggregation flag's help text.+var metricAggregations = []string{"avg", "sum", "count", "min", "max", "p50", "p95", "p99"}++func newMetricsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "metrics",+ Short: "Query metric time series",+ }+ cmd.AddCommand(newMetricsQueryCmd())+ return cmd+}++func newMetricsQueryCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "query",+ Short: "Query a single metric over time",+ RunE: runMetricsQuery,+ }+ addTimeRangeFlags(cmd)+ cmd.Flags().String("name", "", "Metric name (required)")+ cmd.Flags().String("aggregation", "avg", "Aggregation: avg, sum, count, min, max, p50, p95, p99")+ cmd.Flags().StringSlice("tag", nil, "Tag filter as key=value (repeatable)")+ cmd.Flags().String("group-by", "", "Tag to group series by")+ cmd.Flags().Int("interval-minutes", 0, "Time bucket size in minutes (0 = auto)")+ return cmd+}++func runMetricsQuery(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }++ name, _ := cmd.Flags().GetString("name")+ if name == "" {+ return renderUsageError(cmd.ErrOrStderr(), mode, "--name is required",+ "traceway metrics query --name <metric-name>")+ }+ 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))+ }+ groupBy, _ := cmd.Flags().GetString("group-by")+ intervalMin, _ := cmd.Flags().GetInt("interval-minutes")+ tags, _ := cmd.Flags().GetStringSlice("tag")++ tagFilters, err := parseTagFilters(tags)+ if err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(),+ "use --tag key=value (repeatable)")+ }++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.QueryMetrics(ctx, sess.ProjectID, client.QueryMetricsRequest{+ TimeRange: tr,+ IntervalMinutes: intervalMin,+ Queries: []client.MetricQueryItem{+ {Name: name, Aggregation: agg, TagFilters: tagFilters, GroupBy: groupBy},+ },+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ // Summary table — for actual time-series data, --output json is recommended.+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "METRIC\tUNIT\tGROUP\tPOINTS\tLATEST")+ for _, r := range resp.Results {+ if len(r.Series) == 0 {+ _, _ = fmt.Fprintf(tw, "%s\t%s\t-\t0\t-\n", r.Name, pickStr(r.Unit, "-"))+ continue+ }+ for group, pts := range r.Series {+ latest := "-"+ if len(pts) > 0 {+ latest = fmt.Sprintf("%g", pts[len(pts)-1].Value)+ }+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t%s\n", r.Name, pickStr(r.Unit, "-"), group, len(pts), latest)+ }+ }+ return tw.Flush()+ }+}++// parseTagFilters parses ["k=v", "x=y"] into {"k":"v","x":"y"}. Returns an+// error if any element is malformed.+func parseTagFilters(in []string) (map[string]string, error) {+ if len(in) == 0 {+ return nil, nil+ }+ out := make(map[string]string, len(in))+ for _, item := range in {+ k, v, ok := strings.Cut(item, "=")+ if !ok || k == "" {+ return nil, fmt.Errorf("invalid --tag %q: expected key=value", item)+ }+ out[k] = v+ }+ return out, nil+}diff --git a/cli/cmd/traceway/metrics_test.go b/cli/cmd/traceway/metrics_test.gonew file mode 100644index 00000000..e81e09b6--- /dev/null+++ b/cli/cmd/traceway/metrics_test.go@@ -0,0 +1,127 @@+package main++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++func TestMetricsQuery_jsonOutput(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "results":[+ {"name":"http.request.duration","unit":"ms","series":{"all":[{"timestamp":"2026-05-13T12:00:00Z","value":42.5}]}}+ ]+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "metrics", "query", "--name", "http.request.duration", "--aggregation", "p95", "--output", "json")+ if err != nil {+ t.Fatalf("metrics query: %v", err)+ }+ if !strings.Contains(stdout.String(), "http.request.duration") {+ t.Errorf("expected metric name in output: %s", stdout.String())+ }+ if !strings.Contains(stdout.String(), "42.5") {+ t.Errorf("expected value in output: %s", stdout.String())+ }+}++func TestMetricsQuery_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "results":[+ {"name":"http.request.duration","unit":"ms","series":{+ "all":[+ {"timestamp":"2026-05-13T12:00:00Z","value":42.5},+ {"timestamp":"2026-05-13T12:05:00Z","value":47.0}+ ]+ }}+ ]+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "metrics", "query", "--name", "http.request.duration", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "METRIC") || !strings.Contains(out, "GROUP") || !strings.Contains(out, "POINTS") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "http.request.duration") {+ t.Errorf("table missing metric name: %s", out)+ }+ if !strings.Contains(out, "47") {+ t.Errorf("table missing latest value: %s", out)+ }+}++func TestMetricsQuery_requiresName(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"results":[]}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "metrics", "query", "--output", "json")+ if err == nil {+ t.Fatal("expected --name to be required")+ }+ if !strings.Contains(stderr.String(), `"usage_error"`) {+ t.Errorf("expected usage_error envelope, got: %s", stderr.String())+ }+}++func TestMetricsQuery_aggregationAcceptsAllDocumentedValues(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"results":[]}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ for _, agg := range []string{"avg", "sum", "count", "min", "max", "p50", "p95", "p99"} {+ t.Run(agg, func(t *testing.T) {+ _, stderr, err := runCmd(t, "", "metrics", "query", "--name", "x", "--aggregation", agg, "--output", "json")+ if err != nil {+ t.Fatalf("aggregation %q rejected: %v\nstderr: %s", agg, err, stderr.String())+ }+ })+ }+}++func TestMetricsQuery_aggregationRejectsBogus(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {+ t.Fatal("server should not be called for invalid --aggregation")+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "metrics", "query", "--name", "x", "--aggregation", "nopenope", "--output", "json")+ if err == nil {+ t.Fatal("expected error for bogus --aggregation")+ }+ if !strings.Contains(stderr.String(), `"usage_error"`) {+ t.Errorf("expected usage_error envelope, got: %s", stderr.String())+ }+ if !strings.Contains(stderr.String(), "--aggregation") {+ t.Errorf("error should name the flag, got: %s", stderr.String())+ }+ for _, want := range []string{"avg", "sum", "count", "min", "max", "p50", "p95", "p99"} {+ if !strings.Contains(stderr.String(), want) {+ t.Errorf("error should list allowed value %q, got: %s", want, stderr.String())+ }+ }+ var ce *cliError+ if !errors.As(err, &ce) || ce.code != exitcode.Usage {+ t.Errorf("expected cliError(Usage), got %v", err)+ }+}diff --git a/cli/cmd/traceway/profile_resolve.go b/cli/cmd/traceway/profile_resolve.gonew file mode 100644index 00000000..716222af--- /dev/null+++ b/cli/cmd/traceway/profile_resolve.go@@ -0,0 +1,15 @@+package main++import "github.com/tracewayapp/traceway/cli/internal/state"++// resolveProfileName picks the effective profile name using the standard+// 3-tier precedence: --profile flag > st.CurrentProfile > "default".+func resolveProfileName(st *state.State) string {+ if flagProfile != "" {+ return flagProfile+ }+ if st.CurrentProfile != "" {+ return st.CurrentProfile+ }+ return "default"+}diff --git a/cli/cmd/traceway/profiles.go b/cli/cmd/traceway/profiles.gonew file mode 100644index 00000000..15f43846--- /dev/null+++ b/cli/cmd/traceway/profiles.go@@ -0,0 +1,137 @@+package main++import (+ "fmt"+ "sort"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func newProfilesCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "profiles",+ Short: "Manage stored Traceway profiles",+ }+ cmd.AddCommand(newProfilesListCmd())+ cmd.AddCommand(newProfilesUseCmd())+ return cmd+}++func newProfilesListCmd() *cobra.Command {+ return &cobra.Command{+ Use: "list",+ Short: "List configured profiles",+ RunE: runProfilesList,+ }+}++type profileSummary struct {+ Name string `json:"name"`+ URL string `json:"url"`+ Username string `json:"username"`+ Current bool `json:"current"`+}++type profilesListResponse struct {+ Current string `json:"current"`+ Data []profileSummary `json:"data"`+}++func runProfilesList(cmd *cobra.Command, _ []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }+ st, err := state.Load()+ if err != nil {+ return err+ }+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ // Build a union of names from config and state.+ nameSet := make(map[string]struct{})+ for n := range cfg.Profiles {+ nameSet[n] = struct{}{}+ }+ for n := range st.Profiles {+ nameSet[n] = struct{}{}+ }+ names := make([]string, 0, len(nameSet))+ for n := range nameSet {+ names = append(names, n)+ }+ sort.Strings(names)++ resp := profilesListResponse{Current: st.CurrentProfile}+ for _, n := range names {+ p := cfg.Profiles[n]+ resp.Data = append(resp.Data, profileSummary{+ Name: n,+ URL: p.URL,+ Username: p.Username,+ Current: n == st.CurrentProfile,+ })+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, " \tNAME\tURL\tUSERNAME")+ for _, p := range resp.Data {+ marker := " "+ if p.Current {+ marker = "*"+ }+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", marker, p.Name, p.URL, p.Username)+ }+ return tw.Flush()+ }+}++func newProfilesUseCmd() *cobra.Command {+ return &cobra.Command{+ Use: "use <profile>",+ Short: "Set the current profile",+ Args: cobra.ExactArgs(1),+ RunE: runProfilesUse,+ }+}++func runProfilesUse(cmd *cobra.Command, args []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }+ st, err := state.Load()+ if err != nil {+ return err+ }+ name := args[0]+ _, inCfg := cfg.Profiles[name]+ _, inState := st.Profiles[name]+ if !inCfg && !inState {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "no_profile",+ Message: fmt.Sprintf("profile %q does not exist", name),+ Hint: "traceway profiles list",+ ExitCode: exitcode.Auth,+ })+ return newCLIError(exitcode.Auth, "no_profile")+ }+ st.CurrentProfile = name+ if err := st.Save(); err != nil {+ return err+ }+ _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Now using profile %q\n", name)+ return nil+}diff --git a/cli/cmd/traceway/profiles_test.go b/cli/cmd/traceway/profiles_test.gonew file mode 100644index 00000000..50f1f789--- /dev/null+++ b/cli/cmd/traceway/profiles_test.go@@ -0,0 +1,90 @@+package main++import (+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func seedTwoProfiles(t *testing.T) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ cfg := &config.Config{+ Profiles: map[string]config.Profile{+ "default": {URL: "https://a", Username: "fred@a"},+ "cloud": {URL: "https://b", Username: "fred@b"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{+ "default": {JWT: "tok1"},+ "cloud": {JWT: "tok2"},+ },+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }+}++func TestProfilesList_table(t *testing.T) {+ seedTwoProfiles(t)+ stdout, _, err := runCmd(t, "", "profiles", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "default") {+ t.Errorf("missing 'default' in output: %s", out)+ }+ if !strings.Contains(out, "cloud") {+ t.Errorf("missing 'cloud' in output: %s", out)+ }+ // Current profile marked somehow (we use a "*" prefix).+ if !strings.Contains(out, "*") {+ t.Errorf("expected current-profile marker '*': %s", out)+ }+}++func TestProfilesList_json(t *testing.T) {+ seedTwoProfiles(t)+ stdout, _, err := runCmd(t, "", "profiles", "list", "--output", "json")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"default"`) || !strings.Contains(out, `"cloud"`) {+ t.Errorf("expected both profiles in JSON, got: %s", out)+ }+ if !strings.Contains(out, `"current"`) {+ t.Errorf("expected 'current' field in JSON, got: %s", out)+ }+}++func TestProfilesUse_setsCurrent(t *testing.T) {+ seedTwoProfiles(t)+ if _, _, err := runCmd(t, "", "profiles", "use", "cloud"); err != nil {+ t.Fatal(err)+ }+ st, _ := state.Load()+ if st.CurrentProfile != "cloud" {+ t.Errorf("CurrentProfile = %q, want cloud", st.CurrentProfile)+ }+}++func TestProfilesUse_unknown_returnsAuthError(t *testing.T) {+ seedTwoProfiles(t)+ _, stderr, err := runCmd(t, "", "profiles", "use", "ghost", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"no_profile"`) {+ t.Errorf("expected 'no_profile' code in stderr, got: %s", stderr.String())+ }+}diff --git a/cli/cmd/traceway/projects.go b/cli/cmd/traceway/projects.gonew file mode 100644index 00000000..2c64678d--- /dev/null+++ b/cli/cmd/traceway/projects.go@@ -0,0 +1,120 @@+package main++import (+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/internal/state"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func newProjectsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "projects",+ Short: "List and switch projects",+ }+ cmd.AddCommand(newProjectsListCmd())+ cmd.AddCommand(newProjectsUseCmd())+ return cmd+}++func newProjectsListCmd() *cobra.Command {+ return &cobra.Command{+ Use: "list",+ Short: "List projects visible to the authenticated user",+ RunE: runProjectsList,+ }+}++func runProjectsList(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ cfg, err := config.Load()+ if err != nil {+ return err+ }+ st, err := state.Load()+ if err != nil {+ return err+ }++ profileName := resolveProfileName(st)++ cfgProfile, hasCfg := cfg.Profiles[profileName]+ stateProfile, hasState := st.Profiles[profileName]++ if !hasCfg || cfgProfile.URL == "" {+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "not_authenticated",+ Message: fmt.Sprintf("profile %q not found", profileName),+ Hint: "traceway login",+ ExitCode: exitcode.Auth,+ })+ return newCLIError(exitcode.Auth, "not_authenticated")+ }+ if !hasState || stateProfile.JWT == "" {+ _ = 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",+ ExitCode: exitcode.Auth,+ })+ return newCLIError(exitcode.Auth, "not_authenticated")+ }++ c := client.New(cfgProfile.URL, client.WithJWT(stateProfile.JWT))+ projects, err := c.ListProjects(ctx)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), projects, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), projects, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "ID\tNAME")+ for _, p := range projects {+ _, _ = fmt.Fprintf(tw, "%s\t%s\n", p.ID, p.Name)+ }+ return tw.Flush()+ }+}++func newProjectsUseCmd() *cobra.Command {+ return &cobra.Command{+ Use: "use <project-id>",+ Short: "Set the current project for the active profile",+ Args: cobra.ExactArgs(1),+ RunE: runProjectsUse,+ }+}++func runProjectsUse(cmd *cobra.Command, args []string) error {+ st, err := state.Load()+ if err != nil {+ return err+ }++ profileName := resolveProfileName(st)++ if st.Profiles == nil {+ st.Profiles = map[string]state.ProfileState{}+ }+ ps := st.Profiles[profileName]+ ps.CurrentProjectID = args[0]+ st.Profiles[profileName] = ps++ if err := st.Save(); err != nil {+ return err+ }+ _, _ = fmt.Fprintf(cmd.OutOrStdout(), "Now using project %q for profile %q\n", args[0], profileName)+ return nil+}diff --git a/cli/cmd/traceway/projects_test.go b/cli/cmd/traceway/projects_test.gonew file mode 100644index 00000000..c58d5e75--- /dev/null+++ b/cli/cmd/traceway/projects_test.go@@ -0,0 +1,122 @@+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func seedProfileFor(t *testing.T, baseURL string) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ cfg := &config.Config{+ Profiles: map[string]config.Profile{+ "default": {URL: baseURL, Username: "[email protected]"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{+ "default": {JWT: "tok"},+ },+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }+}++func TestProjectsList_jsonShape(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/projects" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.Method != http.MethodGet {+ t.Errorf("method = %q", r.Method)+ }+ _, _ = w.Write([]byte(`[+ {"id":"p1","name":"alpha"},+ {"id":"p2","name":"beta"}+ ]`))+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "projects", "list", "--output", "json")+ if err != nil {+ t.Fatalf("projects list: %v", err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"alpha"`) || !strings.Contains(out, `"beta"`) {+ t.Errorf("expected both project names, got: %s", out)+ }+}++func TestProjectsList_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`[{"id":"p1","name":"alpha"}]`))+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "projects", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "p1") || !strings.Contains(out, "alpha") {+ t.Errorf("expected id/name in table, got: %s", out)+ }+}++func TestProjectsList_unauth_writesEnvelope(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "projects", "list", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"token_expired"`) {+ t.Errorf("expected token_expired envelope, got: %s", stderr.String())+ }+}++func TestProjectsList_noProfile_writesEnvelope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ _, stderr, err := runCmd(t, "", "projects", "list", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"not_authenticated"`) {+ t.Errorf("expected not_authenticated envelope, got: %s", stderr.String())+ }+}++func TestProjectsUse_persistsToProfile(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ if _, _, err := runCmd(t, "", "projects", "use", "p1"); err != nil {+ t.Fatal(err)+ }+ st, _ := state.Load()+ if st.Profiles["default"].CurrentProjectID != "p1" {+ t.Errorf("CurrentProjectID = %q", st.Profiles["default"].CurrentProjectID)+ }+}diff --git a/cli/cmd/traceway/querycommon.go b/cli/cmd/traceway/querycommon.gonew file mode 100644index 00000000..68833beb--- /dev/null+++ b/cli/cmd/traceway/querycommon.go@@ -0,0 +1,122 @@+package main++import (+ "bufio"+ "errors"+ "fmt"+ "io"+ "os"+ "strings"++ "github.com/spf13/cobra"+ "golang.org/x/term"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++// addPaginationFlags registers --page and --page-size on the given command.+// Defaults: page=1, page-size=50.+func addPaginationFlags(cmd *cobra.Command) {+ f := cmd.Flags()+ f.Int("page", 1, "Page number (1-indexed)")+ f.Int("page-size", 50, "Page size (max records per response)")+}++// resolvePagination reads the --page/--page-size flags from cmd and returns+// a PaginationParams. Assumes addPaginationFlags was called on the command.+func resolvePagination(cmd *cobra.Command) client.PaginationParams {+ page, _ := cmd.Flags().GetInt("page")+ pageSize, _ := cmd.Flags().GetInt("page-size")+ return client.PaginationParams{Page: page, PageSize: pageSize}+}++// firstLine returns the first line of s, useful for fitting a stack trace+// into a table column.+func firstLine(s string) string {+ for i, ch := range s {+ if ch == '\n' || ch == '\r' {+ return s[:i]+ }+ }+ return s+}++// pickStr returns alt if s is empty, else s. Saves a guard at every callsite.+func pickStr(s, alt string) string {+ if s == "" {+ return alt+ }+ return s+}++// pickDefault returns alt if v is zero, else v.+func pickDefault(v, alt int) int {+ if v == 0 {+ return alt+ }+ return v+}++// renderUsageError writes a usage_error envelope and returns a *cliError+// with exitcode.Usage. Used when a command receives invalid flag combinations+// or values that aren't covered by other validators.+func renderUsageError(errOut io.Writer, mode output.Mode, message, hint string) error {+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "usage_error",+ Message: message,+ Hint: hint,+ ExitCode: exitcode.Usage,+ })+ return newCLIError(exitcode.Usage, "usage_error")+}++// confirmMutation gates a destructive action behind one of three approvals,+// in priority order:+//+// 1. --yes flag is set+// 2. TRACEWAY_ASSUME_YES env var is set to a truthy value (1, true, yes)+// 3. stdin is a TTY → print summary + prompt, accept y/yes+//+// If none apply (non-TTY caller without an opt-in), a usage_error envelope+// is rendered to errOut and a *cliError(Usage) is returned. Callers should+// return that error directly so main() exits 2.+func confirmMutation(cmd *cobra.Command, summaryLines []string) error {+ if flagYes {+ return nil+ }+ if assume := strings.ToLower(strings.TrimSpace(os.Getenv("TRACEWAY_ASSUME_YES"))); assume == "1" || assume == "true" || assume == "yes" {+ return nil+ }++ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ in := cmd.InOrStdin()+ f, ok := in.(*os.File)+ if !ok || !term.IsTerminal(int(f.Fd())) {+ return renderUsageError(cmd.ErrOrStderr(), mode,+ "refusing to perform mutation without confirmation",+ "pass --yes or set TRACEWAY_ASSUME_YES=1")+ }++ out := cmd.OutOrStdout()+ for _, line := range summaryLines {+ _, _ = fmt.Fprintln(out, line)+ }+ _, _ = fmt.Fprint(out, "Continue? [y/N] ")++ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return renderUsageError(cmd.ErrOrStderr(), mode,+ "failed to read confirmation: "+err.Error(),+ "pass --yes to skip the prompt")+ }+ answer := strings.ToLower(strings.TrimSpace(line))+ if answer != "y" && answer != "yes" {+ return renderUsageError(cmd.ErrOrStderr(), mode,+ "confirmation declined", "")+ }+ return nil+}diff --git a/cli/cmd/traceway/querycommon_test.go b/cli/cmd/traceway/querycommon_test.gonew file mode 100644index 00000000..7d899a9e--- /dev/null+++ b/cli/cmd/traceway/querycommon_test.go@@ -0,0 +1,116 @@+package main++import (+ "bytes"+ "errors"+ "strings"+ "testing"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++// newTestCmd returns a minimal cobra command pre-wired with the global flags+// confirmMutation cares about (--yes is the only one).+func newTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "test"}+ cmd.Flags().BoolVar(&flagYes, "yes", false, "")+ return cmd+}++func TestConfirmMutation_yesFlagBypassesPrompt(t *testing.T) {+ t.Cleanup(func() { flagYes = false })++ cmd := newTestCmd()+ flagYes = true // set after newTestCmd so BoolVar default doesn't reset it+ out := &bytes.Buffer{}+ cmd.SetOut(out)+ cmd.SetErr(out)+ cmd.SetIn(strings.NewReader("")) // no input — must not be consulted++ if err := confirmMutation(cmd, []string{"about to do thing"}); err != nil {+ t.Fatalf("confirmMutation = %v, want nil", err)+ }+ if out.Len() != 0 {+ t.Errorf("expected no output with --yes, got %q", out.String())+ }+}++func TestConfirmMutation_envVarBypassesPrompt(t *testing.T) {+ t.Setenv("TRACEWAY_ASSUME_YES", "1")+ cmd := newTestCmd()+ out := &bytes.Buffer{}+ cmd.SetOut(out)+ cmd.SetErr(out)+ cmd.SetIn(strings.NewReader(""))++ if err := confirmMutation(cmd, []string{"summary"}); err != nil {+ t.Fatalf("confirmMutation = %v, want nil", err)+ }+}++func TestConfirmMutation_nonTTYWithoutYes_returnsUsageError(t *testing.T) {+ cmd := newTestCmd()+ stderr := &bytes.Buffer{}+ cmd.SetOut(&bytes.Buffer{})+ cmd.SetErr(stderr)+ cmd.SetIn(strings.NewReader("")) // io.Reader, not *os.File → not a TTY++ err := confirmMutation(cmd, []string{"summary"})+ if err == nil {+ t.Fatal("expected error, got nil")+ }+ var ce *cliError+ if !errors.As(err, &ce) {+ t.Fatalf("expected *cliError, got %T", err)+ }+ if ce.code != exitcode.Usage {+ t.Errorf("exit code = %d, want %d", ce.code, exitcode.Usage)+ }+ if !strings.Contains(stderr.String(), "usage_error") {+ t.Errorf("stderr should contain usage_error envelope, got %q", stderr.String())+ }+}++func TestResolvePagination_defaults(t *testing.T) {+ cmd := &cobra.Command{Use: "fake"}+ addPaginationFlags(cmd)+ if err := cmd.ParseFlags(nil); err != nil {+ t.Fatal(err)+ }+ p := resolvePagination(cmd)+ if p.Page != 1 {+ t.Errorf("Page = %d, want 1", p.Page)+ }+ if p.PageSize != 50 {+ t.Errorf("PageSize = %d, want 50", p.PageSize)+ }+}++func TestAddPaginationFlags_pageDefaultIsOne(t *testing.T) {+ cmd := &cobra.Command{Use: "fake"}+ addPaginationFlags(cmd)+ f := cmd.Flags().Lookup("page")+ if f == nil {+ t.Fatal("--page flag not registered")+ }+ if f.DefValue != "1" {+ t.Errorf("--page default = %q, want \"1\"", f.DefValue)+ }+}++func TestResolvePagination_explicit(t *testing.T) {+ cmd := &cobra.Command{Use: "fake"}+ addPaginationFlags(cmd)+ if err := cmd.ParseFlags([]string{"--page", "3", "--page-size", "100"}); err != nil {+ t.Fatal(err)+ }+ p := resolvePagination(cmd)+ if p.Page != 3 {+ t.Errorf("Page = %d, want 3", p.Page)+ }+ if p.PageSize != 100 {+ t.Errorf("PageSize = %d, want 100", p.PageSize)+ }+}diff --git a/cli/cmd/traceway/root.go b/cli/cmd/traceway/root.gonew file mode 100644index 00000000..b76a31c2--- /dev/null+++ b/cli/cmd/traceway/root.go@@ -0,0 +1,41 @@+package main++import (+ "github.com/spf13/cobra"+)++// Global flag values, populated by Cobra at flag-parse time.+var (+ flagProfile string+ flagProject string+ flagOutput string+ flagFields string+ flagYes bool+)++func newRootCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "traceway",+ Short: "CLI for the Traceway observability platform",+ SilenceUsage: true, // we render our own error envelopes+ SilenceErrors: true,+ }++ pf := cmd.PersistentFlags()+ pf.StringVar(&flagProfile, "profile", "", "Profile name (default: current profile, then \"default\")")+ pf.StringVar(&flagProject, "project", "", "Project ID (default: profile's current project)")+ pf.StringVarP(&flagOutput, "output", "o", "", "Output format: json, yaml, or table (default: table on TTY, json otherwise)")+ pf.StringVar(&flagFields, "fields", "", "Comma-separated field projection (e.g. id,name)")+ pf.BoolVar(&flagYes, "yes", false, "Skip confirmation for mutating commands")++ cmd.AddCommand(newLoginCmd())+ cmd.AddCommand(newLogoutCmd())+ cmd.AddCommand(newProfilesCmd())+ cmd.AddCommand(newProjectsCmd())+ cmd.AddCommand(newExceptionsCmd())+ cmd.AddCommand(newLogsCmd())+ cmd.AddCommand(newEndpointsCmd())+ cmd.AddCommand(newMetricsCmd())++ return cmd+}diff --git a/cli/cmd/traceway/session.go b/cli/cmd/traceway/session.gonew file mode 100644index 00000000..42ad9e23--- /dev/null+++ b/cli/cmd/traceway/session.go@@ -0,0 +1,97 @@+package main++import (+ "errors"+ "fmt"+ "io"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++// session bundles everything a query command needs after resolving config,+// state, the active profile, and the project ID. Built by loadSession.+type session struct {+ ProfileName string+ URL string+ Username string+ JWT string+ ProjectID string+}++// Sentinel errors so the caller can map them to the right error envelope.+var (+ errSessionNoProfile = errors.New("session: no profile configured")+ errSessionNoJWT = errors.New("session: profile has no stored token")+ errSessionNoProject = errors.New("session: no project selected")+)++// loadSession reads config + state, resolves the active profile and project,+// and returns a session. Returns one of the errSession* sentinels on common+// "you need to configure something" failures so callers can render the+// matching error envelope.+func loadSession() (*session, error) {+ cfg, err := config.Load()+ if err != nil {+ return nil, fmt.Errorf("loading config: %w", err)+ }+ st, err := state.Load()+ if err != nil {+ return nil, fmt.Errorf("loading state: %w", err)+ }++ name := resolveProfileName(st)+ cp, hasCfg := cfg.Profiles[name]+ if !hasCfg {+ return nil, fmt.Errorf("%w: %q", errSessionNoProfile, name)+ }++ sp, hasState := st.Profiles[name]+ if !hasState || sp.JWT == "" {+ return nil, fmt.Errorf("%w: %q", errSessionNoJWT, name)+ }++ projectID := flagProject+ if projectID == "" {+ projectID = sp.CurrentProjectID+ }+ if projectID == "" {+ return nil, fmt.Errorf("%w: profile %q has no current project", errSessionNoProject, name)+ }++ return &session{+ ProfileName: name,+ URL: cp.URL,+ Username: cp.Username,+ JWT: sp.JWT,+ ProjectID: projectID,+ }, nil+}++// renderSessionError maps loadSession sentinel errors to envelopes.+func renderSessionError(errOut io.Writer, mode output.Mode, err error) error {+ switch {+ case errors.Is(err, errSessionNoProfile), errors.Is(err, errSessionNoJWT):+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "not_authenticated",+ Message: err.Error(),+ Hint: "traceway login",+ ExitCode: exitcode.Auth,+ })+ return newCLIError(exitcode.Auth, "not_authenticated")+ case errors.Is(err, errSessionNoProject):+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "no_project",+ Message: err.Error(),+ Hint: "traceway projects use <project-id> (or pass --project)",+ ExitCode: exitcode.Usage,+ })+ return newCLIError(exitcode.Usage, "no_project")+ }+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "internal", Message: err.Error(), ExitCode: exitcode.Generic,+ })+ return newCLIError(exitcode.Generic, "internal")+}diff --git a/cli/cmd/traceway/session_test.go b/cli/cmd/traceway/session_test.gonew file mode 100644index 00000000..fb423158--- /dev/null+++ b/cli/cmd/traceway/session_test.go@@ -0,0 +1,149 @@+package main++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func TestLoadSession_happyPath(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x", Username: "u"},+ }}+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "proj-1"}},+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }++ sess, err := loadSession()+ if err != nil {+ t.Fatalf("loadSession: %v", err)+ }+ if sess.URL != "https://x" {+ t.Errorf("URL = %q", sess.URL)+ }+ if sess.JWT != "tok" {+ t.Errorf("JWT = %q", sess.JWT)+ }+ if sess.ProjectID != "proj-1" {+ t.Errorf("ProjectID = %q", sess.ProjectID)+ }+ if sess.ProfileName != "default" {+ t.Errorf("ProfileName = %q", sess.ProfileName)+ }+}++func TestLoadSession_flagProjectOverridesState(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ }}+ _ = cfg.Save()+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "proj-default"}},+ }+ _ = st.Save()++ flagProject = "proj-override"+ sess, err := loadSession()+ if err != nil {+ t.Fatal(err)+ }+ if sess.ProjectID != "proj-override" {+ t.Errorf("ProjectID = %q, want proj-override", sess.ProjectID)+ }+}++func TestLoadSession_missingProfile_returnsNotAuthenticated(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ _, err := loadSession()+ if !errors.Is(err, errSessionNoProfile) {+ t.Errorf("got %v, want errSessionNoProfile", err)+ }+}++func TestLoadSession_profileWithoutJWT_returnsNotAuthenticated(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ }}+ _ = cfg.Save()+ // State exists but has no JWT for this profile.+ st := &state.State{CurrentProfile: "default", Profiles: map[string]state.ProfileState{}}+ _ = st.Save()++ _, err := loadSession()+ if !errors.Is(err, errSessionNoJWT) {+ t.Errorf("got %v, want errSessionNoJWT", err)+ }+}++func TestLoadSession_missingProject_returnsNoProject(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ }}+ _ = cfg.Save()+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok"}}, // no current_project_id+ }+ _ = st.Save()++ _, err := loadSession()+ if !errors.Is(err, errSessionNoProject) {+ t.Errorf("got %v, want errSessionNoProject", err)+ }+}++// Sanity-check: a session built against an httptest server and an HTTP probe+// works end-to-end (smoke for caller patterns).+func TestLoadSession_pointsAtRealServer(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(204)+ }))+ defer srv.Close()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{"default": {URL: srv.URL}}}+ _ = cfg.Save()+ st := &state.State{CurrentProfile: "default", Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "p"}}}+ _ = st.Save()++ sess, err := loadSession()+ if err != nil {+ t.Fatal(err)+ }+ if sess.URL != srv.URL {+ t.Errorf("URL mismatch")+ }+}diff --git a/cli/cmd/traceway/testutil_test.go b/cli/cmd/traceway/testutil_test.gonew file mode 100644index 00000000..2183c4ec--- /dev/null+++ b/cli/cmd/traceway/testutil_test.go@@ -0,0 +1,38 @@+package main++import (+ "bytes"+ "io"+ "strings"+ "testing"+)++// runCmd executes the given args against a fresh root command, with stdin/out/err+// captured into buffers. It returns the buffers and the error from Execute().+//+// Each test should also call t.Setenv("XDG_CONFIG_HOME", t.TempDir()) so that+// config writes are isolated.+func runCmd(t *testing.T, stdin string, args ...string) (stdout, stderr *bytes.Buffer, err error) {+ t.Helper()+ stdout = &bytes.Buffer{}+ stderr = &bytes.Buffer{}++ cmd := newRootCmd()+ cmd.SetIn(strings.NewReader(stdin))+ cmd.SetOut(stdout)+ cmd.SetErr(stderr)+ cmd.SetArgs(args)+ err = cmd.Execute()+ return+}++// readAll consumes a bytes.Buffer entirely; useful when a test needs the+// trailing bytes after Execute returned.+func readAll(t *testing.T, r io.Reader) string { //nolint:unused+ t.Helper()+ b, err := io.ReadAll(r)+ if err != nil {+ t.Fatalf("readAll: %v", err)+ }+ return string(b)+}diff --git a/cli/cmd/traceway/timerange.go b/cli/cmd/traceway/timerange.gonew file mode 100644index 00000000..fdbbc949--- /dev/null+++ b/cli/cmd/traceway/timerange.go@@ -0,0 +1,96 @@+package main++import (+ "errors"+ "fmt"+ "io"+ "strconv"+ "strings"+ "time"++ "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"+)++// errInvalidTimeRange is returned for any malformed combination of+// --since / --from / --to. Callers map this to the invalid_time_range+// error envelope code with exit 2 (usage).+var errInvalidTimeRange = errors.New("invalid time range")++// addTimeRangeFlags registers --since, --from, --to on the given command.+// The default (no flags) is "since 1h".+func addTimeRangeFlags(cmd *cobra.Command) {+ f := cmd.Flags()+ f.String("since", "", "Relative time range, e.g. 1h, 24h, 7d (default: 1h, mutually exclusive with --from/--to)")+ f.String("from", "", "Start of explicit time range, RFC3339 (mutually exclusive with --since)")+ f.String("to", "", "End of explicit time range, RFC3339 (required with --from)")+}++// resolveTimeRange validates the combination of --since/--from/--to on cmd+// and returns the resulting TimeRange. The default (none of the flags) is+// "last 1 hour".+func resolveTimeRange(cmd *cobra.Command) (client.TimeRange, error) {+ since, _ := cmd.Flags().GetString("since")+ from, _ := cmd.Flags().GetString("from")+ to, _ := cmd.Flags().GetString("to")++ if since != "" && (from != "" || to != "") {+ return client.TimeRange{}, fmt.Errorf("%w: --since cannot be combined with --from/--to", errInvalidTimeRange)+ }+ if (from != "") != (to != "") {+ return client.TimeRange{}, fmt.Errorf("%w: --from and --to must be used together", errInvalidTimeRange)+ }++ if from != "" {+ fromT, err := time.Parse(time.RFC3339, from)+ if err != nil {+ return client.TimeRange{}, fmt.Errorf("%w: --from: %v", errInvalidTimeRange, err)+ }+ toT, err := time.Parse(time.RFC3339, to)+ if err != nil {+ return client.TimeRange{}, fmt.Errorf("%w: --to: %v", errInvalidTimeRange, err)+ }+ return client.TimeRangeFromExplicit(fromT, toT), nil+ }++ dur := time.Hour+ if since != "" {+ d, err := parseRelativeDuration(since)+ if err != nil {+ return client.TimeRange{}, fmt.Errorf("%w: --since: %v", errInvalidTimeRange, err)+ }+ dur = d+ }+ return client.TimeRangeFromSince(dur), nil+}++// parseRelativeDuration accepts time.ParseDuration's standard input plus a+// simple "Nd" form (positive integer days) which time.ParseDuration rejects.+// Compound forms like "7d2h" or "7D" are not supported on purpose.+func parseRelativeDuration(s string) (time.Duration, error) {+ if prefix, ok := strings.CutSuffix(s, "d"); ok {+ n, err := strconv.Atoi(prefix)+ if err != nil {+ return 0, fmt.Errorf("invalid duration %q", s)+ }+ if n <= 0 {+ return 0, fmt.Errorf("invalid duration %q: must be positive", s)+ }+ return time.Duration(n) * 24 * time.Hour, nil+ }+ return time.ParseDuration(s)+}++// renderTimeRangeError maps errInvalidTimeRange (from resolveTimeRange) to an envelope.+func renderTimeRangeError(errOut io.Writer, mode output.Mode, err error) error {+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "invalid_time_range",+ Message: err.Error(),+ Hint: "use --since DURATION (e.g. 1h, 24h, 7d) or --from RFC3339 --to RFC3339",+ ExitCode: exitcode.Usage,+ })+ return newCLIError(exitcode.Usage, "invalid_time_range")+}diff --git a/cli/cmd/traceway/timerange_test.go b/cli/cmd/traceway/timerange_test.gonew file mode 100644index 00000000..475347ef--- /dev/null+++ b/cli/cmd/traceway/timerange_test.go@@ -0,0 +1,200 @@+package main++import (+ "errors"+ "testing"+ "time"++ "github.com/spf13/cobra"+)++// helper to build a fake command with the time-range flags wired+func newCmdWithTimeFlags(t *testing.T) *cobra.Command {+ t.Helper()+ cmd := &cobra.Command{Use: "fake"}+ addTimeRangeFlags(cmd)+ return cmd+}++func TestResolveTimeRange_defaultIsLastHour(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags(nil); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ delta := tr.To.Sub(tr.From)+ if delta < 59*time.Minute || delta > 61*time.Minute {+ t.Errorf("default range should be ~1h, got %v", delta)+ }+}++func TestResolveTimeRange_sinceFlag(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "30m"}); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ delta := tr.To.Sub(tr.From)+ if delta < 29*time.Minute || delta > 31*time.Minute {+ t.Errorf("--since 30m should give ~30m range, got %v", delta)+ }+}++func TestResolveTimeRange_fromTo(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{+ "--from", "2026-05-13T00:00:00Z",+ "--to", "2026-05-13T23:59:59Z",+ }); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ wantFrom, _ := time.Parse(time.RFC3339, "2026-05-13T00:00:00Z")+ wantTo, _ := time.Parse(time.RFC3339, "2026-05-13T23:59:59Z")+ if !tr.From.Equal(wantFrom) {+ t.Errorf("From = %v, want %v", tr.From, wantFrom)+ }+ if !tr.To.Equal(wantTo) {+ t.Errorf("To = %v, want %v", tr.To, wantTo)+ }+}++func TestResolveTimeRange_sinceAndFromAreMutuallyExclusive(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{+ "--since", "1h",+ "--from", "2026-05-13T00:00:00Z",+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected mutual-exclusivity error")+ }+}++func TestResolveTimeRange_fromWithoutTo(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--from", "2026-05-13T00:00:00Z"}); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected error: --from requires --to")+ }+}++func TestResolveTimeRange_invalidFromFormat(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{+ "--from", "not-a-date",+ "--to", "2026-05-13T23:59:59Z",+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected parse error")+ }+}++func TestResolveTimeRange_invalidSinceDuration(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "invalid"}); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected duration parse error")+ }+}++func TestParseRelativeDuration_validInputs(t *testing.T) {+ cases := []struct {+ in string+ want time.Duration+ }{+ {"1h", time.Hour},+ {"24h", 24 * time.Hour},+ {"7d", 168 * time.Hour},+ {"30d", 720 * time.Hour},+ {"1d", 24 * time.Hour},+ {"30m", 30 * time.Minute},+ }+ for _, tc := range cases {+ t.Run(tc.in, func(t *testing.T) {+ got, err := parseRelativeDuration(tc.in)+ if err != nil {+ t.Fatalf("parseRelativeDuration(%q) error: %v", tc.in, err)+ }+ if got != tc.want {+ t.Errorf("parseRelativeDuration(%q) = %v, want %v", tc.in, got, tc.want)+ }+ })+ }+}++func TestParseRelativeDuration_invalidInputs(t *testing.T) {+ cases := []string{+ "0d",+ "-1d",+ "7days",+ "7D",+ "7d2h",+ "d",+ "notaduration",+ "",+ }+ for _, in := range cases {+ t.Run(in, func(t *testing.T) {+ if _, err := parseRelativeDuration(in); err == nil {+ t.Errorf("parseRelativeDuration(%q) expected error, got nil", in)+ }+ })+ }+}++func TestResolveTimeRange_sinceDays(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "7d"}); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ delta := tr.To.Sub(tr.From)+ want := 168 * time.Hour+ if delta < want-time.Minute || delta > want+time.Minute {+ t.Errorf("--since 7d should give ~168h range, got %v", delta)+ }+}++func TestResolveTimeRange_sinceZeroDaysRejected(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "0d"}); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected error for --since 0d")+ }+}++func TestResolveTimeRange_invalidSinceStillWrapsErrInvalidTimeRange(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "notaduration"}); err != nil {+ t.Fatal(err)+ }+ _, err := resolveTimeRange(cmd)+ if err == nil {+ t.Fatal("expected error")+ }+ if !errors.Is(err, errInvalidTimeRange) {+ t.Errorf("error %v should wrap errInvalidTimeRange", err)+ }+}diff --git a/cli/docs/superpowers/plans/2026-05-13-traceway-cli-foundation.md b/cli/docs/superpowers/plans/2026-05-13-traceway-cli-foundation.mdnew file mode 100644index 00000000..81247bd7--- /dev/null+++ b/cli/docs/superpowers/plans/2026-05-13-traceway-cli-foundation.md@@ -0,0 +1,3609 @@+# traceway-cli Foundation Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Build the foundation of traceway-cli — module bootstrap, HTTP client skeleton, config storage, output renderers, and a working `login` → `projects list` vertical slice. End state: a CLI that authenticates against a Traceway instance and lists projects in JSON, YAML, or table format, with proper error handling and profile management.++**Architecture:** Library-first split — `pkg/client` is a pure HTTP+types library (importable by a future MCP server), `internal/config` and `internal/output` are CLI-only. `cmd/traceway/*.go` files are thin glue: parse flags → load config → call client → render output.++**Tech Stack:** Go (stdlib `net/http`), Cobra (CLI framework), Viper (env-var binding only), `golang.org/x/term` (password reading + TTY detection), `gopkg.in/yaml.v3` (YAML output), `text/tabwriter` (tables), `httptest` (tests).++---++## File Map++This plan creates the following files. Each task lists exactly which files it touches.++```+.gitignore (modify — add .go/)+flake.nix (modify — add `just` to dev shell)+justfile (create)+go.mod (create — via go mod init)++internal/exitcode/codes.go (create)+internal/exitcode/codes_test.go (create)++internal/config/paths.go (create)+internal/config/paths_test.go (create)+internal/config/config.go (create)+internal/config/config_test.go (create)++pkg/client/errors.go (create)+pkg/client/errors_test.go (create)+pkg/client/client.go (create)+pkg/client/client_test.go (create)+pkg/client/auth.go (create)+pkg/client/auth_test.go (create)+pkg/client/projects.go (create)+pkg/client/projects_test.go (create)++internal/output/format.go (create)+internal/output/format_test.go (create)+internal/output/json.go (create)+internal/output/json_test.go (create)+internal/output/yaml.go (create)+internal/output/yaml_test.go (create)+internal/output/table.go (create)+internal/output/error.go (create)+internal/output/error_test.go (create)++cmd/traceway/main.go (create)+cmd/traceway/root.go (create)+cmd/traceway/testutil_test.go (create — shared test helpers)+cmd/traceway/login.go (create)+cmd/traceway/login_test.go (create)+cmd/traceway/logout.go (create)+cmd/traceway/logout_test.go (create)+cmd/traceway/profiles.go (create)+cmd/traceway/profiles_test.go (create)+cmd/traceway/projects.go (create)+cmd/traceway/projects_test.go (create)+cmd/traceway/errors.go (create — handleAPIError helper)+cmd/traceway/errors_test.go (create)+```++**File responsibilities:**++- **`internal/exitcode`** — single source of truth for stable exit codes. No deps.+- **`internal/config`** — credential and profile storage (`config.json`). No CLI deps.+- **`pkg/client`** — HTTP client and typed responses. No CLI/config/output deps. The reusable surface.+- **`internal/output`** — rendering JSON/YAML/table and the error envelope. Depends on `exitcode` only.+- **`cmd/traceway`** — Cobra subcommands. Glue — parse flags, call client, call output.++---++## Task 1: Bootstrap module and tooling++**Files:**+- Create: `go.mod` (via `go mod init`)+- Modify: `.gitignore` (currently contains `.go/` already per dev shell — verify)+- Modify: `flake.nix` (add `just` to dev shell)+- Create: `justfile`++- [ ] **Step 1: Initialize the Go module**++Run: `go mod init github.com/tracewayapp/traceway/cli`+Expected: creates `go.mod` with `module github.com/tracewayapp/traceway/cli` and the current Go version.++- [ ] **Step 2: Verify `.gitignore` contains `.go/`**++Read `.gitignore`. If it doesn't already contain `.go/`, add it. The dev shell pins `GOPATH`/`GOCACHE`/`GOBIN` inside `.go/` and we don't want those committed.++Expected `.gitignore` contents (at minimum):+```+.go/+```++- [ ] **Step 3: Add `just` to the Nix dev shell**++Read `flake.nix`. Find the `buildInputs` (or `packages`) list inside `mkShell`. Add `just` to it.++For example, if you see:+```nix+buildInputs = with pkgs; [ go gopls gotools delve gofumpt gomodifytags impl gotestsum golangci-lint govulncheck gh git jq ];+```+Change to:+```nix+buildInputs = with pkgs; [ go gopls gotools delve gofumpt gomodifytags impl gotestsum golangci-lint govulncheck gh git jq just ];+```++- [ ] **Step 4: Create the justfile**++Create `justfile` (no extension) at the repo root:++```just+default: test++test:+ gotestsum --format pkgname -- ./...++smoke-test:+ gotestsum --format pkgname -- -tags smoke ./test/smoke/...++lint:+ golangci-lint run++vulncheck:+ govulncheck ./...++# Run everything that should pass before a commit+check: lint test vulncheck+```++- [ ] **Step 5: Verify the toolchain works**++Run: `nix develop --command which just`+Expected: a path under `/nix/store/...`.++Run: `nix develop --command go mod download`+Expected: no output (no deps yet) and exit 0.++Run: `nix develop --command just --list`+Expected: lists `default`, `test`, `smoke-test`, `lint`, `vulncheck`, `check`.++Note: Do **not** run `just test` yet — there are no tests.++- [ ] **Step 6: Commit**++```bash+git add go.mod .gitignore flake.nix justfile+git commit -m "chore: bootstrap go module, justfile, just in dev shell"+```++---++## Task 2: Exit code constants++**Files:**+- Create: `internal/exitcode/codes.go`+- Test: `internal/exitcode/codes_test.go`++- [ ] **Step 1: Write the failing test**++Create `internal/exitcode/codes_test.go`:++```go+package exitcode++import "testing"++func TestCodes_areStable(t *testing.T) {+ cases := []struct {+ name string+ got int+ want int+ }{+ {"Success", Success, 0},+ {"Generic", Generic, 1},+ {"Usage", Usage, 2},+ {"Connection", Connection, 3},+ {"Auth", Auth, 4},+ {"NotFound", NotFound, 5},+ {"RateLimited", RateLimited, 6},+ {"Server", Server, 7},+ }+ for _, c := range cases {+ if c.got != c.want {+ t.Errorf("%s = %d, want %d", c.name, c.got, c.want)+ }+ }+}+```++- [ ] **Step 2: Run the test, verify it fails**++Run: `go test ./internal/exitcode/...`+Expected: build failure — `undefined: Success` (etc.).++- [ ] **Step 3: Implement the constants**++Create `internal/exitcode/codes.go`:++```go+// Package exitcode defines the stable exit codes emitted by the traceway CLI.+// LLMs and scripts may branch on these values; do not renumber.+package exitcode++const (+ Success = 0+ Generic = 1+ Usage = 2+ Connection = 3+ Auth = 4+ NotFound = 5+ RateLimited = 6+ Server = 7+)+```++- [ ] **Step 4: Run the test, verify it passes**++Run: `go test ./internal/exitcode/...`+Expected: `ok github.com/tracewayapp/traceway/cli/internal/exitcode`.++- [ ] **Step 5: Commit**++```bash+git add internal/exitcode/+git commit -m "feat(exitcode): define stable exit code constants"+```++---++## Task 3: Config — XDG path resolution++**Files:**+- Create: `internal/config/paths.go`+- Test: `internal/config/paths_test.go`++- [ ] **Step 1: Write the failing test**++Create `internal/config/paths_test.go`:++```go+package config++import (+ "path/filepath"+ "testing"+)++func TestConfigPath_xdgSet(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", "/tmp/xdg")+ t.Setenv("HOME", "/tmp/home")++ got, err := configPath()+ if err != nil {+ t.Fatalf("configPath() error: %v", err)+ }+ want := filepath.Join("/tmp/xdg", "traceway", "config.json")+ if got != want {+ t.Errorf("configPath() = %q, want %q", got, want)+ }+}++func TestConfigPath_xdgUnset(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", "")+ t.Setenv("HOME", "/tmp/home")++ got, err := configPath()+ if err != nil {+ t.Fatalf("configPath() error: %v", err)+ }+ want := filepath.Join("/tmp/home", ".config", "traceway", "config.json")+ if got != want {+ t.Errorf("configPath() = %q, want %q", got, want)+ }+}++func TestConfigPath_neither(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", "")+ t.Setenv("HOME", "")++ if _, err := configPath(); err == nil {+ t.Fatal("expected error when both XDG_CONFIG_HOME and HOME are empty")+ }+}+```++- [ ] **Step 2: Run the test, verify it fails**++Run: `go test ./internal/config/...`+Expected: build failure — `undefined: configPath`.++- [ ] **Step 3: Implement `configPath`**++Create `internal/config/paths.go`:++```go+package config++import (+ "errors"+ "os"+ "path/filepath"+)++// 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+ }+ 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+}+```++- [ ] **Step 4: Run the test, verify it passes**++Run: `go test ./internal/config/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/config/+git commit -m "feat(config): resolve XDG-aware config path"+```++---++## Task 4: Config — types and Load++**Files:**+- Create: `internal/config/config.go`+- Modify: `internal/config/config_test.go` (create)++- [ ] **Step 1: Write the failing tests**++Create `internal/config/config_test.go`:++```go+package config++import (+ "os"+ "path/filepath"+ "testing"+)++func TestLoad_missingFile_returnsEmpty(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ if cfg == nil {+ t.Fatal("Load() returned nil cfg")+ }+ if len(cfg.Profiles) != 0 {+ t.Errorf("expected empty Profiles, got %v", cfg.Profiles)+ }+ if cfg.CurrentProfile != "" {+ t.Errorf("expected empty CurrentProfile, got %q", cfg.CurrentProfile)+ }+}++func TestLoad_existingFile_readsJSON(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)+ if err := os.MkdirAll(filepath.Join(dir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }+ body := `{+ "current_profile": "stormwind",+ "profiles": {+ "stormwind": {+ "url": "https://traceway.stormwind.local",+ "username": "[email protected]",+ "jwt": "abc.def.ghi",+ "current_project_id": "proj-1"+ }+ }+ }`+ if err := os.WriteFile(filepath.Join(dir, "traceway", "config.json"), []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ if cfg.CurrentProfile != "stormwind" {+ t.Errorf("CurrentProfile = %q, want %q", cfg.CurrentProfile, "stormwind")+ }+ p, ok := cfg.Profiles["stormwind"]+ if !ok {+ t.Fatal("stormwind profile not loaded")+ }+ if p.URL != "https://traceway.stormwind.local" {+ t.Errorf("URL = %q", p.URL)+ }+ if p.JWT != "abc.def.ghi" {+ t.Errorf("JWT = %q", p.JWT)+ }+ if p.CurrentProjectID != "proj-1" {+ t.Errorf("CurrentProjectID = %q", p.CurrentProjectID)+ }+}++func TestLoad_corruptFile_returnsError(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)+ if err := os.MkdirAll(filepath.Join(dir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "traceway", "config.json"), []byte("not json"), 0o600); err != nil {+ t.Fatal(err)+ }++ if _, err := Load(); err == nil {+ t.Fatal("expected Load() to fail on corrupt JSON")+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/config/...`+Expected: build failure — `undefined: Load`, `undefined: Config`.++- [ ] **Step 3: Implement `Config` and `Load`**++Create `internal/config/config.go`:++```go+package config++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+)++// Config is the on-disk credential and preference file.+type Config struct {+ CurrentProfile string `json:"current_profile"`+ Profiles map[string]Profile `json:"profiles"`+}++// Profile holds credentials and preferences for a single Traceway instance.+type Profile struct {+ URL string `json:"url"`+ Username string `json:"username"`+ JWT string `json:"jwt"`+ CurrentProjectID string `json:"current_project_id,omitempty"`+}++// Load reads the config file from disk. A missing file yields an empty Config+// (not an error) — the caller treats absence of credentials as an auth error+// only when an actual command needs them.+func Load() (*Config, error) {+ path, err := configPath()+ if err != nil {+ return nil, err+ }+ data, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return &Config{Profiles: map[string]Profile{}}, nil+ }+ if err != nil {+ return nil, fmt.Errorf("reading config: %w", err)+ }+ var cfg Config+ if err := json.Unmarshal(data, &cfg); err != nil {+ return nil, fmt.Errorf("parsing config %s: %w", path, err)+ }+ if cfg.Profiles == nil {+ cfg.Profiles = map[string]Profile{}+ }+ return &cfg, nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./internal/config/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/config/+git commit -m "feat(config): define Config/Profile types and Load"+```++---++## Task 5: Config — atomic Save with strict perms++**Files:**+- Modify: `internal/config/config.go` (add `Save` method)+- Modify: `internal/config/config_test.go` (add tests for `Save`)++- [ ] **Step 1: Write the failing tests**++Append to `internal/config/config_test.go`:++```go+func TestSave_writesAtomicallyWith0600(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)++ cfg := &Config{+ CurrentProfile: "default",+ Profiles: map[string]Profile{+ "default": {+ URL: "https://cloud.traceway.com",+ Username: "[email protected]",+ JWT: "tok",+ },+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatalf("Save() error: %v", err)+ }++ path := filepath.Join(dir, "traceway", "config.json")+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if perm := info.Mode().Perm(); perm != 0o600 {+ t.Errorf("file perm = %o, want 0600", perm)+ }++ dirInfo, err := os.Stat(filepath.Join(dir, "traceway"))+ if err != nil {+ t.Fatalf("stat dir: %v", err)+ }+ if perm := dirInfo.Mode().Perm(); perm != 0o700 {+ t.Errorf("dir perm = %o, want 0700", perm)+ }+}++func TestSave_overwritesExisting(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)++ first := &Config{+ Profiles: map[string]Profile{"a": {URL: "https://a"}},+ }+ if err := first.Save(); err != nil {+ t.Fatalf("first Save: %v", err)+ }++ second := &Config{+ Profiles: map[string]Profile{"b": {URL: "https://b"}},+ }+ if err := second.Save(); err != nil {+ t.Fatalf("second Save: %v", err)+ }++ loaded, err := Load()+ if err != nil {+ t.Fatalf("Load: %v", err)+ }+ if _, ok := loaded.Profiles["a"]; ok {+ t.Error("profile 'a' should have been overwritten")+ }+ if _, ok := loaded.Profiles["b"]; !ok {+ t.Error("profile 'b' should exist after second Save")+ }+}++func TestSave_thenLoad_roundTrips(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ want := &Config{+ CurrentProfile: "stormwind",+ Profiles: map[string]Profile{+ "stormwind": {+ URL: "https://traceway.stormwind.local",+ Username: "[email protected]",+ JWT: "tok",+ CurrentProjectID: "proj-1",+ },+ },+ }+ if err := want.Save(); err != nil {+ t.Fatal(err)+ }+ got, err := Load()+ if err != nil {+ t.Fatal(err)+ }+ if got.CurrentProfile != want.CurrentProfile {+ t.Errorf("CurrentProfile mismatch")+ }+ if got.Profiles["stormwind"] != want.Profiles["stormwind"] {+ t.Errorf("Profile mismatch: got %+v want %+v", got.Profiles["stormwind"], want.Profiles["stormwind"])+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/config/...`+Expected: build failure — `cfg.Save undefined`.++- [ ] **Step 3: Implement `Save`**++Append to `internal/config/config.go`:++```go+import (+ "path/filepath"+)++// Save atomically writes the config to disk. Creates parent dirs (0700) and the+// file (0600). Atomicity is achieved by writing to a tempfile in the same+// directory and renaming over the destination.+func (c *Config) Save() error {+ path, err := configPath()+ if err != nil {+ return err+ }+ dir := filepath.Dir(path)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return fmt.Errorf("creating config dir: %w", err)+ }++ data, err := json.MarshalIndent(c, "", " ")+ if err != nil {+ return fmt.Errorf("marshalling config: %w", err)+ }++ tmp, err := os.CreateTemp(dir, ".config.json.*")+ if err != nil {+ return fmt.Errorf("creating temp file: %w", err)+ }+ tmpName := tmp.Name()+ defer os.Remove(tmpName) // no-op if rename succeeded++ if err := tmp.Chmod(0o600); err != nil {+ tmp.Close()+ return fmt.Errorf("chmod temp: %w", err)+ }+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return fmt.Errorf("writing temp: %w", err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("closing temp: %w", err)+ }+ if err := os.Rename(tmpName, path); err != nil {+ return fmt.Errorf("renaming into place: %w", err)+ }+ return nil+}+```++Make sure the imports at the top of the file include `path/filepath`. Combine with the existing import block.++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./internal/config/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/config/+git commit -m "feat(config): atomic Save with strict 0600/0700 perms"+```++---++## Task 6: Config — Active profile resolution++**Files:**+- Modify: `internal/config/config.go` (add `Active` method)+- Modify: `internal/config/config_test.go` (add tests)++- [ ] **Step 1: Write the failing tests**++Append to `internal/config/config_test.go`:++```go+func TestActive_explicitName(t *testing.T) {+ cfg := &Config{+ CurrentProfile: "stormwind",+ Profiles: map[string]Profile{+ "stormwind": {URL: "https://a"},+ "cloud": {URL: "https://b"},+ },+ }+ p, err := cfg.Active("cloud")+ if err != nil {+ t.Fatal(err)+ }+ if p.URL != "https://b" {+ t.Errorf("got %q, want https://b", p.URL)+ }+}++func TestActive_emptyName_usesCurrentProfile(t *testing.T) {+ cfg := &Config{+ CurrentProfile: "stormwind",+ Profiles: map[string]Profile{+ "stormwind": {URL: "https://a"},+ },+ }+ p, err := cfg.Active("")+ if err != nil {+ t.Fatal(err)+ }+ if p.URL != "https://a" {+ t.Errorf("got %q, want https://a", p.URL)+ }+}++func TestActive_emptyName_emptyCurrent_usesDefault(t *testing.T) {+ cfg := &Config{+ Profiles: map[string]Profile{+ "default": {URL: "https://d"},+ },+ }+ p, err := cfg.Active("")+ if err != nil {+ t.Fatal(err)+ }+ if p.URL != "https://d" {+ t.Errorf("got %q, want https://d", p.URL)+ }+}++func TestActive_unknownName_returnsError(t *testing.T) {+ cfg := &Config{+ Profiles: map[string]Profile{"default": {URL: "https://d"}},+ }+ if _, err := cfg.Active("nonexistent"); err == nil {+ t.Fatal("expected error for unknown profile")+ }+}++func TestActive_emptyConfig_returnsError(t *testing.T) {+ cfg := &Config{Profiles: map[string]Profile{}}+ if _, err := cfg.Active(""); err == nil {+ t.Fatal("expected error when no profiles exist")+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/config/...`+Expected: build failure — `cfg.Active undefined`.++- [ ] **Step 3: Implement `Active`**++Append to `internal/config/config.go`:++```go+// ErrProfileNotFound is returned by Active when the requested profile does not+// exist in the config.+var ErrProfileNotFound = errors.New("profile not found")++// Active resolves the effective profile by precedence:+//+// explicit name (e.g. from --profile) > c.CurrentProfile > "default"+//+// Returns ErrProfileNotFound if the resolved name has no profile in the config.+func (c *Config) Active(name string) (*Profile, error) {+ resolved := name+ if resolved == "" {+ resolved = c.CurrentProfile+ }+ if resolved == "" {+ resolved = "default"+ }+ p, ok := c.Profiles[resolved]+ if !ok {+ return nil, fmt.Errorf("%w: %q", ErrProfileNotFound, resolved)+ }+ return &p, nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./internal/config/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/config/+git commit -m "feat(config): Active profile resolution with --profile precedence"+```++---++## Task 7: pkg/client — typed errors++**Files:**+- Create: `pkg/client/errors.go`+- Test: `pkg/client/errors_test.go`++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/errors_test.go`:++```go+package client++import (+ "errors"+ "testing"+)++func TestAPIError_Error(t *testing.T) {+ e := &APIError{StatusCode: 500, Body: "boom"}+ got := e.Error()+ if got == "" {+ t.Fatal("Error() returned empty string")+ }+}++func TestSentinelErrors_areDistinct(t *testing.T) {+ all := []error{ErrUnauthorized, ErrForbidden, ErrNotFound, ErrRateLimited}+ for i, a := range all {+ for j, b := range all {+ if i == j {+ continue+ }+ if errors.Is(a, b) {+ t.Errorf("errors.Is(%v, %v) = true; expected distinct", a, b)+ }+ }+ }+}++func TestAPIError_doesNotMatchSentinels(t *testing.T) {+ apiErr := &APIError{StatusCode: 418}+ if errors.Is(apiErr, ErrUnauthorized) {+ t.Error("APIError(418) should not match ErrUnauthorized")+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./pkg/client/...`+Expected: build failure — undefined identifiers.++- [ ] **Step 3: Implement the error types**++Create `pkg/client/errors.go`:++```go+// Package client is the HTTP client and types for talking to a Traceway instance.+//+// This package has no dependencies on Cobra, Viper, or any CLI machinery so+// that a future MCP server can import it directly.+package client++import (+ "errors"+ "fmt"+)++// Sentinel errors returned by client methods. Use errors.Is to test.+var (+ ErrUnauthorized = errors.New("unauthorized (401)")+ ErrForbidden = errors.New("forbidden (403)")+ ErrNotFound = errors.New("not found (404)")+ ErrRateLimited = errors.New("rate limited (429)")+)++// APIError is returned for any non-2xx response that isn't covered by a sentinel.+// Inspect StatusCode and Body for diagnostics.+type APIError struct {+ StatusCode int+ Body string+}++func (e *APIError) Error() string {+ if e.Body == "" {+ return fmt.Sprintf("traceway API error: status %d", e.StatusCode)+ }+ return fmt.Sprintf("traceway API error: status %d: %s", e.StatusCode, e.Body)+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./pkg/client/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/+git commit -m "feat(client): define typed errors and APIError"+```++---++## Task 8: pkg/client — Client struct and `do()` helper++**Files:**+- Create: `pkg/client/client.go`+- Test: `pkg/client/client_test.go`++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/client_test.go`:++```go+package client++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestNew_setsDefaults(t *testing.T) {+ c := New("https://example.com")+ if c.BaseURL != "https://example.com" {+ t.Errorf("BaseURL = %q", c.BaseURL)+ }+ if c.HTTPClient == nil {+ t.Error("HTTPClient should default to a non-nil client")+ }+ if c.UserAgent == "" {+ t.Error("UserAgent should have a default value")+ }+}++func TestWithJWT_setsJWT(t *testing.T) {+ c := New("https://example.com", WithJWT("tok"))+ if c.JWT != "tok" {+ t.Errorf("JWT = %q", c.JWT)+ }+}++func TestDo_setsHeadersAndDecodes(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.Header.Get("Content-Type"); got != "application/json" {+ t.Errorf("Content-Type = %q", got)+ }+ if got := r.Header.Get("Authorization"); got != "Bearer tok" {+ t.Errorf("Authorization = %q", got)+ }+ if got := r.Header.Get("User-Agent"); !strings.HasPrefix(got, "traceway-cli") {+ t.Errorf("User-Agent = %q", got)+ }+ var body map[string]string+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["foo"] != "bar" {+ t.Errorf("body.foo = %q", body["foo"])+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"ok": true}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ var resp struct {+ OK bool `json:"ok"`+ }+ err := c.do(context.Background(), http.MethodPost, "/api/test", map[string]string{"foo": "bar"}, &resp)+ if err != nil {+ t.Fatalf("do(): %v", err)+ }+ if !resp.OK {+ t.Error("expected resp.OK = true")+ }+}++func TestDo_omitsAuthHeaderWhenJWTEmpty(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.Header.Get("Authorization"); got != "" {+ t.Errorf("expected no Authorization header, got %q", got)+ }+ w.Write([]byte(`{}`))+ }))+ defer srv.Close()++ c := New(srv.URL)+ var resp struct{}+ if err := c.do(context.Background(), http.MethodPost, "/api/x", nil, &resp); err != nil {+ t.Fatal(err)+ }+}++func TestDo_mapsStatusCodes(t *testing.T) {+ cases := []struct {+ status int+ want error+ }{+ {401, ErrUnauthorized},+ {403, ErrForbidden},+ {404, ErrNotFound},+ {429, ErrRateLimited},+ }+ for _, c := range cases {+ c := c+ t.Run(http.StatusText(c.status), func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(c.status)+ }))+ defer srv.Close()++ cli := New(srv.URL)+ var resp struct{}+ err := cli.do(context.Background(), http.MethodPost, "/api/x", nil, &resp)+ if !errors.Is(err, c.want) {+ t.Errorf("got %v, want errors.Is(_, %v)", err, c.want)+ }+ })+ }+}++func TestDo_returnsAPIErrorForOtherStatus(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(500)+ _, _ = w.Write([]byte("boom"))+ }))+ defer srv.Close()++ cli := New(srv.URL)+ var resp struct{}+ err := cli.do(context.Background(), http.MethodPost, "/api/x", nil, &resp)+ var apiErr *APIError+ if !errors.As(err, &apiErr) {+ t.Fatalf("expected APIError, got %T: %v", err, err)+ }+ if apiErr.StatusCode != 500 {+ t.Errorf("StatusCode = %d", apiErr.StatusCode)+ }+ if apiErr.Body != "boom" {+ t.Errorf("Body = %q", apiErr.Body)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./pkg/client/...`+Expected: build failure — `undefined: New`, `undefined: WithJWT`, `cli.do undefined`.++- [ ] **Step 3: Implement the Client**++Create `pkg/client/client.go`:++```go+package client++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++// Client talks to a Traceway HTTP API.+type Client struct {+ BaseURL string+ HTTPClient *http.Client+ JWT string+ UserAgent string+}++// Option mutates a Client during construction.+type Option func(*Client)++// New returns a Client with sane defaults. The baseURL is normalized by+// stripping trailing slashes; do() prepends "/api/..." paths.+func New(baseURL string, opts ...Option) *Client {+ c := &Client{+ BaseURL: strings.TrimRight(baseURL, "/"),+ HTTPClient: &http.Client{Timeout: 30 * time.Second},+ UserAgent: "traceway-cli/0.1",+ }+ for _, opt := range opts {+ opt(c)+ }+ return c+}++// WithHTTPClient injects a custom *http.Client (useful for tests).+func WithHTTPClient(h *http.Client) Option {+ return func(c *Client) { c.HTTPClient = h }+}++// WithJWT sets the bearer token to send on every request.+func WithJWT(jwt string) Option {+ return func(c *Client) { c.JWT = jwt }+}++// do is the internal HTTP transport. It JSON-encodes body (if non-nil),+// JSON-decodes the response into out (if non-nil), and maps non-2xx status+// codes to typed errors.+func (c *Client) do(ctx context.Context, method, path string, body, out any) error {+ var reqBody io.Reader+ if body != nil {+ buf, err := json.Marshal(body)+ if err != nil {+ return fmt.Errorf("encoding request body: %w", err)+ }+ reqBody = bytes.NewReader(buf)+ }++ req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, reqBody)+ if err != nil {+ return fmt.Errorf("building request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", c.UserAgent)+ if c.JWT != "" {+ req.Header.Set("Authorization", "Bearer "+c.JWT)+ }++ resp, err := c.HTTPClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 200 && resp.StatusCode < 300 {+ if out == nil {+ return nil+ }+ if err := json.NewDecoder(resp.Body).Decode(out); err != nil {+ return fmt.Errorf("decoding response: %w", err)+ }+ return nil+ }++ switch resp.StatusCode {+ case http.StatusUnauthorized:+ return ErrUnauthorized+ case http.StatusForbidden:+ return ErrForbidden+ case http.StatusNotFound:+ return ErrNotFound+ case http.StatusTooManyRequests:+ return ErrRateLimited+ }+ respBody, _ := io.ReadAll(resp.Body)+ return &APIError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(respBody))}+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./pkg/client/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/+git commit -m "feat(client): Client struct, options, do() with typed error mapping"+```++---++## Task 9: pkg/client — `Login`++**Files:**+- Create: `pkg/client/auth.go`+- Test: `pkg/client/auth_test.go`++**Note on the endpoint shape:** Per the spec, login is `POST /api/login` with `{email, password}`. The response shape needs to be confirmed against `tracewayapp/traceway/backend/app/controllers/auth.controller.go`. The most common shape is `{"token": "..."}` or `{"jwt": "..."}`. Before writing the test, fetch the controller and confirm:++```bash+gh api repos/tracewayapp/traceway/contents/backend/app/controllers/auth.controller.go --jq .content | base64 -d+```++If the response field is named differently (e.g. `accessToken`), adjust the `loginResponse` struct's JSON tag accordingly. The test below uses `token` — change it if upstream uses something else.++- [ ] **Step 1: Confirm the upstream response field name**++Fetch the controller (command above) and read it. Look for the JSON response shape returned by the login handler. Note the field name. Default assumption used in this task: `token`.++- [ ] **Step 2: Write the failing tests**++Create `pkg/client/auth_test.go`:++```go+package client++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestLogin_success(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/login" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Errorf("method = %q", r.Method)+ }+ var req map[string]string+ _ = json.NewDecoder(r.Body).Decode(&req)+ if req["email"] != "[email protected]" {+ t.Errorf("email = %q", req["email"])+ }+ if req["password"] != "hunter2" {+ t.Errorf("password = %q", req["password"])+ }+ _, _ = w.Write([]byte(`{"token": "jwt.value.here"}`))+ }))+ defer srv.Close()++ c := New(srv.URL)+ jwt, err := c.Login(context.Background(), "[email protected]", "hunter2")+ if err != nil {+ t.Fatalf("Login: %v", err)+ }+ if jwt != "jwt.value.here" {+ t.Errorf("jwt = %q", jwt)+ }+}++func TestLogin_invalidCredentials_returnsUnauthorized(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(401)+ }))+ defer srv.Close()++ c := New(srv.URL)+ _, err := c.Login(context.Background(), "x", "y")+ if !errors.Is(err, ErrUnauthorized) {+ t.Errorf("got %v, want ErrUnauthorized", err)+ }+}+```++- [ ] **Step 3: Run the tests, verify they fail**++Run: `go test ./pkg/client/...`+Expected: build failure — `c.Login undefined`.++- [ ] **Step 4: Implement `Login`**++Create `pkg/client/auth.go`:++```go+package client++import (+ "context"+ "errors"+ "net/http"+)++type loginRequest struct {+ Email string `json:"email"`+ Password string `json:"password"`+}++type loginResponse struct {+ // If upstream uses "accessToken" or "jwt" instead of "token", change this tag.+ Token string `json:"token"`+}++// 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 {+ return "", err+ }+ if resp.Token == "" {+ return "", errors.New("login response did not include a token")+ }+ return resp.Token, nil+}+```++- [ ] **Step 5: Run the tests, verify they pass**++Run: `go test ./pkg/client/...`+Expected: PASS.++- [ ] **Step 6: Commit**++```bash+git add pkg/client/+git commit -m "feat(client): Login(email, password) → JWT"+```++---++## Task 10: pkg/client — `ListProjects`++**Files:**+- Create: `pkg/client/projects.go`+- Test: `pkg/client/projects_test.go`++**Note on shape:** `POST /api/projects` lists projects. Confirm the response shape against `tracewayapp/traceway/backend/app/controllers/project.controller.go` and the model. Most likely it's `{"data": [{"id": "...", "name": "..."}, ...], "pagination": {...}}`. Adjust struct tags if upstream uses different field names.++- [ ] **Step 1: Confirm upstream response shape**++```bash+gh api repos/tracewayapp/traceway/contents/backend/app/controllers/project.controller.go --jq .content | base64 -d+gh api repos/tracewayapp/traceway/contents/backend/app/models/project.model.go --jq .content | base64 -d+```++Note the Project model field names. Default assumption used in this task: `id`, `name`. Add other fields you observe (e.g. `createdAt`) — but only if you'll use them; YAGNI.++- [ ] **Step 2: Write the failing tests**++Create `pkg/client/projects_test.go`:++```go+package client++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestListProjects_decodesData(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/projects" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Errorf("method = %q", r.Method)+ }+ _, _ = w.Write([]byte(`{+ "data": [+ {"id": "p1", "name": "stormwind-prod"},+ {"id": "p2", "name": "stormwind-staging"}+ ],+ "pagination": {"page": 0, "pageSize": 50, "total": 2}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListProjects(context.Background())+ if err != nil {+ t.Fatalf("ListProjects: %v", err)+ }+ if len(resp.Data) != 2 {+ t.Fatalf("got %d projects, want 2", len(resp.Data))+ }+ if resp.Data[0].ID != "p1" {+ t.Errorf("Data[0].ID = %q", resp.Data[0].ID)+ }+ if resp.Data[1].Name != "stormwind-staging" {+ t.Errorf("Data[1].Name = %q", resp.Data[1].Name)+ }+ if resp.Pagination.Total != 2 {+ t.Errorf("Pagination.Total = %d", resp.Pagination.Total)+ }+}+```++- [ ] **Step 3: Run the tests, verify they fail**++Run: `go test ./pkg/client/...`+Expected: build failure.++- [ ] **Step 4: Implement `Pagination`, `Project`, and `ListProjects`**++Create `pkg/client/projects.go`:++```go+package client++import (+ "context"+ "net/http"+)++// Pagination matches Traceway's pagination block on every list response.+type Pagination struct {+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+ Total int `json:"total"`+}++// Project is the minimal project shape we need today. Add fields as commands+// require them; do not pre-emptively mirror the entire upstream model.+type Project struct {+ ID string `json:"id"`+ Name string `json:"name"`+}++// ListProjectsResponse is the shape of POST /api/projects.+type ListProjectsResponse struct {+ Data []Project `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// ListProjects returns all projects visible to the authenticated user.+func (c *Client) ListProjects(ctx context.Context) (*ListProjectsResponse, error) {+ var resp ListProjectsResponse+ // Empty body — Traceway accepts {} or no body for the default listing.+ if err := c.do(ctx, http.MethodPost, "/api/projects", map[string]any{}, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+```++- [ ] **Step 5: Run the tests, verify they pass**++Run: `go test ./pkg/client/...`+Expected: PASS.++- [ ] **Step 6: Commit**++```bash+git add pkg/client/+git commit -m "feat(client): Pagination, Project, ListProjects"+```++---++## Task 11: output — Mode enum and TTY detection++**Files:**+- Create: `internal/output/format.go`+- Test: `internal/output/format_test.go`++- [ ] **Step 1: Write the failing tests**++Create `internal/output/format_test.go`:++```go+package output++import (+ "testing"+)++func TestParseMode_validValues(t *testing.T) {+ cases := map[string]Mode{+ "json": ModeJSON,+ "JSON": ModeJSON,+ "yaml": ModeYAML,+ "table": ModeTable,+ }+ for in, want := range cases {+ got, err := ParseMode(in)+ if err != nil {+ t.Errorf("ParseMode(%q) error: %v", in, err)+ continue+ }+ if got != want {+ t.Errorf("ParseMode(%q) = %v, want %v", in, got, want)+ }+ }+}++func TestParseMode_invalid(t *testing.T) {+ if _, err := ParseMode("xml"); err == nil {+ t.Error("expected error for invalid mode")+ }+}++func TestResolveMode_explicitWins(t *testing.T) {+ got := ResolveMode("json", false)+ if got != ModeJSON {+ t.Errorf("got %v", got)+ }+ got = ResolveMode("table", false)+ if got != ModeTable {+ t.Errorf("got %v", got)+ }+}++func TestResolveMode_emptyDefaultsByTTY(t *testing.T) {+ if got := ResolveMode("", true); got != ModeTable {+ t.Errorf("TTY default = %v, want ModeTable", got)+ }+ if got := ResolveMode("", false); got != ModeJSON {+ t.Errorf("non-TTY default = %v, want ModeJSON", got)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/output/...`+Expected: build failure.++- [ ] **Step 3: Implement the `Mode` type**++Create `internal/output/format.go`:++```go+// Package output renders command results as JSON, YAML, or tables, plus the+// stable error envelope.+package output++import (+ "fmt"+ "os"+ "strings"++ "golang.org/x/term"+)++// Mode controls how Render formats its output.+type Mode int++const (+ ModeJSON Mode = iota+ ModeYAML+ ModeTable+)++func (m Mode) String() string {+ switch m {+ case ModeJSON:+ return "json"+ case ModeYAML:+ return "yaml"+ case ModeTable:+ return "table"+ default:+ return "unknown"+ }+}++// ParseMode converts the user-facing flag value to a Mode.+func ParseMode(s string) (Mode, error) {+ switch strings.ToLower(s) {+ case "json":+ return ModeJSON, nil+ case "yaml":+ return ModeYAML, nil+ case "table":+ return ModeTable, nil+ default:+ return 0, fmt.Errorf("invalid output mode %q (valid: json, yaml, table)", s)+ }+}++// ResolveMode picks an effective Mode. An explicit user value wins; otherwise+// default to table on TTY and json on non-TTY.+//+// The error returned by ParseMode for invalid explicit values is intentionally+// suppressed here — the caller should validate via ParseMode at flag-parse time.+func ResolveMode(explicit string, isTTY bool) Mode {+ if explicit != "" {+ if m, err := ParseMode(explicit); err == nil {+ return m+ }+ }+ if isTTY {+ return ModeTable+ }+ return ModeJSON+}++// IsTerminal reports whether the given file descriptor is a terminal.+// Wraps golang.org/x/term so callers don't import it directly.+func IsTerminal(fd uintptr) bool {+ return term.IsTerminal(int(fd))+}++// StdoutIsTerminal is a convenience shortcut.+func StdoutIsTerminal() bool { return IsTerminal(os.Stdout.Fd()) }++// StderrIsTerminal is a convenience shortcut.+func StderrIsTerminal() bool { return IsTerminal(os.Stderr.Fd()) }+```++- [ ] **Step 4: Add the term dependency**++Run: `go get golang.org/x/term`+Expected: `go.sum` and `go.mod` updated.++- [ ] **Step 5: Run the tests, verify they pass**++Run: `go test ./internal/output/...`+Expected: PASS.++- [ ] **Step 6: Commit**++```bash+git add internal/output/ go.mod go.sum+git commit -m "feat(output): Mode enum, ParseMode, ResolveMode, TTY detection"+```++---++## Task 12: output — JSON renderer with `--fields` projection++**Files:**+- Create: `internal/output/json.go`+- Test: `internal/output/json_test.go`++- [ ] **Step 1: Write the failing tests**++Create `internal/output/json_test.go`:++```go+package output++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"+)++type project struct {+ ID string `json:"id"`+ Name string `json:"name"`+ URL string `json:"url"`+}++type wrappedResp struct {+ Data []project `json:"data"`+ Pagination struct {+ Total int `json:"total"`+ } `json:"pagination"`+}++func TestRenderJSON_passThroughWhenNoFields(t *testing.T) {+ in := wrappedResp{+ Data: []project{{ID: "p1", Name: "alpha", URL: "https://a"}},+ }+ in.Pagination.Total = 1++ var buf bytes.Buffer+ if err := RenderJSON(&buf, in, nil); err != nil {+ t.Fatal(err)+ }++ var got wrappedResp+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("invalid JSON output: %v\noutput: %s", err, buf.String())+ }+ if got.Data[0].URL != "https://a" {+ t.Errorf("URL was stripped; pass-through expected")+ }+}++func TestRenderJSON_projectsFieldsInWrappedData(t *testing.T) {+ in := wrappedResp{+ Data: []project{+ {ID: "p1", Name: "alpha", URL: "https://a"},+ {ID: "p2", Name: "beta", URL: "https://b"},+ },+ }++ var buf bytes.Buffer+ if err := RenderJSON(&buf, in, []string{"id", "name"}); err != nil {+ t.Fatal(err)+ }+ out := buf.String()++ if !strings.Contains(out, `"id"`) || !strings.Contains(out, `"name"`) {+ t.Errorf("expected id and name in projection, got: %s", out)+ }+ if strings.Contains(out, `"url"`) {+ t.Errorf("url should have been projected away, got: %s", out)+ }+ // Pagination stays at the top level even when fields are projected.+ if !strings.Contains(out, `"pagination"`) {+ t.Errorf("pagination should pass through, got: %s", out)+ }+}++func TestRenderJSON_projectsTopLevelObject(t *testing.T) {+ in := project{ID: "p1", Name: "alpha", URL: "https://a"}++ var buf bytes.Buffer+ if err := RenderJSON(&buf, in, []string{"id"}); err != nil {+ t.Fatal(err)+ }+ out := buf.String()+ if !strings.Contains(out, `"id"`) {+ t.Errorf("expected id, got: %s", out)+ }+ if strings.Contains(out, `"name"`) {+ t.Errorf("name should have been projected away, got: %s", out)+ }+}++func TestParseFieldsFlag(t *testing.T) {+ cases := []struct {+ in string+ want []string+ }{+ {"", nil},+ {"a", []string{"a"}},+ {"a,b,c", []string{"a", "b", "c"}},+ {" a , b ", []string{"a", "b"}},+ }+ for _, c := range cases {+ got := ParseFieldsFlag(c.in)+ if len(got) != len(c.want) {+ t.Errorf("ParseFieldsFlag(%q) = %v, want %v", c.in, got, c.want)+ continue+ }+ for i := range got {+ if got[i] != c.want[i] {+ t.Errorf("ParseFieldsFlag(%q)[%d] = %q, want %q", c.in, i, got[i], c.want[i])+ }+ }+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/output/...`+Expected: build failure.++- [ ] **Step 3: Implement the JSON renderer + projection**++Create `internal/output/json.go`:++```go+package output++import (+ "encoding/json"+ "io"+ "strings"+)++// ParseFieldsFlag splits "a, b, c" → []string{"a", "b", "c"}. Empty input → nil.+func ParseFieldsFlag(s string) []string {+ if strings.TrimSpace(s) == "" {+ return nil+ }+ parts := strings.Split(s, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ p = strings.TrimSpace(p)+ if p != "" {+ out = append(out, p)+ }+ }+ if len(out) == 0 {+ return nil+ }+ return out+}++// RenderJSON marshals v as indented JSON to w. If fields is non-nil, projects+// each item of a top-level "data" array (Traceway's wrapper shape) — or the+// top-level object itself if it has no "data" key — to just the named fields.+// "pagination" and other top-level wrapper keys pass through unchanged.+func RenderJSON(w io.Writer, v any, fields []string) error {+ if fields == nil {+ enc := json.NewEncoder(w)+ enc.SetIndent("", " ")+ return enc.Encode(v)+ }++ // Round-trip through JSON to a generic any so we can project by string keys.+ raw, err := json.Marshal(v)+ if err != nil {+ return err+ }+ var generic any+ if err := json.Unmarshal(raw, &generic); err != nil {+ return err+ }+ projected := projectFields(generic, fields)+ enc := json.NewEncoder(w)+ enc.SetIndent("", " ")+ return enc.Encode(projected)+}++// projectFields keeps only the named keys, with awareness of Traceway's+// {data: [...], pagination: {...}} wrapper. See RenderJSON for the contract.+func projectFields(v any, fields []string) any {+ set := make(map[string]bool, len(fields))+ for _, f := range fields {+ set[f] = true+ }++ if m, ok := v.(map[string]any); ok {+ if data, hasData := m["data"]; hasData {+ if arr, ok := data.([]any); ok {+ out := make([]any, len(arr))+ for i, item := range arr {+ out[i] = projectMap(item, set)+ }+ m["data"] = out+ return m+ }+ }+ return projectMap(v, set)+ }+ if arr, ok := v.([]any); ok {+ out := make([]any, len(arr))+ for i, item := range arr {+ out[i] = projectMap(item, set)+ }+ return out+ }+ return v+}++func projectMap(v any, fields map[string]bool) any {+ m, ok := v.(map[string]any)+ if !ok {+ return v+ }+ out := make(map[string]any, len(fields))+ for k, val := range m {+ if fields[k] {+ out[k] = val+ }+ }+ return out+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./internal/output/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/output/+git commit -m "feat(output): JSON renderer with --fields projection"+```++---++## Task 13: output — YAML renderer++**Files:**+- Create: `internal/output/yaml.go`+- Test: `internal/output/yaml_test.go`++- [ ] **Step 1: Write the failing tests**++Create `internal/output/yaml_test.go`:++```go+package output++import (+ "bytes"+ "strings"+ "testing"+)++func TestRenderYAML_passThrough(t *testing.T) {+ in := project{ID: "p1", Name: "alpha", URL: "https://a"}++ var buf bytes.Buffer+ if err := RenderYAML(&buf, in, nil); err != nil {+ t.Fatal(err)+ }+ out := buf.String()+ if !strings.Contains(out, "id: p1") {+ t.Errorf("expected 'id: p1' in YAML, got:\n%s", out)+ }+ if !strings.Contains(out, "name: alpha") {+ t.Errorf("expected 'name: alpha' in YAML, got:\n%s", out)+ }+ if !strings.Contains(out, "url: https://a") {+ t.Errorf("expected 'url: https://a' in YAML, got:\n%s", out)+ }+}++func TestRenderYAML_projectsFields(t *testing.T) {+ in := project{ID: "p1", Name: "alpha", URL: "https://a"}++ var buf bytes.Buffer+ if err := RenderYAML(&buf, in, []string{"id"}); err != nil {+ t.Fatal(err)+ }+ out := buf.String()+ if !strings.Contains(out, "id: p1") {+ t.Errorf("expected id in projection, got:\n%s", out)+ }+ if strings.Contains(out, "name:") {+ t.Errorf("name should be projected away, got:\n%s", out)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/output/...`+Expected: build failure.++- [ ] **Step 3: Add the yaml dependency and implement**++Run: `go get gopkg.in/yaml.v3`+Expected: `go.mod`/`go.sum` updated.++Create `internal/output/yaml.go`:++```go+package output++import (+ "encoding/json"+ "io"++ "gopkg.in/yaml.v3"+)++// RenderYAML marshals v as YAML to w, applying the same field projection as+// RenderJSON when fields is non-nil. Internally we round-trip through JSON so+// that callers' types only need json struct tags (no need for parallel yaml+// tags on every struct in pkg/client).+func RenderYAML(w io.Writer, v any, fields []string) error {+ raw, err := json.Marshal(v)+ if err != nil {+ return err+ }+ var generic any+ if err := json.Unmarshal(raw, &generic); err != nil {+ return err+ }+ if fields != nil {+ generic = projectFields(generic, fields)+ }+ enc := yaml.NewEncoder(w)+ enc.SetIndent(2)+ defer enc.Close()+ return enc.Encode(generic)+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./internal/output/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/output/ go.mod go.sum+git commit -m "feat(output): YAML renderer (JSON-backed) with --fields projection"+```++---++## Task 14: output — table helper++**Files:**+- Create: `internal/output/table.go`+- (No dedicated test file — table.go is just a tabwriter constructor; per-resource table rendering is tested in the cmd layer.)++- [ ] **Step 1: Implement the table helper**++Per the spec, table rendering is per-resource (each `cmd/traceway/<resource>.go` writes its own columns). This file just provides a configured `text/tabwriter` so all tables look consistent.++Create `internal/output/table.go`:++```go+package output++import (+ "io"+ "text/tabwriter"+)++// NewTabWriter returns a *text/tabwriter.Writer configured for traceway's+// table output style: left-aligned columns separated by two spaces. Callers+// must call Flush() after writing all rows.+//+// tw := output.NewTabWriter(w)+// fmt.Fprintln(tw, "ID\tNAME")+// fmt.Fprintf(tw, "%s\t%s\n", id, name)+// tw.Flush()+func NewTabWriter(w io.Writer) *tabwriter.Writer {+ return tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)+}+```++- [ ] **Step 2: Verify the package still builds**++Run: `go build ./...`+Expected: no errors.++- [ ] **Step 3: Commit**++```bash+git add internal/output/+git commit -m "feat(output): NewTabWriter helper for per-resource tables"+```++---++## Task 15: output — error envelope renderer++**Files:**+- Create: `internal/output/error.go`+- Test: `internal/output/error_test.go`++- [ ] **Step 1: Write the failing tests**++Create `internal/output/error_test.go`:++```go+package output++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"+)++func TestRenderError_jsonShape(t *testing.T) {+ var buf bytes.Buffer+ err := RenderError(&buf, ModeJSON, ErrorEnvelope{+ Code: "token_expired",+ Message: "JWT expired or invalid",+ Hint: "traceway login --profile stormwind",+ ExitCode: 4,+ })+ if err != nil {+ t.Fatal(err)+ }++ var got map[string]any+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("invalid JSON: %v\nout: %s", err, buf.String())+ }+ if got["error"] != "token_expired" {+ t.Errorf("error = %v", got["error"])+ }+ if got["message"] != "JWT expired or invalid" {+ t.Errorf("message = %v", got["message"])+ }+ if got["hint"] != "traceway login --profile stormwind" {+ t.Errorf("hint = %v", got["hint"])+ }+ if int(got["exit_code"].(float64)) != 4 {+ t.Errorf("exit_code = %v", got["exit_code"])+ }+}++func TestRenderError_jsonOmitsEmptyHint(t *testing.T) {+ var buf bytes.Buffer+ _ = RenderError(&buf, ModeJSON, ErrorEnvelope{+ Code: "internal",+ Message: "boom",+ ExitCode: 1,+ })+ var got map[string]any+ _ = json.Unmarshal(buf.Bytes(), &got)+ if _, ok := got["hint"]; ok {+ t.Errorf("hint should be omitted when empty, got: %v", got)+ }+}++func TestRenderError_proseHasErrorPrefix(t *testing.T) {+ var buf bytes.Buffer+ _ = RenderError(&buf, ModeTable, ErrorEnvelope{+ Code: "token_expired",+ Message: "session expired",+ Hint: "traceway login --profile stormwind",+ ExitCode: 4,+ })+ out := buf.String()+ if !strings.HasPrefix(out, "Error:") {+ t.Errorf("prose form should start with 'Error:', got:\n%s", out)+ }+ if !strings.Contains(out, "session expired") {+ t.Errorf("missing message, got:\n%s", out)+ }+ if !strings.Contains(out, "Hint:") {+ t.Errorf("missing hint line, got:\n%s", out)+ }+}++func TestRenderError_proseOmitsHintLineWhenAbsent(t *testing.T) {+ var buf bytes.Buffer+ _ = RenderError(&buf, ModeTable, ErrorEnvelope{+ Code: "internal",+ Message: "boom",+ ExitCode: 1,+ })+ out := buf.String()+ if strings.Contains(out, "Hint:") {+ t.Errorf("Hint line should be omitted, got:\n%s", out)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./internal/output/...`+Expected: build failure.++- [ ] **Step 3: Implement the error renderer**++Create `internal/output/error.go`:++```go+package output++import (+ "encoding/json"+ "fmt"+ "io"+)++// ErrorEnvelope is the stable error contract written to stderr on any failure.+// Code is a snake_case stable identifier; LLMs may branch on it.+type ErrorEnvelope struct {+ Code string `json:"error"`+ Message string `json:"message"`+ Hint string `json:"hint,omitempty"`+ ExitCode int `json:"exit_code"`+}++// RenderError writes the envelope to w. JSON for ModeJSON/ModeYAML; prose for+// ModeTable. (YAML mode uses JSON for errors — easier for callers to parse and+// matches gh's behavior for machine-formatted errors.)+func RenderError(w io.Writer, mode Mode, env ErrorEnvelope) error {+ if mode == ModeJSON || mode == ModeYAML {+ enc := json.NewEncoder(w)+ enc.SetIndent("", " ")+ return enc.Encode(env)+ }+ if _, err := fmt.Fprintf(w, "Error: %s\n", env.Message); err != nil {+ return err+ }+ if env.Hint != "" {+ if _, err := fmt.Fprintf(w, " Hint: %s\n", env.Hint); err != nil {+ return err+ }+ }+ return nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./internal/output/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add internal/output/+git commit -m "feat(output): error envelope renderer (JSON + prose)"+```++---++## Task 16: cmd/traceway — main, root command, global flags++**Files:**+- Create: `cmd/traceway/main.go`+- Create: `cmd/traceway/root.go`++- [ ] **Step 1: Add the Cobra dependency**++Run: `go get github.com/spf13/cobra`+Expected: `go.mod`/`go.sum` updated.++- [ ] **Step 2: Implement `main.go`**++Create `cmd/traceway/main.go`:++```go+package main++import (+ "context"+ "fmt"+ "os"+ "os/signal"+ "syscall"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++func main() {+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer cancel()++ root := newRootCmd()+ if err := root.ExecuteContext(ctx); err != nil {+ // All command runners are expected to write the user-facing error+ // message themselves (via internal/output). This branch is the last+ // resort for errors Cobra returned without a message — most often+ // usage errors, which Cobra has already printed to stderr.+ if msg := err.Error(); msg != "" && os.Getenv("TRACEWAY_DEBUG") == "1" {+ fmt.Fprintln(os.Stderr, "debug:", msg)+ }+ os.Exit(exitcode.Generic)+ }+}+```++- [ ] **Step 3: Implement `root.go`**++Create `cmd/traceway/root.go`:++```go+package main++import (+ "github.com/spf13/cobra"+)++// Global flag values, populated by Cobra at flag-parse time.+var (+ flagProfile string+ flagProject string+ flagOutput string+ flagFields string+ flagYes bool+ flagNoPrompt bool+ flagPasswordFile string+)++func newRootCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "traceway",+ Short: "CLI for the Traceway observability platform",+ SilenceUsage: true, // we render our own error envelopes+ SilenceErrors: true,+ }++ pf := cmd.PersistentFlags()+ pf.StringVar(&flagProfile, "profile", "", "Profile name (default: current profile, then \"default\")")+ pf.StringVar(&flagProject, "project", "", "Project ID (default: profile's current project)")+ pf.StringVarP(&flagOutput, "output", "o", "", "Output format: json, yaml, or table (default: table on TTY, json otherwise)")+ pf.StringVar(&flagFields, "fields", "", "Comma-separated field projection (e.g. id,name)")+ pf.BoolVar(&flagYes, "yes", false, "Skip confirmation for mutating commands")+ pf.BoolVar(&flagNoPrompt, "no-prompt", false, "Never prompt interactively, even on a TTY")++ // Subcommand wiring will be added by individual files in their own init() blocks+ // or by appending to this function as we implement them.+ cmd.AddCommand(newLoginCmd())+ cmd.AddCommand(newLogoutCmd())+ cmd.AddCommand(newProfilesCmd())+ cmd.AddCommand(newProjectsCmd())++ return cmd+}+```++This file references `newLoginCmd`, `newLogoutCmd`, `newProfilesCmd`, `newProjectsCmd` — all created in later tasks. The build will fail until they exist; we wire them in now and they get filled in incrementally.++- [ ] **Step 4: Add temporary stub functions so Task 16 compiles in isolation**++Create temporary stubs to make the build pass; they'll be replaced in Tasks 17–20.++Create `cmd/traceway/login.go`:++```go+package main++import "github.com/spf13/cobra"++func newLoginCmd() *cobra.Command { return &cobra.Command{Use: "login", Hidden: true} }+```++Create `cmd/traceway/logout.go`:++```go+package main++import "github.com/spf13/cobra"++func newLogoutCmd() *cobra.Command { return &cobra.Command{Use: "logout", Hidden: true} }+```++Create `cmd/traceway/profiles.go`:++```go+package main++import "github.com/spf13/cobra"++func newProfilesCmd() *cobra.Command { return &cobra.Command{Use: "profiles", Hidden: true} }+```++Create `cmd/traceway/projects.go`:++```go+package main++import "github.com/spf13/cobra"++func newProjectsCmd() *cobra.Command { return &cobra.Command{Use: "projects", Hidden: true} }+```++- [ ] **Step 5: Verify the build**++Run: `go build ./...`+Expected: no errors.++Run: `go run ./cmd/traceway --help`+Expected: prints usage with "CLI for the Traceway observability platform" and lists `login`, `logout`, `profiles`, `projects` (even though they're hidden, `--help` shows them) — actually, `Hidden: true` keeps them out of `--help`. That's fine for now; you won't see them until they're implemented for real.++Run: `go run ./cmd/traceway --output xml`+Expected: exit nonzero (we don't validate `--output` here yet — that's wired into individual commands in Task 17+). Acceptable.++- [ ] **Step 6: Commit**++```bash+git add cmd/traceway/ go.mod go.sum+git commit -m "feat(cmd): root command, global flags, stub subcommands"+```++---++## Task 17: cmd/traceway — login command++**Files:**+- Create: `cmd/traceway/testutil_test.go` (shared helpers — used by all subsequent command tests)+- Create: `cmd/traceway/errors.go` (handleAPIError stub for login's auth error)+- Modify: `cmd/traceway/login.go` (replace stub with real impl)+- Create: `cmd/traceway/login_test.go`++- [ ] **Step 1: Write the shared test helpers**++Create `cmd/traceway/testutil_test.go`:++```go+package main++import (+ "bytes"+ "io"+ "strings"+ "testing"+)++// runCmd executes the given args against a fresh root command, with stdin/out/err+// captured into buffers. It returns the buffers and the error from Execute().+//+// Each test should also call t.Setenv("XDG_CONFIG_HOME", t.TempDir()) so that+// config writes are isolated.+func runCmd(t *testing.T, stdin string, args ...string) (stdout, stderr *bytes.Buffer, err error) {+ t.Helper()+ stdout = &bytes.Buffer{}+ stderr = &bytes.Buffer{}++ cmd := newRootCmd()+ cmd.SetIn(strings.NewReader(stdin))+ cmd.SetOut(stdout)+ cmd.SetErr(stderr)+ cmd.SetArgs(args)+ err = cmd.Execute()+ return+}++// readAll consumes a bytes.Buffer entirely; useful when a test needs the+// trailing bytes after Execute returned.+func readAll(t *testing.T, r io.Reader) string {+ t.Helper()+ b, err := io.ReadAll(r)+ if err != nil {+ t.Fatalf("readAll: %v", err)+ }+ return string(b)+}+```++- [ ] **Step 2: Write the failing tests for login**++Create `cmd/traceway/login_test.go`:++```go+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+)++func TestLogin_passwordStdin_success(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/login" {+ t.Errorf("path = %q", r.URL.Path)+ }+ var req map[string]string+ _ = json.NewDecoder(r.Body).Decode(&req)+ if req["email"] != "[email protected]" {+ t.Errorf("email = %q", req["email"])+ }+ if req["password"] != "hunter2" {+ t.Errorf("password = %q", req["password"])+ }+ _, _ = w.Write([]byte(`{"token":"jwt.value"}`))+ }))+ defer srv.Close()++ _, _, err := runCmd(t, "hunter2\n",+ "login",+ "--url", srv.URL,+ "--username", "[email protected]",+ "--password-stdin",+ )+ if err != nil {+ t.Fatalf("login failed: %v", err)+ }++ cfg, err := config.Load()+ if err != nil {+ t.Fatalf("Load config: %v", err)+ }+ p, ok := cfg.Profiles["default"]+ if !ok {+ t.Fatal("default profile not saved")+ }+ if p.URL != srv.URL {+ t.Errorf("URL = %q", p.URL)+ }+ if p.Username != "[email protected]" {+ t.Errorf("Username = %q", p.Username)+ }+ if p.JWT != "jwt.value" {+ t.Errorf("JWT = %q", p.JWT)+ }+ if cfg.CurrentProfile != "default" {+ t.Errorf("CurrentProfile = %q, want default (only profile should be auto-set)", cfg.CurrentProfile)+ }+}++func TestLogin_namedProfile_secondLogin_doesNotOverrideCurrent(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"token":"tok"}`))+ }))+ defer srv.Close()++ // First login → default profile.+ if _, _, err := runCmd(t, "p\n",+ "login", "--url", srv.URL, "--username", "[email protected]", "--password-stdin",+ ); err != nil {+ t.Fatalf("first login: %v", err)+ }+ // Second login → cloud profile. Should NOT change current profile pointer.+ if _, _, err := runCmd(t, "p\n",+ "login", "--profile", "cloud", "--url", srv.URL, "--username", "[email protected]", "--password-stdin",+ ); err != nil {+ t.Fatalf("second login: %v", err)+ }++ cfg, _ := config.Load()+ if cfg.CurrentProfile != "default" {+ t.Errorf("CurrentProfile = %q, want 'default' (was set on first login, second login must not override)", cfg.CurrentProfile)+ }+ if _, ok := cfg.Profiles["cloud"]; !ok {+ t.Error("cloud profile missing")+ }+}++func TestLogin_invalidCredentials_writesEnvelope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer srv.Close()++ _, stderr, err := runCmd(t, "wrong\n",+ "login", "--output", "json", "--url", srv.URL, "--username", "x", "--password-stdin",+ )+ if err == nil {+ t.Fatal("expected login to return an error")+ }+ if !strings.Contains(stderr.String(), `"error"`) {+ t.Errorf("expected JSON error envelope on stderr, got: %s", stderr.String())+ }+ if !strings.Contains(stderr.String(), `"not_authenticated"`) {+ t.Errorf("expected error code 'not_authenticated', got: %s", stderr.String())+ }+}++func TestLogin_refreshExistingProfile_keepsURLAndUsername(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"token":"newtoken"}`))+ }))+ defer srv.Close()++ // Seed config with an existing profile.+ cfg := &config.Config{+ CurrentProfile: "default",+ Profiles: map[string]config.Profile{+ "default": {URL: srv.URL, Username: "[email protected]", JWT: "old"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }++ // Refresh: only --password-stdin, no --url/--username.+ if _, _, err := runCmd(t, "newpw\n", "login", "--password-stdin"); err != nil {+ t.Fatalf("refresh: %v", err)+ }++ got, _ := config.Load()+ p := got.Profiles["default"]+ if p.URL != srv.URL {+ t.Errorf("URL changed: %q", p.URL)+ }+ if p.Username != "[email protected]" {+ t.Errorf("Username changed: %q", p.Username)+ }+ if p.JWT != "newtoken" {+ t.Errorf("JWT not refreshed: %q", p.JWT)+ }+}+```++- [ ] **Step 3: Run the tests, verify they fail**++Run: `go test ./cmd/traceway/...`+Expected: build failure (login is still a stub).++- [ ] **Step 4: Create the shared `errors.go` helper**++Create `cmd/traceway/errors.go`:++```go+package main++import (+ "errors"+ "io"+ "net/url"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++// renderAPIError writes the appropriate envelope to errOut and returns a+// sentinel error so the cobra runner sees a non-nil result. The actual exit+// code is communicated via the envelope's ExitCode field; main() resolves it.+//+// loginContext = true means we're in the login command itself; an Unauthorized+// from there means "wrong username/password", not "session expired".+func renderAPIError(errOut io.Writer, mode output.Mode, err error, loginContext bool) error {+ env := classifyError(err, loginContext)+ _ = output.RenderError(errOut, mode, env)+ return errors.New(env.Code) // sentinel; main() calls os.Exit with env.ExitCode+}++func classifyError(err error, loginContext bool) output.ErrorEnvelope {+ switch {+ case errors.Is(err, client.ErrUnauthorized):+ if loginContext {+ return output.ErrorEnvelope{+ Code: "not_authenticated", Message: "invalid email or password",+ ExitCode: exitcode.Auth,+ }+ }+ return output.ErrorEnvelope{+ Code: "token_expired", Message: "session expired or invalid",+ Hint: "traceway login --profile " + flagProfile,+ ExitCode: exitcode.Auth,+ }+ case errors.Is(err, client.ErrForbidden):+ return output.ErrorEnvelope{+ Code: "forbidden", Message: "permission denied",+ ExitCode: exitcode.Auth,+ }+ case errors.Is(err, client.ErrNotFound):+ return output.ErrorEnvelope{+ Code: "not_found", Message: "resource not found",+ ExitCode: exitcode.NotFound,+ }+ case errors.Is(err, client.ErrRateLimited):+ return output.ErrorEnvelope{+ Code: "rate_limited", Message: "rate limit exceeded — slow down or retry later",+ ExitCode: exitcode.RateLimited,+ }+ }+ var apiErr *client.APIError+ if errors.As(err, &apiErr) {+ if apiErr.StatusCode >= 500 {+ return output.ErrorEnvelope{+ Code: "server_error", Message: apiErr.Error(),+ ExitCode: exitcode.Server,+ }+ }+ return output.ErrorEnvelope{+ Code: "api_error", Message: apiErr.Error(),+ ExitCode: exitcode.Generic,+ }+ }+ var urlErr *url.Error+ if errors.As(err, &urlErr) {+ return output.ErrorEnvelope{+ Code: "connection_failed", Message: urlErr.Error(),+ Hint: "check that the Traceway URL is reachable and the network is up",+ ExitCode: exitcode.Connection,+ }+ }+ return output.ErrorEnvelope{+ Code: "internal", Message: err.Error(),+ ExitCode: exitcode.Generic,+ }+}+```++- [ ] **Step 5: Wire `main.go` to honor the envelope's exit code**++We need `main()` to know the exit code. The simplest pattern: stash the envelope in a package-level variable and read it after `Execute`.++Modify `cmd/traceway/main.go` (replace the existing body):++```go+package main++import (+ "context"+ "fmt"+ "os"+ "os/signal"+ "syscall"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++// lastExitCode is set by command runners that want to control os.Exit. Defaults+// to exitcode.Success on a clean run; updated by renderAPIError via the+// classified envelope.+var lastExitCode int++func main() {+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+ defer cancel()++ root := newRootCmd()+ if err := root.ExecuteContext(ctx); err != nil {+ // If a runner already classified the error, lastExitCode is set.+ if lastExitCode != 0 {+ os.Exit(lastExitCode)+ }+ // Otherwise it was likely a Cobra usage error — Cobra has already+ // printed it to stderr.+ if os.Getenv("TRACEWAY_DEBUG") == "1" {+ fmt.Fprintln(os.Stderr, "debug:", err)+ }+ os.Exit(exitcode.Usage)+ }+ os.Exit(exitcode.Success)+}+```++Modify `cmd/traceway/errors.go` to set `lastExitCode`:++```go+// In renderAPIError, after computing env:+func renderAPIError(errOut io.Writer, mode output.Mode, err error, loginContext bool) error {+ env := classifyError(err, loginContext)+ _ = output.RenderError(errOut, mode, env)+ lastExitCode = env.ExitCode+ return errors.New(env.Code)+}+```++- [ ] **Step 6: Implement `login.go`**++Replace `cmd/traceway/login.go` with the real implementation:++```go+package main++import (+ "bufio"+ "context"+ "errors"+ "fmt"+ "io"+ "os"+ "strings"++ "github.com/spf13/cobra"+ "golang.org/x/term"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++const defaultURL = "https://cloud.traceway.com"++// login-specific flag values+var (+ loginURL string+ loginUsername string+ loginPasswordFile bool+)++func newLoginCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "login",+ Short: "Authenticate against a Traceway instance and store the JWT",+ RunE: runLogin,+ }+ cmd.Flags().StringVar(&loginURL, "url", "", "Traceway base URL (default: existing or "+defaultURL+")")+ cmd.Flags().StringVar(&loginUsername, "username", "", "Email address (default: existing or interactive prompt)")+ cmd.Flags().BoolVar(&loginPasswordFile, "password-stdin", false, "Read password from stdin instead of prompting")+ return cmd+}++func runLogin(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()++ cfg, err := config.Load()+ if err != nil {+ return err+ }++ profileName := flagProfile+ if profileName == "" {+ profileName = "default"+ }++ existing, hasExisting := cfg.Profiles[profileName]++ url := loginURL+ if url == "" {+ if hasExisting {+ url = existing.URL+ } else {+ url = defaultURL+ }+ }++ username := loginUsername+ if username == "" {+ if hasExisting {+ username = existing.Username+ }+ if username == "" {+ username, err = promptUsername(cmd.InOrStdin(), cmd.OutOrStdout())+ if err != nil {+ return err+ }+ }+ }++ password, err := readPassword(cmd.InOrStdin(), cmd.OutOrStdout(), loginPasswordFile)+ if err != nil {+ return err+ }++ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ c := client.New(url)+ jwt, err := c.Login(ctx, username, password)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, true)+ }++ if cfg.Profiles == nil {+ cfg.Profiles = map[string]config.Profile{}+ }+ currentProject := ""+ if hasExisting {+ currentProject = existing.CurrentProjectID+ }+ cfg.Profiles[profileName] = config.Profile{+ URL: url,+ Username: username,+ JWT: jwt,+ CurrentProjectID: currentProject,+ }+ // First profile ever → set CurrentProfile pointer. Don't override on subsequent logins.+ if cfg.CurrentProfile == "" {+ cfg.CurrentProfile = profileName+ }+ if err := cfg.Save(); err != nil {+ return err+ }++ fmt.Fprintf(cmd.OutOrStdout(), "Logged in as %s on %s (profile: %s)\n", username, url, profileName)+ return nil+}++func promptUsername(in io.Reader, out io.Writer) (string, error) {+ fmt.Fprint(out, "Username: ")+ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return "", err+ }+ return strings.TrimSpace(line), nil+}++func readPassword(in io.Reader, out io.Writer, fromStdin bool) (string, error) {+ if fromStdin {+ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return "", err+ }+ return strings.TrimSpace(line), nil+ }+ // Interactive: read with no echo if stdin is a real terminal.+ if f, ok := in.(*os.File); ok && term.IsTerminal(int(f.Fd())) {+ fmt.Fprint(out, "Password: ")+ bytes, err := term.ReadPassword(int(f.Fd()))+ fmt.Fprintln(out)+ return string(bytes), err+ }+ // Fallback: line-based read (covers test injection).+ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return "", err+ }+ return strings.TrimSpace(line), nil+}+```++- [ ] **Step 7: Run the tests, verify they pass**++Run: `go test ./cmd/traceway/...`+Expected: PASS for all four login tests.++- [ ] **Step 8: Commit**++```bash+git add cmd/traceway/+git commit -m "feat(cmd): login command with --password-stdin and profile-aware refresh"+```++---++## Task 18: cmd/traceway — logout command++**Files:**+- Modify: `cmd/traceway/logout.go` (replace stub)+- Create: `cmd/traceway/logout_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/logout_test.go`:++```go+package main++import (+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+)++func TestLogout_removesProfile(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ cfg := &config.Config{+ CurrentProfile: "default",+ Profiles: map[string]config.Profile{+ "default": {URL: "https://x", Username: "u", JWT: "tok"},+ "cloud": {URL: "https://y", Username: "v", JWT: "tok2"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }++ if _, _, err := runCmd(t, "", "logout"); err != nil {+ t.Fatalf("logout: %v", err)+ }+ got, _ := config.Load()+ if _, ok := got.Profiles["default"]; ok {+ t.Error("default profile should be removed")+ }+ if _, ok := got.Profiles["cloud"]; !ok {+ t.Error("cloud profile should be untouched")+ }+}++func TestLogout_resetsCurrentProfileWhenRemovingIt(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ cfg := &config.Config{+ CurrentProfile: "default",+ Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ "cloud": {URL: "https://y"},+ },+ }+ _ = cfg.Save()++ _, _, err := runCmd(t, "", "logout")+ if err != nil {+ t.Fatal(err)+ }+ got, _ := config.Load()+ if got.CurrentProfile == "default" {+ t.Errorf("CurrentProfile should not still be 'default', got %q", got.CurrentProfile)+ }+}++func TestLogout_unknownProfile_returnsAuthError(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ _, stderr, err := runCmd(t, "", "logout", "--profile", "ghost", "--output", "json")+ if err == nil {+ t.Fatal("expected error for unknown profile")+ }+ if !strings.Contains(stderr.String(), `"error"`) {+ t.Errorf("expected JSON envelope, got: %s", stderr.String())+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./cmd/traceway/...`+Expected: tests fail (logout is still a stub that does nothing).++- [ ] **Step 3: Implement logout**++Replace `cmd/traceway/logout.go`:++```go+package main++import (+ "errors"+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+)++func newLogoutCmd() *cobra.Command {+ return &cobra.Command{+ Use: "logout",+ Short: "Remove a profile's stored credentials",+ RunE: runLogout,+ }+}++func runLogout(cmd *cobra.Command, _ []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }++ name := flagProfile+ if name == "" {+ name = cfg.CurrentProfile+ }+ if name == "" {+ name = "default"+ }++ if _, ok := cfg.Profiles[name]; !ok {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "no_profile",+ Message: fmt.Sprintf("profile %q does not exist", name),+ ExitCode: exitcode.Auth,+ })+ lastExitCode = exitcode.Auth+ return errors.New("no_profile")+ }++ delete(cfg.Profiles, name)+ if cfg.CurrentProfile == name {+ // Pick any remaining profile as the new current; otherwise blank.+ cfg.CurrentProfile = ""+ for k := range cfg.Profiles {+ cfg.CurrentProfile = k+ break+ }+ }+ if err := cfg.Save(); err != nil {+ return err+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Logged out of profile %q\n", name)+ return nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./cmd/traceway/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/+git commit -m "feat(cmd): logout command — remove profile and reset current pointer"+```++---++## Task 19: cmd/traceway — `profiles list` and `profiles use`++**Files:**+- Modify: `cmd/traceway/profiles.go` (replace stub)+- Create: `cmd/traceway/profiles_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/profiles_test.go`:++```go+package main++import (+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+)++func seedTwoProfiles(t *testing.T) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ cfg := &config.Config{+ CurrentProfile: "default",+ Profiles: map[string]config.Profile{+ "default": {URL: "https://a", Username: "fred@a"},+ "cloud": {URL: "https://b", Username: "fred@b"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+}++func TestProfilesList_table(t *testing.T) {+ seedTwoProfiles(t)+ stdout, _, err := runCmd(t, "", "profiles", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "default") {+ t.Errorf("missing 'default' in output: %s", out)+ }+ if !strings.Contains(out, "cloud") {+ t.Errorf("missing 'cloud' in output: %s", out)+ }+ // Current profile marked somehow (we use a "*" prefix).+ if !strings.Contains(out, "*") {+ t.Errorf("expected current-profile marker '*': %s", out)+ }+}++func TestProfilesList_json(t *testing.T) {+ seedTwoProfiles(t)+ stdout, _, err := runCmd(t, "", "profiles", "list", "--output", "json")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"default"`) || !strings.Contains(out, `"cloud"`) {+ t.Errorf("expected both profiles in JSON, got: %s", out)+ }+ if !strings.Contains(out, `"current"`) {+ t.Errorf("expected 'current' field in JSON, got: %s", out)+ }+}++func TestProfilesUse_setsCurrent(t *testing.T) {+ seedTwoProfiles(t)+ if _, _, err := runCmd(t, "", "profiles", "use", "cloud"); err != nil {+ t.Fatal(err)+ }+ cfg, _ := config.Load()+ if cfg.CurrentProfile != "cloud" {+ t.Errorf("CurrentProfile = %q, want cloud", cfg.CurrentProfile)+ }+}++func TestProfilesUse_unknown_returnsAuthError(t *testing.T) {+ seedTwoProfiles(t)+ _, stderr, err := runCmd(t, "", "profiles", "use", "ghost", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"no_profile"`) {+ t.Errorf("expected 'no_profile' code in stderr, got: %s", stderr.String())+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./cmd/traceway/...`+Expected: failures (profiles is a stub).++- [ ] **Step 3: Implement `profiles list` and `profiles use`**++Replace `cmd/traceway/profiles.go`:++```go+package main++import (+ "errors"+ "fmt"+ "sort"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+)++func newProfilesCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "profiles",+ Short: "Manage stored Traceway profiles",+ }+ cmd.AddCommand(newProfilesListCmd())+ cmd.AddCommand(newProfilesUseCmd())+ return cmd+}++func newProfilesListCmd() *cobra.Command {+ return &cobra.Command{+ Use: "list",+ Short: "List configured profiles",+ RunE: runProfilesList,+ }+}++type profileSummary struct {+ Name string `json:"name"`+ URL string `json:"url"`+ Username string `json:"username"`+ Current bool `json:"current"`+}++type profilesListResponse struct {+ Current string `json:"current"`+ Data []profileSummary `json:"data"`+}++func runProfilesList(cmd *cobra.Command, _ []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ names := make([]string, 0, len(cfg.Profiles))+ for n := range cfg.Profiles {+ names = append(names, n)+ }+ sort.Strings(names)++ resp := profilesListResponse{Current: cfg.CurrentProfile}+ for _, n := range names {+ p := cfg.Profiles[n]+ resp.Data = append(resp.Data, profileSummary{+ Name: n,+ URL: p.URL,+ Username: p.Username,+ Current: n == cfg.CurrentProfile,+ })+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ fmt.Fprintln(tw, " \tNAME\tURL\tUSERNAME")+ for _, p := range resp.Data {+ marker := " "+ if p.Current {+ marker = "*"+ }+ fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", marker, p.Name, p.URL, p.Username)+ }+ return tw.Flush()+ }+}++func newProfilesUseCmd() *cobra.Command {+ return &cobra.Command{+ Use: "use <profile>",+ Short: "Set the current profile",+ Args: cobra.ExactArgs(1),+ RunE: runProfilesUse,+ }+}++func runProfilesUse(cmd *cobra.Command, args []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }+ name := args[0]+ if _, ok := cfg.Profiles[name]; !ok {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "no_profile",+ Message: fmt.Sprintf("profile %q does not exist", name),+ Hint: "traceway profiles list",+ ExitCode: exitcode.Auth,+ })+ lastExitCode = exitcode.Auth+ return errors.New("no_profile")+ }+ cfg.CurrentProfile = name+ if err := cfg.Save(); err != nil {+ return err+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Now using profile %q\n", name)+ return nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./cmd/traceway/...`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/+git commit -m "feat(cmd): profiles list and profiles use"+```++---++## Task 20: cmd/traceway — `projects list` and `projects use`++**Files:**+- Modify: `cmd/traceway/projects.go` (replace stub)+- Create: `cmd/traceway/projects_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/projects_test.go`:++```go+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+)++func seedProfileFor(t *testing.T, baseURL string) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ cfg := &config.Config{+ CurrentProfile: "default",+ Profiles: map[string]config.Profile{+ "default": {URL: baseURL, Username: "[email protected]", JWT: "tok"},+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+}++func TestProjectsList_jsonPassThrough(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/projects" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _, _ = w.Write([]byte(`{+ "data": [+ {"id":"p1","name":"alpha"},+ {"id":"p2","name":"beta"}+ ],+ "pagination":{"page":0,"pageSize":50,"total":2}+ }`))+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "projects", "list", "--output", "json")+ if err != nil {+ t.Fatalf("projects list: %v", err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"alpha"`) || !strings.Contains(out, `"beta"`) {+ t.Errorf("expected both project names, got: %s", out)+ }+ if !strings.Contains(out, `"pagination"`) {+ t.Errorf("expected pagination passthrough, got: %s", out)+ }+}++func TestProjectsList_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[{"id":"p1","name":"alpha"}],"pagination":{"total":1}}`))+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "projects", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "p1") || !strings.Contains(out, "alpha") {+ t.Errorf("expected id/name in table, got: %s", out)+ }+}++func TestProjectsList_unauth_writesEnvelope(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "projects", "list", "--output", "json", "--no-prompt")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"token_expired"`) {+ t.Errorf("expected token_expired envelope, got: %s", stderr.String())+ }+}++func TestProjectsList_noProfile_writesEnvelope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())++ _, stderr, err := runCmd(t, "", "projects", "list", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"not_authenticated"`) {+ t.Errorf("expected not_authenticated envelope, got: %s", stderr.String())+ }+}++func TestProjectsUse_persistsToProfile(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{}`))+ }))+ defer srv.Close()+ seedProfileFor(t, srv.URL)++ if _, _, err := runCmd(t, "", "projects", "use", "p1"); err != nil {+ t.Fatal(err)+ }+ cfg, _ := config.Load()+ if cfg.Profiles["default"].CurrentProjectID != "p1" {+ t.Errorf("CurrentProjectID = %q", cfg.Profiles["default"].CurrentProjectID)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `go test ./cmd/traceway/...`+Expected: failures.++- [ ] **Step 3: Implement projects**++Replace `cmd/traceway/projects.go`:++```go+package main++import (+ "errors"+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func newProjectsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "projects",+ Short: "List and switch projects",+ }+ cmd.AddCommand(newProjectsListCmd())+ cmd.AddCommand(newProjectsUseCmd())+ return cmd+}++func newProjectsListCmd() *cobra.Command {+ return &cobra.Command{+ Use: "list",+ Short: "List projects visible to the authenticated user",+ RunE: runProjectsList,+ }+}++func runProjectsList(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ cfg, err := config.Load()+ if err != nil {+ return err+ }+ profile, err := cfg.Active(flagProfile)+ if err != nil {+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "not_authenticated",+ Message: err.Error(),+ Hint: "traceway login",+ ExitCode: exitcode.Auth,+ })+ lastExitCode = exitcode.Auth+ return errors.New("not_authenticated")+ }++ c := client.New(profile.URL, client.WithJWT(profile.JWT))+ resp, err := c.ListProjects(ctx)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ fmt.Fprintln(tw, "ID\tNAME")+ for _, p := range resp.Data {+ fmt.Fprintf(tw, "%s\t%s\n", p.ID, p.Name)+ }+ return tw.Flush()+ }+}++func newProjectsUseCmd() *cobra.Command {+ return &cobra.Command{+ Use: "use <project-id>",+ Short: "Set the current project for the active profile",+ Args: cobra.ExactArgs(1),+ RunE: runProjectsUse,+ }+}++func runProjectsUse(cmd *cobra.Command, args []string) error {+ cfg, err := config.Load()+ if err != nil {+ return err+ }++ profileName := flagProfile+ if profileName == "" {+ profileName = cfg.CurrentProfile+ }+ if profileName == "" {+ profileName = "default"+ }+ p, ok := cfg.Profiles[profileName]+ if !ok {+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "no_profile",+ Message: fmt.Sprintf("profile %q does not exist", profileName),+ Hint: "traceway login",+ ExitCode: exitcode.Auth,+ })+ lastExitCode = exitcode.Auth+ return errors.New("no_profile")+ }+ p.CurrentProjectID = args[0]+ cfg.Profiles[profileName] = p+ if err := cfg.Save(); err != nil {+ return err+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Now using project %q for profile %q\n", args[0], profileName)+ return nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `go test ./cmd/traceway/...`+Expected: PASS.++- [ ] **Step 5: End-to-end smoke against stormwind (optional but recommended)**++Run against your real Traceway instance — replace placeholders with your stormwind URL and credentials:++```bash+go run ./cmd/traceway login --url https://traceway.stormwind.local --username [email protected]+# (enter password at prompt)++go run ./cmd/traceway projects list+go run ./cmd/traceway projects list --output json+go run ./cmd/traceway projects list --output yaml+go run ./cmd/traceway projects list --output json --fields id,name++go run ./cmd/traceway profiles list+```++Expected: each command exits 0 and shows the projects from your stormwind. If `login` fails with a different field name in the response, fix `loginResponse.Token`'s json tag in `pkg/client/auth.go` (see Task 9).++- [ ] **Step 6: Commit**++```bash+git add cmd/traceway/+git commit -m "feat(cmd): projects list and projects use"+```++---++## Self-Review (already performed during writing)++**Spec coverage check:**++| Spec section | Implementing tasks |+|---|---|+| Audience priority (LLM-first, humans at home) | Task 11 (auto-detect TTY), Task 15 (envelope shapes) |+| Profile model + `--profile default` | Tasks 4–6, 17–19 |+| Project model + `--project` resolution | Task 6 (resolution helpers), Task 20 (per-profile current) |+| `--output json/yaml/table` + auto-detect | Tasks 11–14 |+| `--fields` projection | Task 12 |+| Pagination (one HTTP call per command) | Task 10 (Pagination type) |+| Mutations confirmation gate | **Deferred to Plan 3** (no mutations in Plan 1) |+| Error envelope (JSON + prose) | Task 15, Task 17 (error helper) |+| Exit codes | Task 2, Task 17 (lastExitCode wiring) |+| Token expiry retry | **Partially in Plan 1** (envelope-only path); interactive retry deferred to Plan 2 first-use |+| Atomic config writes, 0600/0700 | Task 5 |+| Library-first (`pkg/client`) | Tasks 7–10 (no CLI imports) |+| Smoke harness | **Deferred to Plan 3** |+| `justfile` + `just` in dev shell | Task 1 |++Two intentional Plan-1 deferrals:+- **Mutations + confirmation gate** — no mutations exist yet (no `--yes` workflow to test).+- **Interactive token-expiry re-login retry** — implemented as envelope-only in Plan 1; the interactive prompt path lands when the first read-resource needs it (Plan 2).++**Placeholder scan:** No "TBD"/"TODO" in steps. The two endpoint-shape "confirm against upstream" notes (Tasks 9, 10) are explicit research items, not placeholders.++**Type consistency:** Spot-checked across tasks. `Config`, `Profile`, `Client`, `Project`, `Pagination`, `ListProjectsResponse`, `Mode`, `ErrorEnvelope`, `lastExitCode` — all named consistently across the tasks that reference them. `flagProfile`/`flagProject`/`flagOutput`/`flagFields`/`flagYes`/`flagNoPrompt` declared once in Task 16, used by name in Tasks 17–20.++---++## End-of-plan checkpoint++After Task 20, you should be able to:++```bash+just test # all tests pass+just lint # no lint findings+just vulncheck # no vulns+go run ./cmd/traceway login --url <your URL> --username <you>+go run ./cmd/traceway projects list+go run ./cmd/traceway profiles list+```++End state: working CLI with auth, profiles, project switching, and three output formats. All architectural patterns (client, config, output, errors, profiles, exit codes) are in place. Plan 2 builds on this for the read resources (exceptions, logs, endpoints, metrics).diff --git a/cli/docs/superpowers/plans/2026-05-14-traceway-cli-mutations-and-smoke.md b/cli/docs/superpowers/plans/2026-05-14-traceway-cli-mutations-and-smoke.mdnew file mode 100644index 00000000..de6c5934--- /dev/null+++ b/cli/docs/superpowers/plans/2026-05-14-traceway-cli-mutations-and-smoke.md@@ -0,0 +1,1339 @@+# traceway-cli Mutations + Smoke Harness + README Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Close out v1 of the CLI by adding the only mutating commands the spec calls for (`exceptions archive` / `exceptions unarchive`), plus a confirmation gate that's safe for both humans and LLMs, a build-tag-gated smoke test suite that exercises the full stack against a real Traceway instance, and a README so a new caller (human or agent) can pick the tool up cold.++**Architecture:** Same library-first split established in Plan 1 — mutation methods live on `pkg/client.Client` with no CLI concerns; subcommands in `cmd/traceway/exceptions.go` parse args, call a shared `confirmMutation()` helper for safety, then call the client. Smoke tests live under `test/smoke/` behind a `//go:build smoke` tag so the default `go test ./...` skips them; they read connection/credential info from environment variables and round-trip through the public CLI surface. README is a single top-level `README.md`.++**Tech Stack:** Go (stdlib `net/http`, `os`, `bufio`), Cobra, existing `internal/{config,state,output,exitcode}` packages, existing `pkg/client.Client`/`do()` infrastructure.++---++## Critical context: upstream API shape (verified 2026-05-14)++The brainstorm spec mentioned "archive + resolve" but `tracewayapp/traceway/backend/app/routes.go` actually exposes:++```+POST /api/exception-stack-traces/archive (RequireProjectAccess + RequireWriteAccess)+POST /api/exception-stack-traces/unarchive (RequireProjectAccess + RequireWriteAccess)+```++There is **no** `resolve` route upstream. Plan 3 implements `archive` + `unarchive` to match reality. (The ListExceptions request already exposes `IncludeArchived`; toggling that is how callers see archived items.)++Both routes accept the same JSON body shape, with `projectId` as a URL **query param** (not a body field) — same convention all the other endpoints use:++```go+type ArchiveRequest struct {+ Hashes []string `json:"hashes"`+}+```++Response on success: `{"success": true}` (just a status confirmation; we don't expose the struct, we surface the count and the hashes the user passed).++---++## Confirmation gate semantics++These are the only mutating commands in v1, but the gate must work the same way for any mutation we add later, so we implement it as a reusable helper.++**Resolution order** (first match wins):++1. `--yes` flag is set → proceed silently.+2. `TRACEWAY_ASSUME_YES=1` (or `=true`) environment variable → proceed silently. (Lets CI / wrapper scripts opt in once instead of threading `--yes` through every invocation.)+3. stdin is a TTY → print the summary, prompt `Continue? [y/N] `, read one line, accept only `y` or `yes` (case-insensitive). Anything else → `usage_error` envelope, exit 2.+4. stdin is not a TTY and neither opt-in is set → render `usage_error` immediately with hint `pass --yes or set TRACEWAY_ASSUME_YES=1`, exit 2. (LLMs invoking the CLI via Bash get a clear, machine-readable refusal instead of a hung prompt.)++**What the summary looks like:**++```+About to archive 3 exception group(s):+ - 5f8a3b1c9d2e+ - a1b2c3d4e5f6+ - 0123456789ab+Continue? [y/N]+```++The verb (`archive` vs `unarchive`) is the only thing that changes between the two commands. Hashes longer than 12 chars are truncated for the prompt, full hashes still go on the wire.++**Why an env var as well as a flag:** matches `gh`'s pattern for non-interactive defaults; some callers (cron, CI) find an env var cleaner than threading a flag through wrappers. The flag still wins if both are set.++---++## Smoke harness shape++`test/smoke/` is a separate Go package gated behind `//go:build smoke` so:++- `go test ./...` (and `just test`) runs zero smoke tests.+- `go test -tags smoke ./test/smoke/...` (and `just smoke-test`) runs them all.++Each test reads required env vars at the top of the file via a single `requireEnv(t)` helper that calls `t.Skip(...)` (not `t.Fatal`) when any are missing. That way running `just smoke-test` without the env set produces clean SKIP output, not failures.++**Required env vars:**++- `TRACEWAY_SMOKE_URL` — e.g. `https://traceway.stormwind.local`+- `TRACEWAY_SMOKE_USERNAME` — email for login+- `TRACEWAY_SMOKE_PASSWORD` — password for login+- `TRACEWAY_SMOKE_PROJECT_ID` — UUID of the project to query against++Each test gets its own fresh `XDG_CONFIG_HOME` and `XDG_STATE_HOME` (via `t.TempDir()` + `t.Setenv`) so the user's actual credentials are never touched and tests can't leak state into each other. Tests shell out to the locally built binary (`go build -o $TMP/traceway ./cmd/traceway` once at TestMain), invoke it with `--output json`, and assert on the parsed envelope/response.++Coverage is intentionally narrow — one happy-path round trip per command, not exhaustive. The point is "does the wire shape we coded against match what real Traceway returns?", not regression coverage.++---++## File Map++```+pkg/client/+├── exceptions.go (modify) — add ArchiveExceptions, UnarchiveExceptions+└── exceptions_test.go (modify) — add tests for both++cmd/traceway/+├── querycommon.go (modify) — add confirmMutation() helper+├── querycommon_test.go (create) — confirmMutation tests+├── exceptions.go (modify) — wire up archive + unarchive subcommands+└── exceptions_test.go (modify) — add tests for both subcommands++test/smoke/ (create directory)+├── doc.go (create) — package comment + build tag+├── harness_test.go (create) — TestMain (build binary), runCLI helper, requireEnv+├── login_test.go (create) — login round trip+├── projects_test.go (create) — projects list round trip+├── exceptions_test.go (create) — exceptions list + archive/unarchive round trip+├── endpoints_test.go (create) — endpoints list round trip+└── logs_test.go (create) — logs query round trip++README.md (create) — top-level README+```++**File responsibilities (new):**++- **`pkg/client/exceptions.go` additions** — `ArchiveExceptions(ctx, projectID, hashes)` and `UnarchiveExceptions(ctx, projectID, hashes)`. Both POST to their respective `/api/exception-stack-traces/{archive,unarchive}?projectId=...` paths with `{"hashes":[...]}` body. Return `error` only (no useful response payload to surface).+- **`cmd/traceway/querycommon.go` addition** — `confirmMutation(cmd *cobra.Command, summaryLines []string) error` implementing the resolution order above. Stdin/TTY detection uses the same approach `output.StdoutIsTerminal` uses for stdout (peek at `*os.File` + `term.IsTerminal`). Returns nil on approval, `*cliError(usage)` on refusal/non-interactive without opt-in.+- **`cmd/traceway/exceptions.go` additions** — `newExceptionsArchiveCmd()` and `newExceptionsUnarchiveCmd()` registered onto the existing `exceptions` parent. Each takes `cobra.MinimumNArgs(1)` of hashes. The two share a single `runMutation` helper parameterised by verb + client method to avoid duplicating the boilerplate (session load, summary build, confirmation, client call, success render).+- **`test/smoke/harness_test.go`** — `TestMain` does one `go build` into a temp dir, exposes the binary path via a package-level var. `runCLI(t, args...)` returns `(stdout, stderr, exitCode)`. `requireEnv(t)` skips with a clear message if any var is missing. `freshXDG(t)` returns config + state dirs and sets the env vars with `t.Setenv`.+- **`README.md`** — install (Nix dev shell + `just build`), per-command usage examples, profiles + projects guide, output formats with field projection, error envelope reference table, smoke testing section.++---++## Task 1: pkg/client — ArchiveExceptions++**Files:**+- Modify: `pkg/client/exceptions.go`+- Modify: `pkg/client/exceptions_test.go`++- [ ] **Step 1: Write the failing tests**++Append to `pkg/client/exceptions_test.go`:++```go+func TestArchiveExceptions_postsHashesAndProjectId(t *testing.T) {+ var gotPath string+ var gotProject string+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("method = %q", r.Method)+ }+ gotPath = r.URL.Path+ gotProject = r.URL.Query().Get("projectId")+ _ = json.NewDecoder(r.Body).Decode(&gotBody)+ _, _ = w.Write([]byte(`{"success":true}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ err := c.ArchiveExceptions(context.Background(), "proj-1", []string{"h1", "h2", "h3"})+ if err != nil {+ t.Fatalf("ArchiveExceptions: %v", err)+ }+ if gotPath != "/api/exception-stack-traces/archive" {+ t.Errorf("path = %q", gotPath)+ }+ if gotProject != "proj-1" {+ t.Errorf("projectId = %q", gotProject)+ }+ hashes, _ := gotBody["hashes"].([]any)+ if len(hashes) != 3 || hashes[0] != "h1" || hashes[2] != "h3" {+ t.Errorf("body hashes = %v", hashes)+ }+}++func TestArchiveExceptions_403_returnsErrForbidden(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ err := c.ArchiveExceptions(context.Background(), "proj-1", []string{"h1"})+ if !errors.Is(err, ErrForbidden) {+ t.Errorf("expected ErrForbidden, got %v", err)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run ArchiveExceptions -count=1`+Expected: build failure — `ArchiveExceptions` undefined.++- [ ] **Step 3: Implement ArchiveExceptions**++Append to `pkg/client/exceptions.go`:++```go+// archiveRequest is the body for POST /api/exception-stack-traces/archive+// and .../unarchive. Same shape for both routes.+type archiveRequest struct {+ Hashes []string `json:"hashes"`+}++// ArchiveExceptions marks the given exception hashes as archived for the+// project. The upstream response is just {"success": true}; on success this+// returns nil and the caller can report the count back to the user.+func (c *Client) ArchiveExceptions(ctx context.Context, projectID string, hashes []string) error {+ path := "/api/exception-stack-traces/archive?projectId=" + url.QueryEscape(projectID)+ return c.do(ctx, http.MethodPost, path, archiveRequest{Hashes: hashes}, nil)+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -run ArchiveExceptions -count=1`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/exceptions.go pkg/client/exceptions_test.go+git commit -m "feat(client): ArchiveExceptions"+```++---++## Task 2: pkg/client — UnarchiveExceptions++**Files:**+- Modify: `pkg/client/exceptions.go`+- Modify: `pkg/client/exceptions_test.go`++- [ ] **Step 1: Write the failing test**++Append to `pkg/client/exceptions_test.go`:++```go+func TestUnarchiveExceptions_postsHashesAndProjectId(t *testing.T) {+ var gotPath string+ var gotProject string+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ gotProject = r.URL.Query().Get("projectId")+ _ = json.NewDecoder(r.Body).Decode(&gotBody)+ _, _ = w.Write([]byte(`{"success":true}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ err := c.UnarchiveExceptions(context.Background(), "proj-1", []string{"h1"})+ if err != nil {+ t.Fatalf("UnarchiveExceptions: %v", err)+ }+ if gotPath != "/api/exception-stack-traces/unarchive" {+ t.Errorf("path = %q", gotPath)+ }+ if gotProject != "proj-1" {+ t.Errorf("projectId = %q", gotProject)+ }+ hashes, _ := gotBody["hashes"].([]any)+ if len(hashes) != 1 || hashes[0] != "h1" {+ t.Errorf("body hashes = %v", hashes)+ }+}+```++- [ ] **Step 2: Run the test, verify it fails**++Run: `nix develop --command go test ./pkg/client/... -run UnarchiveExceptions -count=1`+Expected: build failure — `UnarchiveExceptions` undefined.++- [ ] **Step 3: Implement UnarchiveExceptions**++Append to `pkg/client/exceptions.go`:++```go+// UnarchiveExceptions reverses ArchiveExceptions for the given hashes.+func (c *Client) UnarchiveExceptions(ctx context.Context, projectID string, hashes []string) error {+ path := "/api/exception-stack-traces/unarchive?projectId=" + url.QueryEscape(projectID)+ return c.do(ctx, http.MethodPost, path, archiveRequest{Hashes: hashes}, nil)+}+```++(Reuses the unexported `archiveRequest` type from Task 1.)++- [ ] **Step 4: Run the test, verify it passes**++Run: `nix develop --command go test ./pkg/client/... -run UnarchiveExceptions -count=1`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/exceptions.go pkg/client/exceptions_test.go+git commit -m "feat(client): UnarchiveExceptions"+```++---++## Task 3: cmd/traceway — confirmMutation helper++**Files:**+- Modify: `cmd/traceway/querycommon.go`+- Create: `cmd/traceway/querycommon_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/querycommon_test.go`:++```go+package main++import (+ "bytes"+ "errors"+ "strings"+ "testing"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+)++// newTestCmd returns a minimal cobra command pre-wired with the global flags+// confirmMutation cares about (--yes is the only one).+func newTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "test"}+ cmd.Flags().BoolVar(&flagYes, "yes", false, "")+ return cmd+}++func TestConfirmMutation_yesFlagBypassesPrompt(t *testing.T) {+ t.Cleanup(func() { flagYes = false })+ flagYes = true++ cmd := newTestCmd()+ out := &bytes.Buffer{}+ cmd.SetOut(out)+ cmd.SetErr(out)+ cmd.SetIn(strings.NewReader("")) // no input — must not be consulted++ if err := confirmMutation(cmd, []string{"about to do thing"}); err != nil {+ t.Fatalf("confirmMutation = %v, want nil", err)+ }+ if out.Len() != 0 {+ t.Errorf("expected no output with --yes, got %q", out.String())+ }+}++func TestConfirmMutation_envVarBypassesPrompt(t *testing.T) {+ t.Setenv("TRACEWAY_ASSUME_YES", "1")+ cmd := newTestCmd()+ out := &bytes.Buffer{}+ cmd.SetOut(out)+ cmd.SetErr(out)+ cmd.SetIn(strings.NewReader(""))++ if err := confirmMutation(cmd, []string{"summary"}); err != nil {+ t.Fatalf("confirmMutation = %v, want nil", err)+ }+}++func TestConfirmMutation_nonTTYWithoutYes_returnsUsageError(t *testing.T) {+ cmd := newTestCmd()+ stderr := &bytes.Buffer{}+ cmd.SetOut(&bytes.Buffer{})+ cmd.SetErr(stderr)+ cmd.SetIn(strings.NewReader("")) // io.Reader, not *os.File → not a TTY++ err := confirmMutation(cmd, []string{"summary"})+ if err == nil {+ t.Fatal("expected error, got nil")+ }+ var ce *cliError+ if !errors.As(err, &ce) {+ t.Fatalf("expected *cliError, got %T", err)+ }+ if ce.code != exitcode.Usage {+ t.Errorf("exit code = %d, want %d", ce.code, exitcode.Usage)+ }+ if !strings.Contains(stderr.String(), "usage_error") {+ t.Errorf("stderr should contain usage_error envelope, got %q", stderr.String())+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run ConfirmMutation -count=1`+Expected: build failure — `confirmMutation` undefined.++- [ ] **Step 3: Implement confirmMutation**++Append to `cmd/traceway/querycommon.go`:++```go+// confirmMutation gates a destructive action behind one of three approvals,+// in priority order:+//+// 1. --yes flag is set+// 2. TRACEWAY_ASSUME_YES env var is set to a truthy value (1, true, yes)+// 3. stdin is a TTY → print summary + prompt, accept y/yes+//+// If none apply (non-TTY caller without an opt-in), a usage_error envelope+// is rendered to errOut and a *cliError(Usage) is returned. Callers should+// return that error directly so main() exits 2.+func confirmMutation(cmd *cobra.Command, summaryLines []string) error {+ if flagYes {+ return nil+ }+ if assume := strings.ToLower(strings.TrimSpace(os.Getenv("TRACEWAY_ASSUME_YES"))); assume == "1" || assume == "true" || assume == "yes" {+ return nil+ }++ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ in := cmd.InOrStdin()+ f, ok := in.(*os.File)+ if !ok || !term.IsTerminal(int(f.Fd())) {+ return renderUsageError(cmd.ErrOrStderr(), mode,+ "refusing to perform mutation without confirmation",+ "pass --yes or set TRACEWAY_ASSUME_YES=1")+ }++ out := cmd.OutOrStdout()+ for _, line := range summaryLines {+ _, _ = fmt.Fprintln(out, line)+ }+ _, _ = fmt.Fprint(out, "Continue? [y/N] ")++ r := bufio.NewReader(in)+ line, err := r.ReadString('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return renderUsageError(cmd.ErrOrStderr(), mode,+ "failed to read confirmation: "+err.Error(),+ "pass --yes to skip the prompt")+ }+ answer := strings.ToLower(strings.TrimSpace(line))+ if answer != "y" && answer != "yes" {+ return renderUsageError(cmd.ErrOrStderr(), mode,+ "confirmation declined", "")+ }+ return nil+}+```++Add the new imports to the import block (currently the file imports just `"io"`, `cobra`, `exitcode`, `output`, `client`):++```go+import (+ "bufio"+ "errors"+ "fmt"+ "io"+ "os"+ "strings"++ "github.com/spf13/cobra"+ "golang.org/x/term"++ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -run ConfirmMutation -count=1`+Expected: PASS.++- [ ] **Step 5: Run the full test suite to confirm no regressions**++Run: `nix develop --command go test ./... -count=1`+Expected: PASS across all packages.++- [ ] **Step 6: Commit**++```bash+git add cmd/traceway/querycommon.go cmd/traceway/querycommon_test.go+git commit -m "feat(cli): confirmMutation gate (--yes, env, TTY prompt)"+```++---++## Task 4: cmd/traceway — exceptions archive subcommand++**Files:**+- Modify: `cmd/traceway/exceptions.go`+- Modify: `cmd/traceway/exceptions_test.go`++- [ ] **Step 1: Write the failing tests**++Append to `cmd/traceway/exceptions_test.go`:++```go+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()++ withTestSession(t, srv.URL, "proj-1")+ stdout, stderr, err := runCmd(t, "exceptions", "archive", "--yes", "--output", "json", "h1", "h2")+ if err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr)+ }+ 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([]byte(stdout), &resp); err != nil {+ t.Fatalf("stdout not JSON: %v\n%s", err, stdout)+ }+ 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()++ withTestSession(t, srv.URL, "proj-1")+ stdout, stderr, err := runCmd(t, "exceptions", "archive", "--output", "json", "h1")+ if err == nil {+ t.Fatalf("expected error, got success: stdout=%s", stdout)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("stderr should contain usage_error: %s", stderr)+ }+ 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) {+ withTestSession(t, "https://unused", "proj-1")+ _, _, err := runCmd(t, "exceptions", "archive", "--yes")+ if err == nil {+ t.Fatal("expected error from missing args")+ }+}+```++(Helpers `runCmd` and `withTestSession` already exist in `cmd/traceway/testutil_test.go` from Plan 1/2 — confirm before writing this task that they accept the signature shown here. If `withTestSession` does not yet exist, factor it out from existing tests rather than writing a new one inline.)++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run ExceptionsArchive -count=1`+Expected: build failure or test failure — `archive` subcommand not registered.++- [ ] **Step 3: Implement the archive subcommand**++Append to `cmd/traceway/exceptions.go`. First, extend `newExceptionsCmd` to register the new subcommands:++```go+func newExceptionsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "exceptions",+ Short: "Query exception groups and occurrences",+ }+ cmd.AddCommand(newExceptionsListCmd())+ cmd.AddCommand(newExceptionsShowCmd())+ cmd.AddCommand(newExceptionsArchiveCmd())+ cmd.AddCommand(newExceptionsUnarchiveCmd())+ return cmd+}+```++Then add the archive command and the shared mutation runner:++```go+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)+ })+ },+ }+}++// 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 := client.New(sess.URL, client.WithJWT(sess.JWT))+ 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 {+ if len(hash) <= n {+ return hash+ }+ return hash[:n]+}+```++Add `"context"` to the imports if it isn't already there.++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -run ExceptionsArchive -count=1`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/exceptions.go cmd/traceway/exceptions_test.go+git commit -m "feat(cli): exceptions archive"+```++---++## Task 5: cmd/traceway — exceptions unarchive subcommand++**Files:**+- Modify: `cmd/traceway/exceptions.go`+- Modify: `cmd/traceway/exceptions_test.go`++- [ ] **Step 1: Write the failing test**++Append to `cmd/traceway/exceptions_test.go`:++```go+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()++ withTestSession(t, srv.URL, "proj-1")+ stdout, stderr, err := runCmd(t, "exceptions", "unarchive", "--yes", "--output", "json", "h1")+ if err != nil {+ t.Fatalf("runCmd: %v\nstderr: %s", err, stderr)+ }+ 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([]byte(stdout), &resp); err != nil {+ t.Fatalf("stdout not JSON: %v\n%s", err, stdout)+ }+ if resp["action"] != "unarchive" {+ t.Errorf("action = %v", resp["action"])+ }+}+```++- [ ] **Step 2: Run the test, verify it fails**++Run: `nix develop --command go test ./cmd/traceway/... -run ExceptionsUnarchive -count=1`+Expected: build failure — `unarchive` subcommand not registered.++- [ ] **Step 3: Implement the unarchive subcommand**++Append to `cmd/traceway/exceptions.go`:++```go+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)+ })+ },+ }+}+```++(`newExceptionsCmd` was already updated in Task 4 to call `AddCommand(newExceptionsUnarchiveCmd())`.)++- [ ] **Step 4: Run the test, verify it passes**++Run: `nix develop --command go test ./cmd/traceway/... -run ExceptionsUnarchive -count=1`+Expected: PASS.++- [ ] **Step 5: Run the full test suite**++Run: `nix develop --command go test ./... -count=1`+Expected: PASS across all packages.++- [ ] **Step 6: Commit**++```bash+git add cmd/traceway/exceptions.go cmd/traceway/exceptions_test.go+git commit -m "feat(cli): exceptions unarchive"+```++---++## Task 6: test/smoke — harness scaffolding + login round trip++**Files:**+- Create: `test/smoke/doc.go`+- Create: `test/smoke/harness_test.go`+- Create: `test/smoke/login_test.go`++- [ ] **Step 1: Create the package doc with the build tag**++Create `test/smoke/doc.go`:++```go+//go:build smoke++// Package smoke contains end-to-end tests that talk to a real Traceway+// instance via the built CLI binary. They are gated behind the "smoke"+// build tag so `go test ./...` skips them entirely.+//+// Run with: go test -tags smoke ./test/smoke/... (or `just smoke-test`).+//+// Required env vars (tests are skipped, not failed, if any are missing):+//+// TRACEWAY_SMOKE_URL e.g. https://traceway.stormwind.local+// TRACEWAY_SMOKE_USERNAME email used to log in+// TRACEWAY_SMOKE_PASSWORD password+// TRACEWAY_SMOKE_PROJECT_ID UUID of a project the user can access+package smoke+```++- [ ] **Step 2: Write the harness**++Create `test/smoke/harness_test.go`:++```go+//go:build smoke++package smoke++import (+ "bytes"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+)++var binaryPath string++func TestMain(m *testing.M) {+ tmp, err := os.MkdirTemp("", "traceway-smoke-bin-")+ if err != nil {+ panic(err)+ }+ defer os.RemoveAll(tmp)++ binaryPath = filepath.Join(tmp, "traceway")+ cmd := exec.Command("go", "build", "-o", binaryPath, "./cmd/traceway")+ cmd.Dir = repoRoot()+ if out, err := cmd.CombinedOutput(); err != nil {+ panic("smoke harness: go build failed: " + err.Error() + "\n" + string(out))+ }+ os.Exit(m.Run())+}++// repoRoot walks up from the current working dir to find go.mod.+func repoRoot() string {+ wd, err := os.Getwd()+ if err != nil {+ panic(err)+ }+ for d := wd; d != "/"; d = filepath.Dir(d) {+ if _, err := os.Stat(filepath.Join(d, "go.mod")); err == nil {+ return d+ }+ }+ panic("smoke harness: go.mod not found above " + wd)+}++// requireEnv reads the four smoke env vars and skips the test cleanly if+// any are missing. Returns (url, username, password, projectID).+func requireEnv(t *testing.T) (string, string, string, string) {+ t.Helper()+ url := os.Getenv("TRACEWAY_SMOKE_URL")+ user := os.Getenv("TRACEWAY_SMOKE_USERNAME")+ pass := os.Getenv("TRACEWAY_SMOKE_PASSWORD")+ proj := os.Getenv("TRACEWAY_SMOKE_PROJECT_ID")+ if url == "" || user == "" || pass == "" || proj == "" {+ t.Skip("smoke env not set (TRACEWAY_SMOKE_URL/USERNAME/PASSWORD/PROJECT_ID)")+ }+ return url, user, pass, proj+}++// freshXDG isolates each test by pointing XDG_CONFIG_HOME and XDG_STATE_HOME+// at fresh temp dirs. Cleanup is handled by t.TempDir.+func freshXDG(t *testing.T) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+}++// runCLI invokes the built binary with the given args. stdinBody is fed+// to the process stdin; pass "" for none. Returns stdout, stderr, exit code.+func runCLI(t *testing.T, stdinBody string, args ...string) (string, string, int) {+ t.Helper()+ cmd := exec.Command(binaryPath, args...)+ cmd.Env = os.Environ() // inherit XDG_* and any other vars+ if stdinBody != "" {+ cmd.Stdin = strings.NewReader(stdinBody)+ }+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ err := cmd.Run()+ code := 0+ if err != nil {+ var ee *exec.ExitError+ if errors.As(err, &ee) {+ code = ee.ExitCode()+ } else {+ t.Fatalf("runCLI: failed to run %v: %v", args, err)+ }+ }+ return stdout.String(), stderr.String(), code+}+```++- [ ] **Step 3: Write the login test**++Create `test/smoke/login_test.go`:++```go+//go:build smoke++package smoke++import (+ "strings"+ "testing"+)++// TestSmokeLogin authenticates against the real instance and verifies the+// resulting session works for one follow-up call. This is the prerequisite+// every other smoke test depends on.+func TestSmokeLogin(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)++ stdout, stderr, code := runCLI(t,+ pass+"\n",+ "login", "--url", url, "--username", user, "--password-stdin",+ )+ if code != 0 {+ t.Fatalf("login exit %d\nstdout: %s\nstderr: %s", code, stdout, stderr)+ }+ if !strings.Contains(stdout, "Logged in as "+user) {+ t.Errorf("login stdout = %q", stdout)+ }+}+```++- [ ] **Step 4: Verify the package compiles under the smoke tag**++Run: `nix develop --command go vet -tags smoke ./test/smoke/...`+Expected: no errors. (Tests aren't run yet — `go vet` is enough to catch typos.)++- [ ] **Step 5: Verify the default test run skips smoke tests**++Run: `nix develop --command go test ./... -count=1`+Expected: PASS, no `test/smoke` package reported (tag-gated out).++- [ ] **Step 6: Commit**++```bash+git add test/smoke/doc.go test/smoke/harness_test.go test/smoke/login_test.go+git commit -m "test(smoke): build-tag-gated harness with login round trip"+```++---++## Task 7: test/smoke — projects / exceptions / endpoints / logs round trips++**Files:**+- Create: `test/smoke/projects_test.go`+- Create: `test/smoke/exceptions_test.go`+- Create: `test/smoke/endpoints_test.go`+- Create: `test/smoke/logs_test.go`++Each test reuses the harness from Task 6: `requireEnv`, `freshXDG`, `runCLI`. They share a small pattern: log in, set the project, run the resource command, parse JSON, assert the wrapper shape.++- [ ] **Step 1: Write the projects test**++Create `test/smoke/projects_test.go`:++```go+//go:build smoke++package smoke++import (+ "encoding/json"+ "testing"+)++func TestSmokeProjectsList(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)++ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed (see TestSmokeLogin)")+ }++ stdout, stderr, code := runCLI(t, "", "projects", "list", "--output", "json")+ if code != 0 {+ t.Fatalf("projects list exit %d\nstderr: %s", code, stderr)+ }+ var arr []map[string]any+ if err := json.Unmarshal([]byte(stdout), &arr); err != nil {+ t.Fatalf("projects list stdout not a JSON array: %v\n%s", err, stdout)+ }+ if len(arr) == 0 {+ t.Fatal("projects list returned 0 projects; smoke account should have at least one")+ }+ if _, ok := arr[0]["id"]; !ok {+ t.Errorf("first project missing 'id' field: %v", arr[0])+ }+}+```++- [ ] **Step 2: Write the exceptions test**++Create `test/smoke/exceptions_test.go`:++```go+//go:build smoke++package smoke++import (+ "encoding/json"+ "testing"+)++func TestSmokeExceptionsList(t *testing.T) {+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)++ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }++ stdout, stderr, code := runCLI(t, "", "exceptions", "list", "--since", "24h", "--output", "json")+ if code != 0 {+ t.Fatalf("exceptions list exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Data []map[string]any `json:"data"`+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("exceptions list stdout not JSON: %v\n%s", err, stdout)+ }+ if resp.Pagination == nil {+ t.Errorf("exceptions list response missing pagination wrapper: %s", stdout)+ }+}+```++- [ ] **Step 3: Write the endpoints test**++Create `test/smoke/endpoints_test.go`:++```go+//go:build smoke++package smoke++import (+ "encoding/json"+ "testing"+)++func TestSmokeEndpointsList(t *testing.T) {+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)++ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }++ stdout, stderr, code := runCLI(t, "", "endpoints", "list", "--since", "24h", "--output", "json")+ if code != 0 {+ t.Fatalf("endpoints list exit %d\nstderr: %s", code, stderr)+ }+ var resp map[string]any+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("endpoints list stdout not JSON: %v\n%s", err, stdout)+ }+ if _, ok := resp["data"]; !ok {+ t.Errorf("endpoints list response missing 'data' field: %s", stdout)+ }+}+```++- [ ] **Step 4: Write the logs test**++Create `test/smoke/logs_test.go`:++```go+//go:build smoke++package smoke++import (+ "encoding/json"+ "testing"+)++func TestSmokeLogsQuery(t *testing.T) {+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)++ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }++ stdout, stderr, code := runCLI(t, "", "logs", "query", "--since", "1h", "--page-size", "5", "--output", "json")+ if code != 0 {+ t.Fatalf("logs query exit %d\nstderr: %s", code, stderr)+ }+ var resp map[string]any+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("logs query stdout not JSON: %v\n%s", err, stdout)+ }+ if _, ok := resp["data"]; !ok {+ t.Errorf("logs query response missing 'data' field: %s", stdout)+ }+}+```++(Intentionally no archive/unarchive smoke test: it would require finding a real exception hash to mutate, then leave server-side state different from before the test. The unit + CLI tests in Tasks 1, 2, 4, 5 already cover wire shape.)++- [ ] **Step 5: Verify the smoke package still compiles**++Run: `nix develop --command go vet -tags smoke ./test/smoke/...`+Expected: no errors.++- [ ] **Step 6: Verify default test run is unaffected**++Run: `nix develop --command go test ./... -count=1`+Expected: PASS, no smoke tests run.++- [ ] **Step 7: Commit**++```bash+git add test/smoke/projects_test.go test/smoke/exceptions_test.go test/smoke/endpoints_test.go test/smoke/logs_test.go+git commit -m "test(smoke): projects/exceptions/endpoints/logs round trips"+```++---++## Task 8: README.md++**Files:**+- Create: `README.md`++- [ ] **Step 1: Write the README**++Create `README.md`:++````markdown+# traceway-cli++A Go CLI for the [Traceway](https://github.com/tracewayapp/traceway) observability platform — exceptions, logs, endpoints, metrics. Designed to be **first-class for both LLMs (invoking via shell tools) and humans** (with `gh`-style ergonomics).++## Install++This repo ships a Nix dev shell with Go 1.26, `just`, `gotestsum`, `golangci-lint`, `govulncheck`, and `gh`:++```bash+nix develop+just build # produces ./bin/traceway+```++Or vanilla Go:++```bash+go build -o bin/traceway ./cmd/traceway+```++## Quick start++```bash+# 1. log in (creates ~/.config/traceway/config.json + ~/.local/state/traceway/state.json)+traceway login --url https://cloud.traceway.com++# 2. pick a project (one-time; future calls use it implicitly)+traceway projects list+traceway projects use <project-id>++# 3. ask questions+traceway exceptions list --since 24h+traceway logs query --since 1h --search "OutOfMemory"+traceway endpoints list --since 1h+traceway metrics query --name http.server.duration --aggregation avg --since 1h+```++## Commands++| Command | Purpose |+|---|---|+| `traceway login` | Authenticate and store the JWT |+| `traceway logout` | Forget the stored JWT for a profile |+| `traceway profiles {list,use}` | Manage multiple Traceway accounts/instances |+| `traceway projects {list,use}` | List or select the active project |+| `traceway exceptions list` | Recent grouped exceptions |+| `traceway exceptions show <hash>` | A single exception group + occurrences |+| `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 metrics query` | Time-series metric queries |++Run `traceway <command> --help` for full per-command flags.++## Profiles++Multiple Traceway instances or accounts coexist via profiles. Configuration (URL, username) lives in `$XDG_CONFIG_HOME/traceway/config.json` so it can be checked in or managed declaratively (e.g. NixOS); credentials and the active project live in `$XDG_STATE_HOME/traceway/state.json`.++```bash+traceway login --url https://traceway.example.com --profile work+traceway profiles list+traceway profiles use work+traceway --profile personal exceptions list # one-off override+```++## Output formats++The `--output` flag picks the format. The default is `table` on a TTY and `json` otherwise — i.e. piping always gets machine-readable output.++| Format | Use |+|---|---|+| `table` | Human-friendly columns (default on TTY) |+| `json` | Compact JSON, one record per line. Default when stdout isn't a TTY |+| `yaml` | YAML rendering of the same data |++`--fields a,b,c` projects list responses to just those keys (the `pagination` wrapper passes through unchanged):++```bash+traceway exceptions list --output json --fields exceptionHash,count,lastSeen+```++## Errors++Every error writes a stable JSON envelope to stderr (in `json` / `yaml` modes — prose in `table` mode) and exits with one of:++| Exit | Meaning |+|---|---|+| 0 | Success |+| 1 | Generic / API error |+| 2 | Usage error (bad flags, missing confirmation, invalid time range) |+| 3 | Connection failure |+| 4 | Auth failure (`not_authenticated`, `token_expired`, `forbidden`) |+| 5 | Not found |+| 6 | Rate limited |+| 7 | Server (5xx) |++Envelope shape:++```json+{"error":"token_expired","message":"session expired or invalid","hint":"traceway login","exit_code":4}+```++The `error` field is a stable snake_case identifier. LLMs/scripts can branch on it.++## Mutations + confirmation++`exceptions archive` and `exceptions unarchive` require explicit consent because they change server state:++- Pass `--yes` to skip the prompt.+- Or set `TRACEWAY_ASSUME_YES=1` in the environment.+- Or run interactively and answer the `Continue? [y/N]` prompt.++Calling a mutating command from a non-TTY context (script, LLM tool call) without one of the opt-ins fails immediately with `usage_error` (exit 2) — no hung prompts.++## Smoke testing++Unit/CLI tests run by default and never touch a network:++```bash+just test+```++End-to-end tests against a real Traceway instance are gated behind a build tag and read connection info from env vars:++```bash+export TRACEWAY_SMOKE_URL=https://traceway.example.com+export [email protected]+export TRACEWAY_SMOKE_PASSWORD=...+export TRACEWAY_SMOKE_PROJECT_ID=...+just smoke-test+```++If any of those vars is missing, the smoke tests skip cleanly rather than fail.++## Contributing++```bash+just check # lint + test + vulncheck+```++The library at `pkg/client` deliberately has zero CLI dependencies — it's importable directly by other Go programs (e.g. a future MCP server).+````++- [ ] **Step 2: Verify the README renders without obvious issues**++Run: `nix develop --command markdown-it README.md > /dev/null 2>&1 || true` (best-effort; if `markdown-it` isn't in the dev shell, just visually inspect).++- [ ] **Step 3: Commit**++```bash+git add README.md+git commit -m "docs: README"+```++---++## Task 9: Final regression sweep++**Files:**+- None (verification only)++- [ ] **Step 1: Run the full default test suite**++Run: `nix develop --command go test ./... -count=1`+Expected: PASS across all packages. No smoke tests reported.++- [ ] **Step 2: Run the linter**++Run: `nix develop --command just lint`+Expected: clean.++- [ ] **Step 3: Run the vulnerability scanner**++Run: `nix develop --command just vulncheck`+Expected: no findings (or only known-acceptable findings from prior plans, unchanged).++- [ ] **Step 4: Verify the smoke package builds under its tag**++Run: `nix develop --command go vet -tags smoke ./...`+Expected: clean.++- [ ] **Step 5: Sanity-check the binary**++Run:+```bash+nix develop --command just build+./bin/traceway --help+./bin/traceway exceptions --help+./bin/traceway exceptions archive --help+```+Expected: each prints usage with the expected flags. `exceptions archive --help` shows the `--yes` global flag and accepts `<hash> [<hash>...]`.++- [ ] **Step 6: If smoke env is configured, run the smoke suite as a final gate**++Run: `nix develop --command just smoke-test`+Expected: all smoke tests PASS (or SKIP if env is intentionally unset on this machine).++No commit — this task is verification only.diff --git a/cli/docs/superpowers/plans/2026-05-14-traceway-cli-read-resources.md b/cli/docs/superpowers/plans/2026-05-14-traceway-cli-read-resources.mdnew file mode 100644index 00000000..c9e87458--- /dev/null+++ b/cli/docs/superpowers/plans/2026-05-14-traceway-cli-read-resources.md@@ -0,0 +1,2999 @@+# traceway-cli Read Resources Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Wrap the four query resources Traceway exposes (exceptions, logs, endpoints, metrics), wiring them up as `traceway` subcommands that satisfy the four use cases approved during brainstorming: "what's broken in prod?", "why is endpoint X slow?", "what did service Y log?", "any anomalies?".++**Architecture:** Same library-first split established in Plan 1 — each resource is a method on `pkg/client.Client` plus a thin `cmd/traceway/<resource>.go` that parses flags, calls the client, renders output. Shared infrastructure (time-range parsing, pagination flags, per-command session loading) is extracted into reusable helpers so the 4 resource commands don't duplicate setup boilerplate.++**Tech Stack:** Go (stdlib `net/http`), Cobra, existing `internal/{config,state,output,exitcode}` packages, existing `pkg/client.Client`/`do()` infrastructure.++---++## Critical context: upstream API shape (verified 2026-05-14)++The design doc was wrong about how `projectId` is passed. Confirmed against `tracewayapp/traceway` source:++- `projectId` is a **URL query parameter** (`?projectId=<uuid>`), NOT in the request body. Read by `extractProjectId(c)` via `c.Query("projectId")` in `backend/app/middleware/require_project_access.middleware.go`.+- All four query endpoints are `POST` with a JSON body containing search params.+- All four return `PaginatedResponse[T]`:+ ```+ { "data": [...], "pagination": { "page", "pageSize", "total", "totalPages" } }+ ```+ EXCEPT `metrics/query` which returns `{ "results": [...] }` with no pagination.+- `PaginationParams` (request) has `page` + `pageSize`. `Pagination` (response) has `page`, `pageSize`, `total`, `totalPages`.+- Time fields are RFC3339 (`time.Time` in upstream Go, marshalled as RFC3339 strings).++Endpoint-specific request shapes (from `tracewayapp/traceway/backend/app/controllers/`):++```go+// /api/exception-stack-traces (FindGrouppedExceptionStackTraces)+type ExceptionSearchRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ Pagination PaginationParams `json:"pagination"`+ Search string `json:"search"`+ SearchType string `json:"searchType"`+ IncludeArchived bool `json:"includeArchived"`+}++// /api/exception-stack-traces/:hash (FindByHash)+type ExceptionDetailRequest struct {+ Pagination PaginationParams `json:"pagination"` // for occurrences list+}++// /api/logs (List)+type LogSearchRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ SortDirection string `json:"sortDirection"`+ Search string `json:"search"`+ SearchType string `json:"searchType"`+ MinSeverity uint8 `json:"minSeverity"`+ ServiceName string `json:"serviceName"`+ TraceId string `json:"traceId"`+ Pagination PaginationParams `json:"pagination"`+ // (other fields exist; we won't expose them in v1)+}++// /api/endpoints (FindAllEndpoints) — also FindGroupedByEndpoint with same shape+type EndpointSearchRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ OrderBy string `json:"orderBy"`+ SortDirection string `json:"sortDirection"`+ Pagination PaginationParams `json:"pagination"`+ Search string `json:"search"`+}++// /api/metrics/query (Query) — note: 'from'/'to' (not fromDate/toDate), no pagination+type MetricQueryRequest struct {+ Queries []MetricQueryItem `json:"queries"`+ From time.Time `json:"from"`+ To time.Time `json:"to"`+ IntervalMinutes int `json:"intervalMinutes"`+}+type MetricQueryItem struct {+ Name string `json:"name"`+ Aggregation string `json:"aggregation"`+ TagFilters map[string]string `json:"tagFilters"`+ GroupBy string `json:"groupBy"`+}+```++**Endpoint-grouping decision:** for `traceway endpoints list` we use `/api/endpoints/grouped` (returns `[]EndpointStats` with p50/p95/p99 per endpoint) — that's what humans/LLMs actually want. The bare `/api/endpoints` returns individual request samples (one row per request). The "grouped" route gives the per-endpoint stats view that matches use case #2 ("why is endpoint X slow?").++---++## File Map++```+pkg/client/+├── pagination.go (create) — Pagination + PaginationParams types+├── pagination_test.go (create)+├── time.go (create) — TimeRange type + JSON serialization helpers+├── time_test.go (create)+├── exceptions.go (create) — types, ListExceptions, GetException+├── exceptions_test.go (create)+├── logs.go (create) — types, QueryLogs+├── logs_test.go (create)+├── endpoints.go (create) — types, ListEndpoints (uses /endpoints/grouped)+├── endpoints_test.go (create)+├── metrics.go (create) — types, QueryMetrics+└── metrics_test.go (create)++cmd/traceway/+├── session.go (create) — loadSession() helper: config + state + active profile + project ID resolution+├── session_test.go (create)+├── timerange.go (create) — addTimeRangeFlags() + resolveTimeRange()+├── timerange_test.go (create)+├── querycommon.go (create) — addPaginationFlags() + addProjectFlag() (project flag is per-command)+├── exceptions.go (replace stub) — list + show subcommands+├── exceptions_test.go (create)+├── logs.go (replace stub) — query subcommand+├── logs_test.go (create)+├── endpoints.go (create) [+ register in root] — list subcommand+├── endpoints_test.go (create)+├── metrics.go (create) [+ register in root] — query subcommand+└── metrics_test.go (create)+└── root.go (modify) — register newExceptionsCmd, newLogsCmd, newEndpointsCmd, newMetricsCmd+```++**File responsibilities (new):**++- **`pkg/client/pagination.go`** — `Pagination` (response shape), `PaginationParams` (request shape). Only types; no behavior.+- **`pkg/client/time.go`** — `TimeRange{From, To time.Time}`. Used in request bodies (it's not a Cobra concern — that lives in `cmd/traceway/timerange.go`).+- **`pkg/client/{exceptions,logs,endpoints,metrics}.go`** — one file per resource: domain types + the `Client` methods that wrap the HTTP endpoints.+- **`cmd/traceway/session.go`** — single source of truth for "load config, load state, resolve active profile, resolve project ID." Every query command calls this.+- **`cmd/traceway/timerange.go`** — `addTimeRangeFlags()` registers `--since/--from/--to`; `resolveTimeRange()` validates and returns the `client.TimeRange`. Mutual-exclusivity rules live here.+- **`cmd/traceway/querycommon.go`** — `addPaginationFlags()` adds `--page` and `--page-size`. Also `addProjectFlag()` since `--project` is now per-command (the original persistent flag stays for backward compat? — see decision below).++**Decision on `--project` placement:** Plan 1 made `--project` a persistent root flag. We keep that for backward compat AND because every query command uses it. Per-command we just read `flagProject` directly. (No new flag declaration needed — it already exists.)++**Decision on `--since`/`--from`/`--to`/`--page`/`--page-size` placement:** These only apply to query commands. We add them per-command via the `addTimeRangeFlags`/`addPaginationFlags` helpers. They will NOT show up in `traceway login --help`, only in commands that use them.++---++## Task 1: pkg/client — Pagination types++**Files:**+- Create: `pkg/client/pagination.go`+- Test: `pkg/client/pagination_test.go`++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/pagination_test.go`:++```go+package client++import (+ "encoding/json"+ "testing"+)++func TestPaginationParams_marshalsJSON(t *testing.T) {+ p := PaginationParams{Page: 0, PageSize: 50}+ b, err := json.Marshal(p)+ if err != nil {+ t.Fatal(err)+ }+ want := `{"page":0,"pageSize":50}`+ if string(b) != want {+ t.Errorf("got %s, want %s", b, want)+ }+}++func TestPagination_unmarshalsJSON(t *testing.T) {+ in := `{"page":2,"pageSize":50,"total":312,"totalPages":7}`+ var p Pagination+ if err := json.Unmarshal([]byte(in), &p); err != nil {+ t.Fatal(err)+ }+ if p.Page != 2 || p.PageSize != 50 || p.Total != 312 || p.TotalPages != 7 {+ t.Errorf("got %+v", p)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run Pagination`+Expected: build failure — undefined types.++- [ ] **Step 3: Implement the types**++Create `pkg/client/pagination.go`:++```go+package client++// PaginationParams is the request-side pagination control.+type PaginationParams struct {+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+}++// Pagination is the response-side pagination block. Traceway returns this+// on every paginated list endpoint.+type Pagination struct {+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+ Total int64 `json:"total"`+ TotalPages int64 `json:"totalPages"`+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -run Pagination`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/pagination.go pkg/client/pagination_test.go+git commit -m "feat(client): Pagination and PaginationParams types"+```++---++## Task 2: pkg/client — TimeRange type++**Files:**+- Create: `pkg/client/time.go`+- Test: `pkg/client/time_test.go`++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/time_test.go`:++```go+package client++import (+ "testing"+ "time"+)++func TestTimeRange_zeroValueIsValid(t *testing.T) {+ tr := TimeRange{}+ if !tr.From.IsZero() || !tr.To.IsZero() {+ t.Error("zero TimeRange should have zero From/To")+ }+}++func TestTimeRangeFromSince_setsFromToNow(t *testing.T) {+ now := time.Date(2026, 5, 14, 12, 0, 0, 0, time.UTC)+ tr := TimeRangeFromSinceAt(time.Hour, now)+ if !tr.To.Equal(now) {+ t.Errorf("To = %v, want %v", tr.To, now)+ }+ wantFrom := now.Add(-time.Hour)+ if !tr.From.Equal(wantFrom) {+ t.Errorf("From = %v, want %v", tr.From, wantFrom)+ }+}++func TestTimeRangeFromExplicit(t *testing.T) {+ from := time.Date(2026, 5, 13, 0, 0, 0, 0, time.UTC)+ to := time.Date(2026, 5, 14, 0, 0, 0, 0, time.UTC)+ tr := TimeRangeFromExplicit(from, to)+ if !tr.From.Equal(from) {+ t.Errorf("From = %v, want %v", tr.From, from)+ }+ if !tr.To.Equal(to) {+ t.Errorf("To = %v, want %v", tr.To, to)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run TimeRange`+Expected: build failure.++- [ ] **Step 3: Implement TimeRange**++Create `pkg/client/time.go`:++```go+package client++import "time"++// TimeRange is an inclusive [From, To] interval used in resource queries.+// It marshals to RFC3339 strings via the request structs that embed it.+type TimeRange struct {+ From time.Time+ To time.Time+}++// TimeRangeFromSince returns a TimeRange ending now and starting `d` ago.+// Equivalent to TimeRangeFromSinceAt(d, time.Now()).+func TimeRangeFromSince(d time.Duration) TimeRange {+ return TimeRangeFromSinceAt(d, time.Now())+}++// TimeRangeFromSinceAt is the testable form: caller supplies "now".+func TimeRangeFromSinceAt(d time.Duration, now time.Time) TimeRange {+ return TimeRange{From: now.Add(-d), To: now}+}++// TimeRangeFromExplicit constructs a TimeRange from two explicit instants.+// Caller is responsible for ensuring From <= To.+func TimeRangeFromExplicit(from, to time.Time) TimeRange {+ return TimeRange{From: from, To: to}+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -run TimeRange`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/time.go pkg/client/time_test.go+git commit -m "feat(client): TimeRange type for resource queries"+```++---++## Task 3: cmd/traceway — session loader++**Files:**+- Create: `cmd/traceway/session.go`+- Test: `cmd/traceway/session_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/session_test.go`:++```go+package main++import (+ "errors"+ "net/http/httptest"+ "net/http"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++func TestLoadSession_happyPath(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x", Username: "u"},+ }}+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "proj-1"}},+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }++ sess, err := loadSession()+ if err != nil {+ t.Fatalf("loadSession: %v", err)+ }+ if sess.URL != "https://x" {+ t.Errorf("URL = %q", sess.URL)+ }+ if sess.JWT != "tok" {+ t.Errorf("JWT = %q", sess.JWT)+ }+ if sess.ProjectID != "proj-1" {+ t.Errorf("ProjectID = %q", sess.ProjectID)+ }+ if sess.ProfileName != "default" {+ t.Errorf("ProfileName = %q", sess.ProfileName)+ }+}++func TestLoadSession_flagProjectOverridesState(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ }}+ _ = cfg.Save()+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "proj-default"}},+ }+ _ = st.Save()++ flagProject = "proj-override"+ sess, err := loadSession()+ if err != nil {+ t.Fatal(err)+ }+ if sess.ProjectID != "proj-override" {+ t.Errorf("ProjectID = %q, want proj-override", sess.ProjectID)+ }+}++func TestLoadSession_missingProfile_returnsNotAuthenticated(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ _, err := loadSession()+ if !errors.Is(err, errSessionNoProfile) {+ t.Errorf("got %v, want errSessionNoProfile", err)+ }+}++func TestLoadSession_profileWithoutJWT_returnsNotAuthenticated(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ }}+ _ = cfg.Save()+ // State exists but has no JWT for this profile.+ st := &state.State{CurrentProfile: "default", Profiles: map[string]state.ProfileState{}}+ _ = st.Save()++ _, err := loadSession()+ if !errors.Is(err, errSessionNoJWT) {+ t.Errorf("got %v, want errSessionNoJWT", err)+ }+}++func TestLoadSession_missingProject_returnsNoProject(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: "https://x"},+ }}+ _ = cfg.Save()+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok"}}, // no current_project_id+ }+ _ = st.Save()++ _, err := loadSession()+ if !errors.Is(err, errSessionNoProject) {+ t.Errorf("got %v, want errSessionNoProject", err)+ }+}++// Sanity-check: a session built against an httptest server and an HTTP probe+// works end-to-end (smoke for caller patterns).+func TestLoadSession_pointsAtRealServer(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(204)+ }))+ defer srv.Close()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Cleanup(func() { flagProfile = ""; flagProject = "" })++ cfg := &config.Config{Profiles: map[string]config.Profile{"default": {URL: srv.URL}}}+ _ = cfg.Save()+ st := &state.State{CurrentProfile: "default", Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "p"}}}+ _ = st.Save()++ sess, err := loadSession()+ if err != nil {+ t.Fatal(err)+ }+ if sess.URL != srv.URL {+ t.Errorf("URL mismatch")+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run Session`+Expected: build failure.++- [ ] **Step 3: Implement loadSession**++Create `cmd/traceway/session.go`:++```go+package main++import (+ "errors"+ "fmt"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++// session bundles everything a query command needs after resolving config,+// state, the active profile, and the project ID. Built by loadSession.+type session struct {+ ProfileName string+ URL string+ Username string+ JWT string+ ProjectID string+}++// Sentinel errors so the caller can map them to the right error envelope.+var (+ errSessionNoProfile = errors.New("session: no profile configured")+ errSessionNoJWT = errors.New("session: profile has no stored token")+ errSessionNoProject = errors.New("session: no project selected")+)++// loadSession reads config + state, resolves the active profile and project,+// and returns a session. Returns one of the errSession* sentinels on common+// "you need to configure something" failures so callers can render the+// matching error envelope.+func loadSession() (*session, error) {+ cfg, err := config.Load()+ if err != nil {+ return nil, fmt.Errorf("loading config: %w", err)+ }+ st, err := state.Load()+ if err != nil {+ return nil, fmt.Errorf("loading state: %w", err)+ }++ name := resolveProfileName(st)+ cp, hasCfg := cfg.Profiles[name]+ if !hasCfg {+ return nil, fmt.Errorf("%w: %q", errSessionNoProfile, name)+ }++ sp, hasState := st.Profiles[name]+ if !hasState || sp.JWT == "" {+ return nil, fmt.Errorf("%w: %q", errSessionNoJWT, name)+ }++ projectID := flagProject+ if projectID == "" {+ projectID = sp.CurrentProjectID+ }+ if projectID == "" {+ return nil, fmt.Errorf("%w: profile %q has no current project", errSessionNoProject, name)+ }++ return &session{+ ProfileName: name,+ URL: cp.URL,+ Username: cp.Username,+ JWT: sp.JWT,+ ProjectID: projectID,+ }, nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -run Session`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/session.go cmd/traceway/session_test.go+git commit -m "feat(cmd): loadSession helper unifying config/state/profile/project resolution"+```++---++## Task 4: cmd/traceway — time range flag helper++**Files:**+- Create: `cmd/traceway/timerange.go`+- Test: `cmd/traceway/timerange_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/timerange_test.go`:++```go+package main++import (+ "testing"+ "time"++ "github.com/spf13/cobra"+)++// helper to build a fake command with the time-range flags wired+func newCmdWithTimeFlags(t *testing.T) *cobra.Command {+ t.Helper()+ cmd := &cobra.Command{Use: "fake"}+ addTimeRangeFlags(cmd)+ return cmd+}++func TestResolveTimeRange_defaultIsLastHour(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags(nil); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ delta := tr.To.Sub(tr.From)+ if delta < 59*time.Minute || delta > 61*time.Minute {+ t.Errorf("default range should be ~1h, got %v", delta)+ }+}++func TestResolveTimeRange_sinceFlag(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "30m"}); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ delta := tr.To.Sub(tr.From)+ if delta < 29*time.Minute || delta > 31*time.Minute {+ t.Errorf("--since 30m should give ~30m range, got %v", delta)+ }+}++func TestResolveTimeRange_fromTo(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{+ "--from", "2026-05-13T00:00:00Z",+ "--to", "2026-05-13T23:59:59Z",+ }); err != nil {+ t.Fatal(err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ t.Fatal(err)+ }+ wantFrom, _ := time.Parse(time.RFC3339, "2026-05-13T00:00:00Z")+ wantTo, _ := time.Parse(time.RFC3339, "2026-05-13T23:59:59Z")+ if !tr.From.Equal(wantFrom) {+ t.Errorf("From = %v, want %v", tr.From, wantFrom)+ }+ if !tr.To.Equal(wantTo) {+ t.Errorf("To = %v, want %v", tr.To, wantTo)+ }+}++func TestResolveTimeRange_sinceAndFromAreMutuallyExclusive(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{+ "--since", "1h",+ "--from", "2026-05-13T00:00:00Z",+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected mutual-exclusivity error")+ }+}++func TestResolveTimeRange_fromWithoutTo(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--from", "2026-05-13T00:00:00Z"}); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected error: --from requires --to")+ }+}++func TestResolveTimeRange_invalidFromFormat(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{+ "--from", "not-a-date",+ "--to", "2026-05-13T23:59:59Z",+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected parse error")+ }+}++func TestResolveTimeRange_invalidSinceDuration(t *testing.T) {+ cmd := newCmdWithTimeFlags(t)+ if err := cmd.ParseFlags([]string{"--since", "invalid"}); err != nil {+ t.Fatal(err)+ }+ if _, err := resolveTimeRange(cmd); err == nil {+ t.Fatal("expected duration parse error")+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run TimeRange`+Expected: build failure.++- [ ] **Step 3: Implement the helper**++Create `cmd/traceway/timerange.go`:++```go+package main++import (+ "errors"+ "fmt"+ "time"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/pkg/client"+)++// errInvalidTimeRange is returned for any malformed combination of+// --since / --from / --to. Callers map this to the invalid_time_range+// error envelope code with exit 2 (usage).+var errInvalidTimeRange = errors.New("invalid time range")++// addTimeRangeFlags registers --since, --from, --to on the given command.+// The default (no flags) is "since 1h".+func addTimeRangeFlags(cmd *cobra.Command) {+ f := cmd.Flags()+ f.String("since", "", "Relative time range, e.g. 1h, 24h, 7d (default: 1h, mutually exclusive with --from/--to)")+ f.String("from", "", "Start of explicit time range, RFC3339 (mutually exclusive with --since)")+ f.String("to", "", "End of explicit time range, RFC3339 (required with --from)")+}++// resolveTimeRange validates the combination of --since/--from/--to on cmd+// and returns the resulting TimeRange. The default (none of the flags) is+// "last 1 hour".+func resolveTimeRange(cmd *cobra.Command) (client.TimeRange, error) {+ since, _ := cmd.Flags().GetString("since")+ from, _ := cmd.Flags().GetString("from")+ to, _ := cmd.Flags().GetString("to")++ if since != "" && (from != "" || to != "") {+ return client.TimeRange{}, fmt.Errorf("%w: --since cannot be combined with --from/--to", errInvalidTimeRange)+ }+ if (from != "") != (to != "") {+ return client.TimeRange{}, fmt.Errorf("%w: --from and --to must be used together", errInvalidTimeRange)+ }++ if from != "" {+ fromT, err := time.Parse(time.RFC3339, from)+ if err != nil {+ return client.TimeRange{}, fmt.Errorf("%w: --from: %v", errInvalidTimeRange, err)+ }+ toT, err := time.Parse(time.RFC3339, to)+ if err != nil {+ return client.TimeRange{}, fmt.Errorf("%w: --to: %v", errInvalidTimeRange, err)+ }+ return client.TimeRangeFromExplicit(fromT, toT), nil+ }++ dur := time.Hour+ if since != "" {+ d, err := time.ParseDuration(since)+ if err != nil {+ return client.TimeRange{}, fmt.Errorf("%w: --since: %v", errInvalidTimeRange, err)+ }+ dur = d+ }+ return client.TimeRangeFromSince(dur), nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -run TimeRange`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/timerange.go cmd/traceway/timerange_test.go+git commit -m "feat(cmd): time range flag helpers (--since / --from / --to)"+```++---++## Task 5: cmd/traceway — pagination flag helper++**Files:**+- Create: `cmd/traceway/querycommon.go`+- Test: `cmd/traceway/querycommon_test.go`++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/querycommon_test.go`:++```go+package main++import (+ "testing"++ "github.com/spf13/cobra"+)++func TestResolvePagination_defaults(t *testing.T) {+ cmd := &cobra.Command{Use: "fake"}+ addPaginationFlags(cmd)+ if err := cmd.ParseFlags(nil); err != nil {+ t.Fatal(err)+ }+ p := resolvePagination(cmd)+ if p.Page != 0 {+ t.Errorf("Page = %d, want 0", p.Page)+ }+ if p.PageSize != 50 {+ t.Errorf("PageSize = %d, want 50", p.PageSize)+ }+}++func TestResolvePagination_explicit(t *testing.T) {+ cmd := &cobra.Command{Use: "fake"}+ addPaginationFlags(cmd)+ if err := cmd.ParseFlags([]string{"--page", "3", "--page-size", "100"}); err != nil {+ t.Fatal(err)+ }+ p := resolvePagination(cmd)+ if p.Page != 3 {+ t.Errorf("Page = %d, want 3", p.Page)+ }+ if p.PageSize != 100 {+ t.Errorf("PageSize = %d, want 100", p.PageSize)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run Pagination`+Expected: build failure.++- [ ] **Step 3: Implement the helper**++Create `cmd/traceway/querycommon.go`:++```go+package main++import (+ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/pkg/client"+)++// addPaginationFlags registers --page and --page-size on the given command.+// Defaults: page=0, page-size=50.+func addPaginationFlags(cmd *cobra.Command) {+ f := cmd.Flags()+ f.Int("page", 0, "Page number (0-indexed)")+ f.Int("page-size", 50, "Page size (max records per response)")+}++// resolvePagination reads the --page/--page-size flags from cmd and returns+// a PaginationParams. Assumes addPaginationFlags was called on the command.+func resolvePagination(cmd *cobra.Command) client.PaginationParams {+ page, _ := cmd.Flags().GetInt("page")+ pageSize, _ := cmd.Flags().GetInt("page-size")+ return client.PaginationParams{Page: page, PageSize: pageSize}+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -run Pagination`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/querycommon.go cmd/traceway/querycommon_test.go+git commit -m "feat(cmd): pagination flag helpers (--page, --page-size)"+```++---++## Task 6: pkg/client — exceptions list (with projectId query param)++**Files:**+- Create: `pkg/client/exceptions.go`+- Test: `pkg/client/exceptions_test.go`++This task introduces the **first endpoint that uses `?projectId=<uuid>`**. Future tasks for logs/endpoints/metrics follow the same pattern.++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/exceptions_test.go`:++```go+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestListExceptions_sendsProjectIdAsQueryParam(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId query = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["fromDate"] == nil || body["toDate"] == nil {+ t.Errorf("body missing fromDate/toDate: %v", body)+ }+ _, _ = w.Write([]byte(`{+ "data": [+ {"exceptionHash":"h1","stackTrace":"...","count":42,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"}+ ],+ "pagination":{"page":0,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListExceptions(context.Background(), "proj-1", ListExceptionsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ Pagination: PaginationParams{Page: 0, PageSize: 50},+ })+ if err != nil {+ t.Fatalf("ListExceptions: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("got %d exceptions, want 1", len(resp.Data))+ }+ if resp.Data[0].ExceptionHash != "h1" {+ t.Errorf("ExceptionHash = %q", resp.Data[0].ExceptionHash)+ }+ if resp.Data[0].Count != 42 {+ t.Errorf("Count = %d", resp.Data[0].Count)+ }+ if resp.Pagination.Total != 1 {+ t.Errorf("Pagination.Total = %d", resp.Pagination.Total)+ }+}++func TestListExceptions_emptyResults(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[],"pagination":{"page":0,"pageSize":50,"total":0,"totalPages":0}}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListExceptions(context.Background(), "proj-1", ListExceptionsRequest{})+ if err != nil {+ t.Fatal(err)+ }+ if len(resp.Data) != 0 {+ t.Errorf("expected empty Data")+ }+}++func TestListExceptions_passesSearchParameters(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["search"] != "NullPointer" {+ t.Errorf("search = %v", body["search"])+ }+ if body["searchType"] != "text" {+ t.Errorf("searchType = %v", body["searchType"])+ }+ if body["includeArchived"] != true {+ t.Errorf("includeArchived = %v", body["includeArchived"])+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.ListExceptions(context.Background(), "proj-1", ListExceptionsRequest{+ Search: "NullPointer",+ SearchType: "text",+ IncludeArchived: true,+ })+ if err != nil {+ t.Fatal(err)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run Exceptions`+Expected: build failure.++- [ ] **Step 3: Implement exceptions.go**++Create `pkg/client/exceptions.go`:++```go+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"+)++// ExceptionGroup matches Traceway's models.ExceptionGroup. Hourly trends are+// only present on list responses; on the detail endpoint they're absent.+type ExceptionGroup struct {+ ExceptionHash string `json:"exceptionHash"`+ StackTrace string `json:"stackTrace"`+ FirstSeen time.Time `json:"firstSeen"`+ LastSeen time.Time `json:"lastSeen"`+ Count uint64 `json:"count"`+ HourlyTrend []ExceptionTrendPoint `json:"hourlyTrend,omitempty"`+}++// ExceptionTrendPoint is one entry in an exception's hourly trend.+type ExceptionTrendPoint struct {+ Timestamp time.Time `json:"timestamp"`+ Count uint64 `json:"count"`+}++// ListExceptionsRequest is the body for POST /api/exception-stack-traces.+// projectId travels as a URL query param (handled by ListExceptions), not in+// the body — the upstream RequireProjectAccess middleware reads it via+// c.Query("projectId").+type ListExceptionsRequest struct {+ TimeRange TimeRange `json:"-"` // serialized as fromDate/toDate via MarshalJSON+ Pagination PaginationParams `json:"pagination"`+ OrderBy string `json:"orderBy,omitempty"`+ Search string `json:"search,omitempty"`+ SearchType string `json:"searchType,omitempty"`+ IncludeArchived bool `json:"includeArchived,omitempty"`+}++// MarshalJSON expands TimeRange.From / TimeRange.To into top-level fromDate /+// toDate so the wire shape matches Traceway's ExceptionSearchRequest.+func (r ListExceptionsRequest) MarshalJSON() ([]byte, error) {+ type alias ListExceptionsRequest+ wire := struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ alias+ }{+ FromDate: r.TimeRange.From,+ ToDate: r.TimeRange.To,+ alias: alias(r),+ }+ return jsonMarshalNoHTMLEscape(wire)+}++// ListExceptionsResponse mirrors the upstream PaginatedResponse[ExceptionGroup].+type ListExceptionsResponse struct {+ Data []ExceptionGroup `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// ListExceptions returns one page of grouped exceptions for the given project.+func (c *Client) ListExceptions(ctx context.Context, projectID string, req ListExceptionsRequest) (*ListExceptionsResponse, error) {+ path := "/api/exception-stack-traces?projectId=" + url.QueryEscape(projectID)+ var resp ListExceptionsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+```++You also need a tiny `jsonMarshalNoHTMLEscape` helper. Add it as the last function in `pkg/client/client.go` (NOT in exceptions.go — it's reusable for every resource that has a custom MarshalJSON). Open `pkg/client/client.go` and append at the bottom:++```go+// jsonMarshalNoHTMLEscape is a json.Marshal that doesn't escape <, >, & in+// strings. The default json.Marshal turns "p < 5" into "p < 5" which+// matches what httptest decoders see anyway, but produces noise in test+// failure messages and in --output json. We use this for any custom+// MarshalJSON on request bodies.+func jsonMarshalNoHTMLEscape(v any) ([]byte, error) {+ var buf bytes.Buffer+ enc := json.NewEncoder(&buf)+ enc.SetEscapeHTML(false)+ if err := enc.Encode(v); err != nil {+ return nil, err+ }+ // json.Encoder appends a trailing newline; trim it so callers can compose.+ out := buf.Bytes()+ if len(out) > 0 && out[len(out)-1] == '\n' {+ out = out[:len(out)-1]+ }+ return out, nil+}+```++`bytes` and `encoding/json` are already imported in client.go from Plan 1; no import changes needed.++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -count=1`+Expected: PASS for all client tests including the new exceptions tests.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/exceptions.go pkg/client/exceptions_test.go pkg/client/client.go+git commit -m "feat(client): ExceptionGroup, ListExceptionsRequest/Response, ListExceptions"+```++---++## Task 7: pkg/client — exception detail (show by hash)++**Files:**+- Modify: `pkg/client/exceptions.go` (add detail types + GetException method)+- Modify: `pkg/client/exceptions_test.go` (add tests)++- [ ] **Step 1: Write the failing tests**++Append to `pkg/client/exceptions_test.go`:++```go+func TestGetException_sendsHashInPath(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces/abc123" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ _, _ = w.Write([]byte(`{+ "group": {"exceptionHash":"abc123","stackTrace":"trace","count":7,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"},+ "occurrences": [+ {"id":"00000000-0000-0000-0000-000000000001","exceptionHash":"abc123","stackTrace":"trace","recordedAt":"2026-05-13T00:30:00Z"}+ ],+ "pagination": {"page":0,"pageSize":20,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.GetException(context.Background(), "proj-1", "abc123", PaginationParams{Page: 0, PageSize: 20})+ if err != nil {+ t.Fatalf("GetException: %v", err)+ }+ if resp.Group == nil || resp.Group.ExceptionHash != "abc123" {+ t.Errorf("Group missing or wrong hash: %+v", resp.Group)+ }+ if len(resp.Occurrences) != 1 {+ t.Fatalf("got %d occurrences, want 1", len(resp.Occurrences))+ }+ if resp.Occurrences[0].ExceptionHash != "abc123" {+ t.Errorf("Occurrence ExceptionHash = %q", resp.Occurrences[0].ExceptionHash)+ }+}++func TestGetException_404_returnsErrNotFound(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.GetException(context.Background(), "proj-1", "missing", PaginationParams{})+ if err == nil || err.Error() == "" {+ t.Error("expected an error")+ }+ // errors.Is check+ if !isNotFound(err) {+ t.Errorf("expected ErrNotFound, got %v", err)+ }+}++// helper because errors.Is needs the import in our test file too+func isNotFound(err error) bool {+ for ; err != nil; err = unwrap(err) {+ if err == ErrNotFound {+ return true+ }+ }+ return false+}++func unwrap(err error) error {+ type unwrapper interface{ Unwrap() error }+ if u, ok := err.(unwrapper); ok {+ return u.Unwrap()+ }+ return nil+}+```++(The `isNotFound` helper avoids adding `errors` to the test file's imports just for this; we already have it implicitly from earlier tests in the same file via `errors.Is`. If your editor complains, replace `isNotFound(err)` with `errors.Is(err, ErrNotFound)` and add `"errors"` to the import block.)++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run Exception`+Expected: build failure — `c.GetException undefined`.++- [ ] **Step 3: Implement GetException**++Append to `pkg/client/exceptions.go`:++```go+import (+ "github.com/google/uuid" // add to existing imports+)++// ExceptionStackTrace is one occurrence of a grouped exception.+type ExceptionStackTrace struct {+ Id uuid.UUID `json:"id"`+ ExceptionHash string `json:"exceptionHash"`+ StackTrace string `json:"stackTrace"`+ RecordedAt time.Time `json:"recordedAt"`+ TraceId *uuid.UUID `json:"traceId,omitempty"`+ TraceType string `json:"traceType,omitempty"`+ ServerName string `json:"serverName,omitempty"`+ AppVersion string `json:"appVersion,omitempty"`+ IsMessage bool `json:"isMessage,omitempty"`+ Attributes map[string]string `json:"attributes,omitempty"`+ DistributedTraceId *uuid.UUID `json:"distributedTraceId,omitempty"`+ SessionId *uuid.UUID `json:"sessionId,omitempty"`+}++// GetExceptionRequest is the body for POST /api/exception-stack-traces/:hash.+type getExceptionRequest struct {+ Pagination PaginationParams `json:"pagination"`+}++// GetExceptionResponse is the upstream ExceptionDetailResponse minus the+// session-recording blob (we don't expose recordings in v1).+type GetExceptionResponse struct {+ Group *ExceptionGroup `json:"group"`+ Occurrences []ExceptionStackTrace `json:"occurrences"`+ Pagination Pagination `json:"pagination"`+}++// GetException returns the group + paginated occurrences for the given hash.+func (c *Client) GetException(ctx context.Context, projectID, hash string, page PaginationParams) (*GetExceptionResponse, error) {+ path := "/api/exception-stack-traces/" + url.PathEscape(hash) + "?projectId=" + url.QueryEscape(projectID)+ var resp GetExceptionResponse+ if err := c.do(ctx, http.MethodPost, path, getExceptionRequest{Pagination: page}, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+```++You'll need to `nix develop --command go get github.com/google/uuid` (it's already a transitive dep but worth making it a direct one explicitly).++- [ ] **Step 4: Add the uuid dependency**++Run:+```bash+nix develop --command go get github.com/google/uuid+nix develop --command go mod tidy+```+Expected: `go.mod` shows `github.com/google/uuid` as direct.++- [ ] **Step 5: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -count=1`+Expected: PASS.++- [ ] **Step 6: Commit**++```bash+git add pkg/client/exceptions.go pkg/client/exceptions_test.go go.mod go.sum+git commit -m "feat(client): GetException + ExceptionStackTrace type"+```++---++## Task 8: cmd/traceway — exceptions list and show++**Files:**+- Modify: `cmd/traceway/exceptions.go` (replace stub)+- Create: `cmd/traceway/exceptions_test.go`+- Modify: `cmd/traceway/root.go` (already imports newExceptionsCmd from the stub; no change needed)++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/exceptions_test.go`:++```go+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/tracewayapp/traceway/cli/internal/config"+ "github.com/tracewayapp/traceway/cli/internal/state"+)++// seedSessionFor configures config + state for a default profile pointing at+// baseURL with a stored JWT and a current_project_id.+func seedSessionFor(t *testing.T, baseURL string) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ cfg := &config.Config{Profiles: map[string]config.Profile{+ "default": {URL: baseURL, Username: "[email protected]"},+ }}+ if err := cfg.Save(); err != nil {+ t.Fatal(err)+ }+ st := &state.State{+ CurrentProfile: "default",+ Profiles: map[string]state.ProfileState{"default": {JWT: "tok", CurrentProjectID: "proj-1"}},+ }+ if err := st.Save(); err != nil {+ t.Fatal(err)+ }+}++func TestExceptionsList_jsonShape(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ _, _ = w.Write([]byte(`{+ "data":[+ {"exceptionHash":"h1","stackTrace":"t1","count":7,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"}+ ],+ "pagination":{"page":0,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)+ t.Cleanup(func() { flagProject = "" })++ stdout, _, err := runCmd(t, "", "exceptions", "list", "--output", "json")+ if err != nil {+ t.Fatalf("exceptions list: %v", err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"h1"`) {+ t.Errorf("expected hash in output, got: %s", out)+ }+ if !strings.Contains(out, `"pagination"`) {+ t.Errorf("expected pagination passthrough, got: %s", out)+ }+}++func TestExceptionsList_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "data":[+ {"exceptionHash":"abcdef1234567890","stackTrace":"NullPointerException at line 42","count":7,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "exceptions", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ // First line is header+ if !strings.Contains(out, "HASH") || !strings.Contains(out, "COUNT") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "7") {+ t.Errorf("table missing count: %s", out)+ }+ // Hash should be truncated (first 12 chars by convention)+ if !strings.Contains(out, "abcdef123456") {+ t.Errorf("table missing truncated hash prefix: %s", out)+ }+}++func TestExceptionsList_noSession_writesEnvelope(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ _, stderr, err := runCmd(t, "", "exceptions", "list", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"not_authenticated"`) {+ t.Errorf("expected not_authenticated envelope, got: %s", stderr.String())+ }+}++func TestExceptionsList_invalidTimeRange_writesEnvelope(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "exceptions", "list", "--output", "json", "--since", "1h", "--from", "2026-05-13T00:00:00Z", "--to", "2026-05-13T23:59:59Z")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"invalid_time_range"`) {+ t.Errorf("expected invalid_time_range envelope, got: %s", stderr.String())+ }+}++func TestExceptionsShow_passesHashInPath(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces/abc" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _, _ = w.Write([]byte(`{+ "group":{"exceptionHash":"abc","stackTrace":"trace","count":3,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"},+ "occurrences":[],+ "pagination":{"page":0,"pageSize":20,"total":0,"totalPages":0}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "exceptions", "show", "abc", "--output", "json")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, `"abc"`) {+ t.Errorf("expected hash in output: %s", out)+ }+}++func TestExceptionsShow_404_writesNotFoundEnvelope(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "exceptions", "show", "missing", "--output", "json")+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(stderr.String(), `"not_found"`) {+ t.Errorf("expected not_found envelope, got: %s", stderr.String())+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run Exceptions`+Expected: failures — `exceptions` command is still a hidden stub.++- [ ] **Step 3: Implement the command**++Replace `cmd/traceway/exceptions.go`:++```go+package main++import (+ "errors"+ "fmt"++ "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"+)++func newExceptionsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "exceptions",+ Short: "Query exception groups and occurrences",+ }+ cmd.AddCommand(newExceptionsListCmd())+ cmd.AddCommand(newExceptionsShowCmd())+ return cmd+}++func newExceptionsListCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "list",+ Short: "List recent exception groups",+ RunE: runExceptionsList,+ }+ addTimeRangeFlags(cmd)+ addPaginationFlags(cmd)+ cmd.Flags().String("search", "", "Free-text search filter")+ cmd.Flags().String("search-type", "text", "Search type: text or regex")+ cmd.Flags().Bool("include-archived", false, "Include archived exceptions")+ cmd.Flags().String("order-by", "lastSeen", "Sort field (lastSeen, firstSeen, count)")+ return cmd+}++func runExceptionsList(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }++ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }+ page := resolvePagination(cmd)+ search, _ := cmd.Flags().GetString("search")+ searchType, _ := cmd.Flags().GetString("search-type")+ includeArchived, _ := cmd.Flags().GetBool("include-archived")+ orderBy, _ := cmd.Flags().GetString("order-by")++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.ListExceptions(ctx, sess.ProjectID, client.ListExceptionsRequest{+ TimeRange: tr,+ Pagination: page,+ Search: search,+ SearchType: searchType,+ IncludeArchived: includeArchived,+ OrderBy: orderBy,+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "HASH\tCOUNT\tLAST SEEN\tFIRST SEEN\tFIRST LINE")+ for _, e := range resp.Data {+ hash := e.ExceptionHash+ if len(hash) > 12 {+ hash = hash[:12]+ }+ _, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\t%s\n",+ hash, e.Count,+ e.LastSeen.Format("2006-01-02 15:04:05"),+ e.FirstSeen.Format("2006-01-02 15:04:05"),+ firstLine(e.StackTrace),+ )+ }+ return tw.Flush()+ }+}++func newExceptionsShowCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "show <hash>",+ Short: "Show a single exception group with its occurrences",+ Args: cobra.ExactArgs(1),+ RunE: runExceptionsShow,+ }+ addPaginationFlags(cmd)+ return cmd+}++func runExceptionsShow(cmd *cobra.Command, args []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ page := resolvePagination(cmd)+ page.PageSize = pickDefault(page.PageSize, 20) // detail uses 20 by default++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.GetException(ctx, sess.ProjectID, args[0], page)+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ // Group header, then occurrences table.+ if resp.Group != nil {+ _, _ = fmt.Fprintf(cmd.OutOrStdout(),+ "HASH: %s\nCOUNT: %d\nFIRST SEEN: %s\nLAST SEEN: %s\n\nSTACK TRACE:\n%s\n\nOCCURRENCES (%d):\n",+ resp.Group.ExceptionHash, resp.Group.Count,+ resp.Group.FirstSeen.Format("2006-01-02 15:04:05"),+ resp.Group.LastSeen.Format("2006-01-02 15:04:05"),+ resp.Group.StackTrace,+ len(resp.Occurrences),+ )+ }+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "ID\tRECORDED AT\tSERVER\tTRACE TYPE")+ for _, occ := range resp.Occurrences {+ traceType := occ.TraceType+ if traceType == "" {+ traceType = "-"+ }+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n",+ occ.Id.String(),+ occ.RecordedAt.Format("2006-01-02 15:04:05"),+ pickStr(occ.ServerName, "-"),+ traceType,+ )+ }+ return tw.Flush()+ }+}++// firstLine returns the first line of s, useful for fitting a stack trace+// into a table column.+func firstLine(s string) string {+ for i, ch := range s {+ if ch == '\n' || ch == '\r' {+ return s[:i]+ }+ }+ return s+}++// pickStr returns alt if s is empty, else s. Saves a guard at every callsite.+func pickStr(s, alt string) string {+ if s == "" {+ return alt+ }+ return s+}++// pickDefault returns alt if v is zero, else v.+func pickDefault(v, alt int) int {+ if v == 0 {+ return alt+ }+ return v+}++// renderSessionError maps loadSession sentinel errors to envelopes.+func renderSessionError(errOut interface {+ Write([]byte) (int, error)+}, mode output.Mode, err error) error {+ switch {+ case errors.Is(err, errSessionNoProfile), errors.Is(err, errSessionNoJWT):+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "not_authenticated",+ Message: err.Error(),+ Hint: "traceway login",+ ExitCode: exitcode.Auth,+ })+ lastExitCode = exitcode.Auth+ return errors.New("not_authenticated")+ case errors.Is(err, errSessionNoProject):+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "no_project",+ Message: err.Error(),+ Hint: "traceway projects use <project-id> (or pass --project)",+ ExitCode: exitcode.Usage,+ })+ lastExitCode = exitcode.Usage+ return errors.New("no_project")+ }+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "internal", Message: err.Error(), ExitCode: exitcode.Generic,+ })+ lastExitCode = exitcode.Generic+ return errors.New("internal")+}++// renderTimeRangeError maps errInvalidTimeRange (from resolveTimeRange) to an envelope.+func renderTimeRangeError(errOut interface {+ Write([]byte) (int, error)+}, mode output.Mode, err error) error {+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{+ Code: "invalid_time_range",+ Message: err.Error(),+ Hint: "use --since DURATION (e.g. 1h, 24h) or --from RFC3339 --to RFC3339",+ ExitCode: exitcode.Usage,+ })+ lastExitCode = exitcode.Usage+ return errors.New("invalid_time_range")+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -count=1`+Expected: PASS for the new exceptions tests (and all existing tests still pass).++- [ ] **Step 5: Commit**++```bash+git add cmd/traceway/exceptions.go cmd/traceway/exceptions_test.go+git commit -m "feat(cmd): exceptions list and exceptions show <hash>"+```++---++## Task 9: pkg/client — logs query++**Files:**+- Create: `pkg/client/logs.go`+- Test: `pkg/client/logs_test.go`++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/logs_test.go`:++```go+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestQueryLogs_basic(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/logs" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["fromDate"] == nil || body["toDate"] == nil {+ t.Errorf("body missing fromDate/toDate: %v", body)+ }+ _, _ = w.Write([]byte(`{+ "data":[+ {"id":"00000000-0000-0000-0000-000000000001","timestamp":"2026-05-13T12:00:00Z","severityText":"ERROR","severityNumber":17,"serviceName":"api","body":"boom"}+ ],+ "pagination":{"page":0,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.QueryLogs(context.Background(), "proj-1", QueryLogsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ Pagination: PaginationParams{Page: 0, PageSize: 50},+ ServiceName: "api",+ })+ if err != nil {+ t.Fatalf("QueryLogs: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("got %d logs", len(resp.Data))+ }+ if resp.Data[0].ServiceName != "api" {+ t.Errorf("ServiceName = %q", resp.Data[0].ServiceName)+ }+ if resp.Data[0].Body != "boom" {+ t.Errorf("Body = %q", resp.Data[0].Body)+ }+}++func TestQueryLogs_passesFilters(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["serviceName"] != "api" {+ t.Errorf("serviceName = %v", body["serviceName"])+ }+ if int(body["minSeverity"].(float64)) != 13 { // WARN per OTel severity numbers+ t.Errorf("minSeverity = %v", body["minSeverity"])+ }+ if body["traceId"] != "abc123" {+ t.Errorf("traceId = %v", body["traceId"])+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.QueryLogs(context.Background(), "proj-1", QueryLogsRequest{+ ServiceName: "api",+ MinSeverity: 13,+ TraceId: "abc123",+ })+ if err != nil {+ t.Fatal(err)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run Logs`+Expected: build failure.++- [ ] **Step 3: Implement logs.go**++Create `pkg/client/logs.go`:++```go+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"++ "github.com/google/uuid"+)++// LogRecord matches the upstream models.LogRecord (subset — we drop fields+// we don't surface in v1, like resource/scope schema URLs).+type LogRecord struct {+ Id uuid.UUID `json:"id"`+ Timestamp time.Time `json:"timestamp"`+ SeverityText string `json:"severityText"`+ SeverityNumber uint8 `json:"severityNumber"`+ ServiceName string `json:"serviceName"`+ Body string `json:"body"`+ TraceId string `json:"traceId,omitempty"`+ SpanId string `json:"spanId,omitempty"`+ ResourceAttributes map[string]string `json:"resourceAttributes,omitempty"`+ ScopeName string `json:"scopeName,omitempty"`+ LogAttributes map[string]string `json:"logAttributes,omitempty"`+}++// QueryLogsRequest is the body for POST /api/logs.+type QueryLogsRequest struct {+ TimeRange TimeRange `json:"-"`+ Pagination PaginationParams `json:"pagination"`+ OrderBy string `json:"orderBy,omitempty"`+ SortDirection string `json:"sortDirection,omitempty"`+ Search string `json:"search,omitempty"`+ SearchType string `json:"searchType,omitempty"`+ MinSeverity uint8 `json:"minSeverity,omitempty"`+ ServiceName string `json:"serviceName,omitempty"`+ TraceId string `json:"traceId,omitempty"`+}++// MarshalJSON expands TimeRange into top-level fromDate/toDate.+func (r QueryLogsRequest) MarshalJSON() ([]byte, error) {+ type alias QueryLogsRequest+ wire := struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ alias+ }{r.TimeRange.From, r.TimeRange.To, alias(r)}+ return jsonMarshalNoHTMLEscape(wire)+}++// QueryLogsResponse mirrors the upstream PaginatedResponse[LogRecord].+type QueryLogsResponse struct {+ Data []LogRecord `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// QueryLogs returns one page of log records for the given project and filters.+func (c *Client) QueryLogs(ctx context.Context, projectID string, req QueryLogsRequest) (*QueryLogsResponse, error) {+ path := "/api/logs?projectId=" + url.QueryEscape(projectID)+ var resp QueryLogsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -count=1`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/logs.go pkg/client/logs_test.go+git commit -m "feat(client): LogRecord, QueryLogsRequest/Response, QueryLogs"+```++---++## Task 10: cmd/traceway — logs query++**Files:**+- Modify: `cmd/traceway/logs.go` (currently a hidden stub from Plan 1 — replace it)+- Create: `cmd/traceway/logs_test.go`+- Modify: `cmd/traceway/root.go` (register the command)++The `logs` stub doesn't currently exist — Plan 1 only stubbed login/logout/profiles/projects. We need to add `cmd.AddCommand(newLogsCmd())` to root.go and create the file fresh.++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/logs_test.go`:++```go+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestLogsQuery_basic(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/logs" {+ t.Errorf("path = %q", r.URL.Path)+ }+ _, _ = w.Write([]byte(`{+ "data":[+ {"id":"00000000-0000-0000-0000-000000000001","timestamp":"2026-05-13T12:00:00Z","severityText":"ERROR","severityNumber":17,"serviceName":"api","body":"failed to connect"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "logs", "query", "--output", "json")+ if err != nil {+ t.Fatalf("logs query: %v", err)+ }+ if !strings.Contains(stdout.String(), "failed to connect") {+ t.Errorf("expected log body in output: %s", stdout.String())+ }+}++func TestLogsQuery_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "data":[+ {"id":"00000000-0000-0000-0000-000000000001","timestamp":"2026-05-13T12:00:00Z","severityText":"ERROR","severityNumber":17,"serviceName":"api","body":"failed to connect"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "logs", "query", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "TIMESTAMP") || !strings.Contains(out, "SEVERITY") || !strings.Contains(out, "SERVICE") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "ERROR") || !strings.Contains(out, "api") || !strings.Contains(out, "failed") {+ t.Errorf("table missing row data: %s", out)+ }+}++func TestLogsQuery_passesServiceFilter(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // Decode body and assert serviceName was passed through+ buf := make([]byte, 4096)+ n, _ := r.Body.Read(buf)+ body := string(buf[:n])+ if !strings.Contains(body, `"serviceName":"api"`) {+ t.Errorf("expected serviceName=api in body, got: %s", body)+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ if _, _, err := runCmd(t, "", "logs", "query", "--service", "api"); err != nil {+ t.Fatal(err)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run Logs`+Expected: failure — newLogsCmd is not registered.++- [ ] **Step 3: Implement logs.go**++Create `cmd/traceway/logs.go`:++```go+package main++import (+ "fmt"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func newLogsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "logs",+ Short: "Query log records",+ }+ cmd.AddCommand(newLogsQueryCmd())+ return cmd+}++func newLogsQueryCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "query",+ Short: "Query logs by time, service, severity, or trace",+ RunE: runLogsQuery,+ }+ addTimeRangeFlags(cmd)+ addPaginationFlags(cmd)+ cmd.Flags().String("service", "", "Filter by service name")+ cmd.Flags().Uint8("min-severity", 0, "Minimum OTel severity number (1=TRACE, 5=DEBUG, 9=INFO, 13=WARN, 17=ERROR, 21=FATAL)")+ cmd.Flags().String("trace-id", "", "Filter to a specific OpenTelemetry trace ID")+ cmd.Flags().String("search", "", "Free-text search in body")+ cmd.Flags().String("search-type", "body", "Search type: body or attribute")+ cmd.Flags().String("order-by", "timestamp", "Sort field")+ cmd.Flags().String("sort-direction", "desc", "Sort direction: asc or desc")+ return cmd+}++func runLogsQuery(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }+ page := resolvePagination(cmd)+ service, _ := cmd.Flags().GetString("service")+ minSev, _ := cmd.Flags().GetUint8("min-severity")+ traceID, _ := cmd.Flags().GetString("trace-id")+ search, _ := cmd.Flags().GetString("search")+ searchType, _ := cmd.Flags().GetString("search-type")+ orderBy, _ := cmd.Flags().GetString("order-by")+ sortDir, _ := cmd.Flags().GetString("sort-direction")++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.QueryLogs(ctx, sess.ProjectID, client.QueryLogsRequest{+ TimeRange: tr,+ Pagination: page,+ ServiceName: service,+ MinSeverity: minSev,+ TraceId: traceID,+ Search: search,+ SearchType: searchType,+ OrderBy: orderBy,+ SortDirection: sortDir,+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "TIMESTAMP\tSEVERITY\tSERVICE\tBODY")+ for _, l := range resp.Data {+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n",+ l.Timestamp.Format("2006-01-02 15:04:05"),+ pickStr(l.SeverityText, "-"),+ pickStr(l.ServiceName, "-"),+ firstLine(l.Body),+ )+ }+ return tw.Flush()+ }+}+```++- [ ] **Step 4: Register the command in root.go**++Open `cmd/traceway/root.go` and add `cmd.AddCommand(newLogsCmd())` to the existing `AddCommand` block (after `newProjectsCmd()`).++- [ ] **Step 5: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -count=1`+Expected: PASS.++- [ ] **Step 6: Commit**++```bash+git add cmd/traceway/logs.go cmd/traceway/logs_test.go cmd/traceway/root.go+git commit -m "feat(cmd): logs query command"+```++---++## Task 11: pkg/client — endpoints list (using /endpoints/grouped)++**Files:**+- Create: `pkg/client/endpoints.go`+- Test: `pkg/client/endpoints_test.go`++We use `/api/endpoints/grouped` (returns per-endpoint p50/p95/p99 stats) instead of `/api/endpoints` (returns individual request rows). The grouped view is what answers use case #2.++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/endpoints_test.go`:++```go+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestListEndpoints_callsGroupedRoute(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/endpoints/grouped" {+ t.Errorf("path = %q (want grouped)", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["fromDate"] == nil || body["toDate"] == nil {+ t.Errorf("body missing fromDate/toDate: %v", body)+ }+ // p50/p95/p99 are time.Duration in upstream — JSON encoded as nanoseconds (int64)+ _, _ = w.Write([]byte(`{+ "data":[+ {"endpoint":"GET /api/projects","count":120,"p50Duration":50000000,"p95Duration":150000000,"p99Duration":300000000,"avgDuration":80000000,"lastSeen":"2026-05-13T12:00:00Z","impact":0.42,"impactReason":"high p95"}+ ],+ "pagination":{"page":0,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListEndpoints(context.Background(), "proj-1", ListEndpointsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ Pagination: PaginationParams{Page: 0, PageSize: 50},+ })+ if err != nil {+ t.Fatalf("ListEndpoints: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("got %d endpoints", len(resp.Data))+ }+ if resp.Data[0].Endpoint != "GET /api/projects" {+ t.Errorf("Endpoint = %q", resp.Data[0].Endpoint)+ }+ if resp.Data[0].Count != 120 {+ t.Errorf("Count = %d", resp.Data[0].Count)+ }+ if resp.Data[0].P50Duration != 50*time.Millisecond {+ t.Errorf("P50Duration = %v, want 50ms", resp.Data[0].P50Duration)+ }+ if resp.Data[0].Impact != 0.42 {+ t.Errorf("Impact = %v", resp.Data[0].Impact)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run Endpoints`+Expected: build failure.++- [ ] **Step 3: Implement endpoints.go**++Create `pkg/client/endpoints.go`:++```go+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"+)++// EndpointStats matches the upstream models.EndpointStats. Durations are+// time.Duration values which Go marshals/unmarshals as nanoseconds.+type EndpointStats struct {+ Endpoint string `json:"endpoint"`+ Count uint64 `json:"count"`+ P50Duration time.Duration `json:"p50Duration"`+ P95Duration time.Duration `json:"p95Duration"`+ P99Duration time.Duration `json:"p99Duration"`+ AvgDuration time.Duration `json:"avgDuration"`+ LastSeen time.Time `json:"lastSeen"`+ Impact float64 `json:"impact"`+ ImpactReason string `json:"impactReason"`+}++// ListEndpointsRequest is the body for POST /api/endpoints/grouped.+type ListEndpointsRequest struct {+ TimeRange TimeRange `json:"-"`+ Pagination PaginationParams `json:"pagination"`+ OrderBy string `json:"orderBy,omitempty"`+ SortDirection string `json:"sortDirection,omitempty"`+ Search string `json:"search,omitempty"`+}++// MarshalJSON expands TimeRange into top-level fromDate/toDate.+func (r ListEndpointsRequest) MarshalJSON() ([]byte, error) {+ type alias ListEndpointsRequest+ wire := struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ alias+ }{r.TimeRange.From, r.TimeRange.To, alias(r)}+ return jsonMarshalNoHTMLEscape(wire)+}++// ListEndpointsResponse mirrors PaginatedResponse[EndpointStats].+type ListEndpointsResponse struct {+ Data []EndpointStats `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// ListEndpoints returns p50/p95/p99 stats grouped by endpoint route. We use+// the /grouped variant rather than the bare /endpoints (which returns one row+// per request).+func (c *Client) ListEndpoints(ctx context.Context, projectID string, req ListEndpointsRequest) (*ListEndpointsResponse, error) {+ path := "/api/endpoints/grouped?projectId=" + url.QueryEscape(projectID)+ var resp ListEndpointsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -count=1`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/endpoints.go pkg/client/endpoints_test.go+git commit -m "feat(client): EndpointStats, ListEndpointsRequest/Response, ListEndpoints"+```++---++## Task 12: cmd/traceway — endpoints list++**Files:**+- Create: `cmd/traceway/endpoints.go`+- Create: `cmd/traceway/endpoints_test.go`+- Modify: `cmd/traceway/root.go` (register newEndpointsCmd)++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/endpoints_test.go`:++```go+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestEndpointsList_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "data":[+ {"endpoint":"GET /api/projects","count":120,"p50Duration":50000000,"p95Duration":150000000,"p99Duration":300000000,"avgDuration":80000000,"lastSeen":"2026-05-13T12:00:00Z","impact":0.42,"impactReason":"high p95"}+ ],+ "pagination":{"total":1}+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "endpoints", "list", "--output", "table")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "ENDPOINT") || !strings.Contains(out, "P50") || !strings.Contains(out, "P95") || !strings.Contains(out, "P99") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "/api/projects") || !strings.Contains(out, "120") {+ t.Errorf("table missing row data: %s", out)+ }+ // Latency should be human-formatted (50ms, not 50000000)+ if strings.Contains(out, "50000000") {+ t.Errorf("table should format ns as human duration: %s", out)+ }+}++func TestEndpointsList_jsonShape(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[{"endpoint":"GET /","count":1}],"pagination":{}}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "endpoints", "list", "--output", "json")+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stdout.String(), `"GET /"`) {+ t.Errorf("missing endpoint in JSON: %s", stdout.String())+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run Endpoints`+Expected: failure (no endpoints command registered).++- [ ] **Step 3: Implement endpoints.go**++Create `cmd/traceway/endpoints.go`:++```go+package main++import (+ "fmt"+ "time"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++func newEndpointsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "endpoints",+ Short: "Query HTTP endpoint performance",+ }+ cmd.AddCommand(newEndpointsListCmd())+ return cmd+}++func newEndpointsListCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "list",+ Short: "List endpoints with p50/p95/p99 latency stats",+ RunE: runEndpointsList,+ }+ addTimeRangeFlags(cmd)+ addPaginationFlags(cmd)+ cmd.Flags().String("search", "", "Free-text search filter for endpoint names")+ cmd.Flags().String("order-by", "impact", "Sort field (impact, count, p95, lastSeen)")+ cmd.Flags().String("sort-direction", "desc", "Sort direction: asc or desc")+ return cmd+}++func runEndpointsList(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }+ page := resolvePagination(cmd)+ search, _ := cmd.Flags().GetString("search")+ orderBy, _ := cmd.Flags().GetString("order-by")+ sortDir, _ := cmd.Flags().GetString("sort-direction")++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.ListEndpoints(ctx, sess.ProjectID, client.ListEndpointsRequest{+ TimeRange: tr,+ Pagination: page,+ Search: search,+ OrderBy: orderBy,+ SortDirection: sortDir,+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "ENDPOINT\tCOUNT\tP50\tP95\tP99\tIMPACT\tLAST SEEN")+ for _, e := range resp.Data {+ _, _ = fmt.Fprintf(tw, "%s\t%d\t%s\t%s\t%s\t%.2f\t%s\n",+ e.Endpoint, e.Count,+ formatDuration(e.P50Duration),+ formatDuration(e.P95Duration),+ formatDuration(e.P99Duration),+ e.Impact,+ e.LastSeen.Format("2006-01-02 15:04:05"),+ )+ }+ return tw.Flush()+ }+}++// formatDuration renders a Duration as a human-readable string.+// time.Duration's String() does this already (e.g. "50ms"); we just shorten+// for very small values.+func formatDuration(d time.Duration) string {+ if d == 0 {+ return "0"+ }+ return d.String()+}+```++- [ ] **Step 4: Register the command**++In `cmd/traceway/root.go`, add `cmd.AddCommand(newEndpointsCmd())` to the AddCommand block.++- [ ] **Step 5: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -count=1`+Expected: PASS.++- [ ] **Step 6: Commit**++```bash+git add cmd/traceway/endpoints.go cmd/traceway/endpoints_test.go cmd/traceway/root.go+git commit -m "feat(cmd): endpoints list command"+```++---++## Task 13: pkg/client — metrics query++**Files:**+- Create: `pkg/client/metrics.go`+- Test: `pkg/client/metrics_test.go`++Metrics has a different shape: it uses `from`/`to` (not `fromDate`/`toDate`), takes a `queries` array (we expose only single-query in v1), and returns `{results: [...]}` (no pagination wrapper).++- [ ] **Step 1: Write the failing tests**++Create `pkg/client/metrics_test.go`:++```go+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestQueryMetrics_singleQuery(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/metrics/query" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ // metrics uses 'from'/'to', not fromDate/toDate+ if body["from"] == nil || body["to"] == nil {+ t.Errorf("body missing from/to: %v", body)+ }+ queries, _ := body["queries"].([]any)+ if len(queries) != 1 {+ t.Fatalf("expected 1 query, got %d", len(queries))+ }+ q := queries[0].(map[string]any)+ if q["name"] != "http.request.duration" {+ t.Errorf("query name = %v", q["name"])+ }+ if q["aggregation"] != "p95" {+ t.Errorf("aggregation = %v", q["aggregation"])+ }+ _, _ = w.Write([]byte(`{+ "results":[+ {+ "name":"http.request.duration",+ "unit":"ms",+ "series":{+ "all":[+ {"timestamp":"2026-05-13T12:00:00Z","value":42.5},+ {"timestamp":"2026-05-13T12:05:00Z","value":47.0}+ ]+ }+ }+ ]+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.QueryMetrics(context.Background(), "proj-1", QueryMetricsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ IntervalMinutes: 5,+ Queries: []MetricQueryItem{+ {Name: "http.request.duration", Aggregation: "p95"},+ },+ })+ if err != nil {+ t.Fatalf("QueryMetrics: %v", err)+ }+ if len(resp.Results) != 1 {+ t.Fatalf("got %d results", len(resp.Results))+ }+ r := resp.Results[0]+ if r.Name != "http.request.duration" {+ t.Errorf("Name = %q", r.Name)+ }+ if r.Unit != "ms" {+ t.Errorf("Unit = %q", r.Unit)+ }+ series, ok := r.Series["all"]+ if !ok {+ t.Fatal(`series["all"] missing`)+ }+ if len(series) != 2 {+ t.Errorf("got %d points, want 2", len(series))+ }+ if series[0].Value != 42.5 {+ t.Errorf("series[0].Value = %v", series[0].Value)+ }+}++func TestQueryMetrics_multiQuery(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ queries, _ := body["queries"].([]any)+ if len(queries) != 2 {+ t.Errorf("expected 2 queries, got %d", len(queries))+ }+ _, _ = w.Write([]byte(`{"results":[]}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.QueryMetrics(context.Background(), "proj-1", QueryMetricsRequest{+ Queries: []MetricQueryItem{+ {Name: "metric.a", Aggregation: "avg"},+ {Name: "metric.b", Aggregation: "sum"},+ },+ })+ if err != nil {+ t.Fatal(err)+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./pkg/client/... -run Metrics`+Expected: build failure.++- [ ] **Step 3: Implement metrics.go**++Create `pkg/client/metrics.go`:++```go+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"+)++// MetricQueryItem is one query within a QueryMetricsRequest.+type MetricQueryItem struct {+ Name string `json:"name"`+ Aggregation string `json:"aggregation,omitempty"`+ TagFilters map[string]string `json:"tagFilters,omitempty"`+ GroupBy string `json:"groupBy,omitempty"`+}++// QueryMetricsRequest is the body for POST /api/metrics/query.+//+// Note: metrics uses `from`/`to` (NOT fromDate/toDate like the other endpoints)+// and has no pagination — results are time-bucketed via IntervalMinutes.+type QueryMetricsRequest struct {+ TimeRange TimeRange `json:"-"`+ IntervalMinutes int `json:"intervalMinutes,omitempty"`+ Queries []MetricQueryItem `json:"queries"`+}++// MarshalJSON expands TimeRange into top-level from/to (NOT fromDate/toDate).+func (r QueryMetricsRequest) MarshalJSON() ([]byte, error) {+ type alias QueryMetricsRequest+ wire := struct {+ From time.Time `json:"from"`+ To time.Time `json:"to"`+ alias+ }{r.TimeRange.From, r.TimeRange.To, alias(r)}+ return jsonMarshalNoHTMLEscape(wire)+}++// TimeSeriesPoint is one data point in a metric query result.+type TimeSeriesPoint struct {+ Timestamp time.Time `json:"timestamp"`+ Value float64 `json:"value"`+}++// MetricQueryResult is one query's results, optionally grouped by tag.+// The map key is the group label ("all" if no GroupBy was specified).+type MetricQueryResult struct {+ Name string `json:"name"`+ Unit string `json:"unit"`+ Series map[string][]TimeSeriesPoint `json:"series"`+}++// QueryMetricsResponse is the upstream MetricQueryResponse.+type QueryMetricsResponse struct {+ Results []MetricQueryResult `json:"results"`+}++// QueryMetrics runs one or more metric queries against the project.+func (c *Client) QueryMetrics(ctx context.Context, projectID string, req QueryMetricsRequest) (*QueryMetricsResponse, error) {+ path := "/api/metrics/query?projectId=" + url.QueryEscape(projectID)+ var resp QueryMetricsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+```++- [ ] **Step 4: Run the tests, verify they pass**++Run: `nix develop --command go test ./pkg/client/... -count=1`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add pkg/client/metrics.go pkg/client/metrics_test.go+git commit -m "feat(client): MetricQueryItem, QueryMetricsRequest/Response, QueryMetrics"+```++---++## Task 14: cmd/traceway — metrics query++**Files:**+- Create: `cmd/traceway/metrics.go`+- Create: `cmd/traceway/metrics_test.go`+- Modify: `cmd/traceway/root.go` (register newMetricsCmd)++- [ ] **Step 1: Write the failing tests**++Create `cmd/traceway/metrics_test.go`:++```go+package main++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestMetricsQuery_jsonOutput(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "results":[+ {"name":"http.request.duration","unit":"ms","series":{"all":[{"timestamp":"2026-05-13T12:00:00Z","value":42.5}]}}+ ]+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "metrics", "query", "--name", "http.request.duration", "--aggregation", "p95", "--output", "json")+ if err != nil {+ t.Fatalf("metrics query: %v", err)+ }+ if !strings.Contains(stdout.String(), "http.request.duration") {+ t.Errorf("expected metric name in output: %s", stdout.String())+ }+ if !strings.Contains(stdout.String(), "42.5") {+ t.Errorf("expected value in output: %s", stdout.String())+ }+}++func TestMetricsQuery_table(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{+ "results":[+ {"name":"http.request.duration","unit":"ms","series":{+ "all":[+ {"timestamp":"2026-05-13T12:00:00Z","value":42.5},+ {"timestamp":"2026-05-13T12:05:00Z","value":47.0}+ ]+ }}+ ]+ }`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ stdout, _, err := runCmd(t, "", "metrics", "query", "--name", "http.request.duration")+ if err != nil {+ t.Fatal(err)+ }+ out := stdout.String()+ if !strings.Contains(out, "METRIC") || !strings.Contains(out, "GROUP") || !strings.Contains(out, "POINTS") {+ t.Errorf("table missing headers: %s", out)+ }+ if !strings.Contains(out, "http.request.duration") {+ t.Errorf("table missing metric name: %s", out)+ }+ if !strings.Contains(out, "47") {+ t.Errorf("table missing latest value: %s", out)+ }+}++func TestMetricsQuery_requiresName(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"results":[]}`))+ }))+ defer srv.Close()+ seedSessionFor(t, srv.URL)++ _, stderr, err := runCmd(t, "", "metrics", "query", "--output", "json")+ if err == nil {+ t.Fatal("expected --name to be required")+ }+ if !strings.Contains(stderr.String(), `"usage_error"`) {+ t.Errorf("expected usage_error envelope, got: %s", stderr.String())+ }+}+```++- [ ] **Step 2: Run the tests, verify they fail**++Run: `nix develop --command go test ./cmd/traceway/... -run Metrics`+Expected: failure.++- [ ] **Step 3: Implement metrics.go**++Create `cmd/traceway/metrics.go`:++```go+package main++import (+ "errors"+ "fmt"+ "strings"++ "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"+)++func newMetricsCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "metrics",+ Short: "Query metric time series",+ }+ cmd.AddCommand(newMetricsQueryCmd())+ return cmd+}++func newMetricsQueryCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "query",+ Short: "Query a single metric over time",+ RunE: runMetricsQuery,+ }+ addTimeRangeFlags(cmd)+ cmd.Flags().String("name", "", "Metric name (required)")+ cmd.Flags().String("aggregation", "avg", "Aggregation: avg, sum, count, min, max, p50, p95, p99")+ cmd.Flags().StringSlice("tag", nil, "Tag filter as key=value (repeatable)")+ cmd.Flags().String("group-by", "", "Tag to group series by")+ cmd.Flags().Int("interval-minutes", 0, "Time bucket size in minutes (0 = auto)")+ return cmd+}++func runMetricsQuery(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ sess, err := loadSession()+ if err != nil {+ return renderSessionError(cmd.ErrOrStderr(), mode, err)+ }+ tr, err := resolveTimeRange(cmd)+ if err != nil {+ return renderTimeRangeError(cmd.ErrOrStderr(), mode, err)+ }++ name, _ := cmd.Flags().GetString("name")+ if name == "" {+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "usage_error", Message: "--name is required",+ Hint: "traceway metrics query --name <metric-name>", ExitCode: exitcode.Usage,+ })+ lastExitCode = exitcode.Usage+ return errors.New("usage_error")+ }+ agg, _ := cmd.Flags().GetString("aggregation")+ groupBy, _ := cmd.Flags().GetString("group-by")+ intervalMin, _ := cmd.Flags().GetInt("interval-minutes")+ tags, _ := cmd.Flags().GetStringSlice("tag")++ tagFilters, err := parseTagFilters(tags)+ if err != nil {+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{+ Code: "usage_error", Message: err.Error(),+ Hint: "use --tag key=value (repeatable)", ExitCode: exitcode.Usage,+ })+ lastExitCode = exitcode.Usage+ return errors.New("usage_error")+ }++ c := client.New(sess.URL, client.WithJWT(sess.JWT))+ resp, err := c.QueryMetrics(ctx, sess.ProjectID, client.QueryMetricsRequest{+ TimeRange: tr,+ IntervalMinutes: intervalMin,+ Queries: []client.MetricQueryItem{+ {Name: name, Aggregation: agg, TagFilters: tagFilters, GroupBy: groupBy},+ },+ })+ if err != nil {+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)+ }++ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(cmd.OutOrStdout(), resp, output.ParseFieldsFlag(flagFields))+ default:+ // Summary table — for actual time-series data, --output json is recommended.+ tw := output.NewTabWriter(cmd.OutOrStdout())+ _, _ = fmt.Fprintln(tw, "METRIC\tUNIT\tGROUP\tPOINTS\tLATEST")+ for _, r := range resp.Results {+ if len(r.Series) == 0 {+ _, _ = fmt.Fprintf(tw, "%s\t%s\t-\t0\t-\n", r.Name, pickStr(r.Unit, "-"))+ continue+ }+ for group, pts := range r.Series {+ latest := "-"+ if len(pts) > 0 {+ latest = fmt.Sprintf("%g", pts[len(pts)-1].Value)+ }+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t%s\n", r.Name, pickStr(r.Unit, "-"), group, len(pts), latest)+ }+ }+ return tw.Flush()+ }+}++// parseTagFilters parses ["k=v", "x=y"] into {"k":"v","x":"y"}. Returns an+// error if any element is malformed.+func parseTagFilters(in []string) (map[string]string, error) {+ if len(in) == 0 {+ return nil, nil+ }+ out := make(map[string]string, len(in))+ for _, item := range in {+ k, v, ok := strings.Cut(item, "=")+ if !ok || k == "" {+ return nil, fmt.Errorf("invalid --tag %q: expected key=value", item)+ }+ out[k] = v+ }+ return out, nil+}+```++- [ ] **Step 4: Register the command**++In `cmd/traceway/root.go`, add `cmd.AddCommand(newMetricsCmd())` to the AddCommand block.++- [ ] **Step 5: Run the tests, verify they pass**++Run: `nix develop --command go test ./cmd/traceway/... -count=1`+Expected: PASS.++- [ ] **Step 6: Final full-suite check**++Run: `nix develop --command go test ./... -count=1 && nix develop --command go vet ./... && nix develop --command just build`+Expected: all tests pass, vet clean, binary builds.++Try the binary:+```bash+nix develop --command ./bin/traceway --help+nix develop --command ./bin/traceway exceptions --help+nix develop --command ./bin/traceway logs --help+nix develop --command ./bin/traceway endpoints --help+nix develop --command ./bin/traceway metrics --help+```+Expected: each shows the right subcommands and flags.++- [ ] **Step 7: Commit**++```bash+git add cmd/traceway/metrics.go cmd/traceway/metrics_test.go cmd/traceway/root.go+git commit -m "feat(cmd): metrics query command"+```++---++## Self-Review (performed inline during writing)++**Spec coverage check:**++| Spec/use case | Implementing tasks |+|---|---|+| "What's broken in prod?" — exceptions list/show | Tasks 6–8 |+| "Why is endpoint X slow?" — endpoints list with p50/p95/p99 | Tasks 11–12 |+| "What did service Y log?" — logs query with service/severity/trace filters | Tasks 9–10 |+| "Anomalies?" — metrics query | Tasks 13–14 |+| Time range: --since OR --from/--to, default 1h | Task 4 |+| Pagination: --page-size N (default 50), --page N (default 0) | Tasks 1, 5 |+| Pass-through JSON shape with --fields projection | Reuses Plan 1's `output.RenderJSON` |+| Stable error envelope with new codes (no_project, invalid_time_range) | Task 8 (renderSessionError, renderTimeRangeError) |+| One HTTP call per command (no auto-pagination) | Tasks 6, 9, 11, 13 |++**Placeholder scan:** No "TBD"/"TODO" steps. The two notes about "we don't expose recordings in v1" and "session recording blob omitted" are explicit scope decisions, not deferred work.++**Type consistency:** Spot-checked key names across tasks — `ListExceptionsRequest`, `ListExceptionsResponse`, `GetExceptionResponse`, `QueryLogsRequest/Response`, `ListEndpointsRequest/Response`, `QueryMetricsRequest/Response`, `EndpointStats`, `LogRecord`, `ExceptionGroup`, `ExceptionStackTrace`, `MetricQueryItem`, `MetricQueryResult`, `TimeSeriesPoint`, `Pagination`, `PaginationParams`, `TimeRange`. All consistent.++The `jsonMarshalNoHTMLEscape` helper is added to `pkg/client/client.go` in Task 6 and reused by Tasks 9, 11, 13 — single source of truth.++The `loadSession`, `resolveTimeRange`, `resolvePagination`, `renderSessionError`, `renderTimeRangeError` helpers are introduced once (Tasks 3, 4, 5, 8) and reused by every subsequent command. Plan 1's `renderAPIError` (which we reuse without changes) handles the API-error mapping side.++---++## End-of-plan checkpoint++After Task 14, you should be able to:++```bash+just build+./bin/traceway exceptions list --since 1h+./bin/traceway exceptions show <hash> --output json --fields exceptionHash,count+./bin/traceway logs query --service api --since 30m --output json | jq '.data[].body'+./bin/traceway endpoints list --since 1h+./bin/traceway metrics query --name http.request.duration --aggregation p95 --since 1h --output json+```++End state: a working observability CLI for the four use cases approved during brainstorming. Plan 3 builds on this for mutations (`exceptions archive`/`resolve`), the smoke-test harness, and the README.diff --git a/cli/docs/superpowers/specs/2026-05-13-traceway-cli-design.md b/cli/docs/superpowers/specs/2026-05-13-traceway-cli-design.mdnew file mode 100644index 00000000..5c847c59--- /dev/null+++ b/cli/docs/superpowers/specs/2026-05-13-traceway-cli-design.md@@ -0,0 +1,480 @@+# traceway-cli — Design++**Date:** 2026-05-13+**Status:** Approved+**Owner:** Fred Drake++## Goal++Build a Go CLI for querying and lightly mutating a [Traceway](https://github.com/tracewayapp/traceway) instance (self-hosted or cloud). Traceway is an OpenTelemetry-native observability platform (logs, metrics, distributed traces, exception tracking, session replay, alerting).++The primary consumer is **LLMs invoking the CLI from a shell tool** (e.g., Claude Code's Bash tool). Humans are a first-class secondary audience: interactive use should feel like `gh` — pretty tables, color when on a TTY, sane defaults — but every choice that benefits LLMs (structured JSON, stable exit codes, explicit error envelopes) wins ties.++A future MCP server is in scope but not in this project. The CLI's `pkg/client` package is structured so a thin MCP server can import it directly later — no shelling, no double-parsing.++## Why CLI first++- **Auth ergonomics.** Traceway uses user JWTs minted via `POST /api/login`. A CLI owns its own config dir and runs `traceway login` once, caching the JWT. An MCP server is spawned without a TTY by Claude Code, so it can't prompt for a password and would need a pre-seeded token in SOPS/keychain.+- **LLM-friendly today.** Claude Code already has a Bash tool; `traceway ... --output json | jq` covers most workflows. MCP's edge (strict tool schemas, streaming) doesn't matter much for query-shaped observability tools.+- **Doesn't block MCP.** Library-first design (`pkg/client`) means the MCP wrapper is a few hundred lines later.++## Why standalone (no upstream Go imports)++- The `tracewayapp/go-client` repo is an instrumentation SDK (sender side — services use it to emit telemetry), not an API query client. Not useful for us.+- Traceway's `backend/app/models` package is internal; they can rename `ExceptionGroup` to `Issue` tomorrow. The actual stable contract is JSON-over-HTTP.+- We define our own types in `pkg/client`, mirroring Traceway's JSON shapes. Hand-rolled once from reading their controllers.++## Audience priority (decided)++LLM-first, humans at home. Specifically:++- `--output` defaults to `json` when stdout is not a TTY, `table` when it is.+- Errors emit a stable JSON envelope on stderr in JSON mode; prose on TTY.+- Exit codes are stable, documented, and emitted in the JSON envelope so LLMs can branch without inspecting `$?`.+- Color when on a TTY; off otherwise.+- Pretty tables via `text/tabwriter`. No `lipgloss`/`charmbracelet` for v1.++## Scope (v1)++**In:**++- Login / logout / profile management+- Project list and "use" pointer (per-profile current project)+- Read endpoints for: exceptions (list, show), logs (query), endpoints (list), metrics (query)+- Mutations on exceptions: archive, resolve. Gated by interactive prompt or `--yes`/`TRACEWAY_ASSUME_YES`.++**Out (v1):**++- Distributed traces, session replay, AI traces. Add later when needed.+- Alerts, dashboards, admin endpoints.+- Anomaly detection logic. We surface raw recent data; the LLM judges anomalies.+- Output trimming via curated default field sets. The `--fields` flag lets the caller project; we don't curate per resource.++## Use cases this CLI is optimized for++1. **"What's broken in prod?"** — `traceway exceptions list --since 1h`, drill into one with `traceway exceptions show <hash>`.+2. **"Why is endpoint X slow?"** — `traceway endpoints list --since 1h` for p50/p95/p99 + error rates.+3. **"What did service Y log around time T?"** — `traceway logs query --service Y --severity error --from ... --to ...`.+4. **"Anomalies in the last hour?"** — broad metric queries; LLM interprets.++## Non-functional decisions++| Concern | Decision |+|---|---|+| CLI framework | Cobra + Viper |+| HTTP client | stdlib `net/http` with thin wrapper |+| Output rendering | `internal/output`: json, yaml, table (`text/tabwriter`) |+| Config storage | `$XDG_CONFIG_HOME/traceway/config.json` (fallback `~/.config/...`), `0700` dir + `0600` file, atomic writes |+| Credential model | Per-profile JWT + URL + username stored on disk. Password never persisted. |+| Token expiry | On 401: re-prompt password if interactive; otherwise hint-and-exit. Retry once. |+| Profiles | Multi-profile from day one. `--profile` defaults to `default`. |+| Projects | Per-profile current project (`traceway projects use <id>`). `--project` flag overrides per call. |+| Time ranges | `--since 1h` *or* `--from`/`--to` (RFC3339), mutually exclusive. Default `--since 1h`. |+| JSON shape | Pass-through Traceway response. `--fields a,b,c` projects to subset. |+| Pagination | `--page-size N` (default 50), `--page N` (default 0). One HTTP call per command. |+| Mutations | Confirmation gate: TTY prompt, or `--yes` / `TRACEWAY_ASSUME_YES=1`. |+| Errors | Stable error envelope (`error`, `message`, `hint`, `exit_code`) on stderr in JSON mode; prose on TTY. |+| Exit codes | 0 success, 1 generic, 2 usage, 3 connection, 4 auth, 5 not-found, 6 rate-limited, 7 server. |+| Logging | None for v1. CLI is short-lived; errors go to stderr; no persistent log file. |++## Architecture & layout++```+traceway-cli/+├── cmd/traceway/ # main entry, root command+│ ├── main.go # main(); panics → exit 1+│ ├── root.go # root *cobra.Command, global flags, output mode+│ ├── login.go # traceway login [--profile X] [--url ...]+│ ├── logout.go # traceway logout [--profile X]+│ ├── profiles.go # traceway profiles {list,use}+│ ├── projects.go # traceway projects {list,use}+│ ├── exceptions.go # exceptions {list,show,archive,resolve}+│ ├── logs.go # logs query+│ ├── endpoints.go # endpoints list+│ └── metrics.go # metrics query+│+├── pkg/client/ # reusable HTTP client + types (MCP-ready)+│ ├── client.go # Client struct, constructor, transport, auth header+│ ├── errors.go # typed errors+│ ├── pagination.go # Pagination struct+│ ├── time.go # TimeRange{Since, From, To} → RFC3339+│ ├── auth.go # Login(email, password) → JWT+│ ├── projects.go # ListProjects()+│ ├── exceptions.go # ListExceptions, GetException, ArchiveException, ResolveException+│ ├── logs.go # QueryLogs+│ ├── endpoints.go # ListEndpoints+│ └── metrics.go # QueryMetrics+│+├── internal/config/ # config file load/save+│ ├── config.go # Config struct + (*Config).Active(name)+│ └── paths.go # XDG_CONFIG_HOME resolution+│+├── internal/output/ # rendering+│ ├── format.go # Mode enum, TTY detection+│ ├── json.go # json.Marshal + --fields projection+│ ├── yaml.go # yaml.Marshal + --fields projection+│ ├── table.go # text/tabwriter; per-resource columns+│ └── error.go # error renderer (matches Mode)+│+├── internal/exitcode/ # stable exit codes+│ └── codes.go+│+├── test/smoke/ # build-tag-gated, real-Traceway tests+│+├── docs/ # this directory+├── go.mod+├── flake.nix # adds `just` to dev shell+├── justfile # task runner — see Tooling+└── .gitignore # add .go/ for the dev shell's GOPATH+```++**Boundaries:**++- `pkg/client` knows nothing about Cobra, Viper, terminals, or config files. Pure HTTP-and-types library.+- `internal/config` and `internal/output` are CLI-only — under `internal/` so they cannot leak into a future MCP server.+- `cmd/traceway/*.go` is thin glue: parse flags → load config → call `pkg/client` → hand result to `internal/output`. No business logic.+- One file per resource throughout.++## Components++### `pkg/client.Client`++```go+type Client struct {+ BaseURL string+ HTTPClient *http.Client // injectable for tests+ JWT string // mutable; refreshed on Login+ UserAgent string+}++type Option func(*Client)++func New(baseURL string, opts ...Option) *Client { ... }+func WithHTTPClient(c *http.Client) Option { ... }+func WithJWT(jwt string) Option { ... }++// auth+func (c *Client) Login(ctx context.Context, email, password string) (jwt string, err error)++// resources+func (c *Client) ListExceptions(ctx context.Context, projectID string, req ListExceptionsRequest) (*ListExceptionsResponse, error)+func (c *Client) GetException(ctx context.Context, projectID, hash string) (*Exception, error)+func (c *Client) ArchiveException(ctx context.Context, projectID, hash string) error+func (c *Client) ResolveException(ctx context.Context, projectID, hash string) error+func (c *Client) ListProjects(ctx context.Context) ([]Project, error)+func (c *Client) QueryLogs(ctx context.Context, projectID string, req QueryLogsRequest) (*QueryLogsResponse, error)+func (c *Client) ListEndpoints(ctx context.Context, projectID string, req ListEndpointsRequest) (*ListEndpointsResponse, error)+func (c *Client) QueryMetrics(ctx context.Context, projectID string, req QueryMetricsRequest) (*QueryMetricsResponse, error)+```++All HTTP calls funnel through one private `do()` method that:++- Adds `Authorization: Bearer <jwt>` (when JWT is set)+- Sets `Content-Type: application/json`+- JSON-encodes the body+- Decodes the response+- Maps HTTP status to typed errors++Typed errors in `errors.go`:++- `ErrUnauthorized` (401)+- `ErrForbidden` (403)+- `ErrNotFound` (404)+- `ErrRateLimited` (429)+- `*APIError{StatusCode, Body}` for everything else++Use `errors.Is` / `errors.As` from the CLI layer to map to exit codes.++`TimeRange` helper takes a relative `--since` *or* explicit `--from`/`--to`, normalizes to `fromDate`/`toDate` RFC3339 in the request body. Lives in `pkg/client/time.go` so MCP gets it too.++### `internal/config.Config`++```go+type Config struct {+ CurrentProfile string `json:"current_profile"`+ Profiles map[string]Profile `json:"profiles"`+}++type Profile struct {+ URL string `json:"url"`+ Username string `json:"username"`+ JWT string `json:"jwt"`+ CurrentProjectID string `json:"current_project_id,omitempty"`+}++func Load() (*Config, error)+func (c *Config) Save() error+func (c *Config) Active(name string) (*Profile, error) // resolves --profile > CurrentProfile > "default"+```++- Path: `$XDG_CONFIG_HOME/traceway/config.json`, fallback `~/.config/traceway/config.json`. Created `0700` dir + `0600` file.+- On load: warn (don't fail) if perms are loose.+- On save: atomic write (tempfile + rename in same dir).+- Viper is used only for env-var binding (`TRACEWAY_PROFILE`, `TRACEWAY_PROJECT`, `TRACEWAY_ASSUME_YES`). The credentials file does not round-trip through Viper.++### `cmd/traceway` flow per command (representative)++```go+// cmd/traceway/exceptions.go — list subcommand+func runListExceptions(cmd *cobra.Command, args []string) error {+ ctx := cmd.Context()++ profile, err := resolveProfile(cmd)+ if err != nil { return err }+ project, err := resolveProject(cmd, profile)+ if err != nil { return err }+ timeRange, err := resolveTimeRange(cmd)+ if err != nil { return err }++ c := client.New(profile.URL, client.WithJWT(profile.JWT))+ resp, err := c.ListExceptions(ctx, project, client.ListExceptionsRequest{+ TimeRange: timeRange,+ Pagination: client.Pagination{Page: page, PageSize: pageSize},+ Search: search,+ })+ if err != nil {+ return handleAPIError(err, profile) // 401 → re-prompt if TTY, else hint+ }++ return output.Render(cmd.OutOrStdout(), outputMode, fields, resp)+}+```++Each command is ~30–40 lines of glue.++## Data flow++### Flow A — `traceway login [--profile X] [--url ...]`++1. Resolve profile name (`--profile`, default `default`).+2. Load config; if profile exists, prompt with saved URL and username as defaults; otherwise prompt fresh (URL defaults to `--url` if set, else `https://cloud.traceway.com`).+3. Read password (no echo) via `golang.org/x/term.ReadPassword`. `--password-stdin` reads from stdin instead (LLM-friendly).+4. Call `client.Login(URL, email, password)` → JWT.+5. Save profile `{URL, Username, JWT, CurrentProjectID=""}`. If this is the only profile, set `CurrentProfile` to its name.+6. Print `Logged in as <user> on <url> (profile: <name>)`. Exit 0.++`--url` is honored on profile creation. On refresh of an existing profile, the saved URL wins unless `--url` is explicitly passed (then update + save).++### Flow B — Query (e.g., `traceway exceptions list --since 1h`)++1. Parse flags → resolve profile → resolve project → build `TimeRange`.+2. `client.ListExceptions(ctx, projectID, req)`.+3. On 200: render to stdout in selected output mode, applying `--fields` projection if set. Exit 0.+4. On non-2xx: typed error → `handleAPIError` → stderr envelope + exit code. stdout stays empty.++One HTTP call per command. The `pagination` block in the response tells the caller whether more pages exist.++### Flow C — Mutation (e.g., `traceway exceptions archive <hash>`)++1. Parse flags → resolve profile, project.+2. Confirmation gate:+ - TTY on stdin AND `--yes` not set AND `TRACEWAY_ASSUME_YES` not set → prompt `Archive exception <hash>? [y/N]`.+ - Non-interactive AND no `--yes` → exit 2 + `usage_error`. Fail fast; don't stall.+3. `client.ArchiveException(ctx, projectID, hash)`.+4. On success: print `Archived exception <hash>` (or `{"archived": "<hash>"}` in JSON mode). Exit 0.++LLMs always pass `--yes`; humans get the prompt.++### Flow D — Token expiry (401 from any call)++1. Any client call returns `ErrUnauthorized`.+2. `handleAPIError(err, profile)`:+ - TTY on stdin AND not `--output json` AND not `--no-prompt` → `Session expired. Re-login as <user>? [Y/n]`. Prompt password → `client.Login()` → save JWT → retry the original call **once**.+ - Otherwise → stderr envelope `{error: "token_expired", hint: "traceway login --profile X"}`, exit 4.+3. If retry fails: exit 4 with the same error. No infinite loops.++`--no-prompt` global flag lets humans opt into LLM-style behavior in a TTY.++## Error handling++### Exit codes (stable contract)++| Code | Meaning | Examples |+|------|---------|----------|+| 0 | Success | Command ran, returned data (even if empty `[]`) |+| 1 | Generic error | Bug, panic recovered, unknown failure |+| 2 | Usage error | Missing required flag, mutually exclusive flags, bad time format, mutation without `--yes` in non-TTY |+| 3 | Connection error | DNS, refused, TLS, timeout — anything before HTTP status |+| 4 | Auth error | 401, 403, expired token, missing profile, missing JWT |+| 5 | Not found | 404 |+| 6 | Rate limited | 429 |+| 7 | Server error | 5xx from Traceway |++Defined in `internal/exitcode/codes.go`. Documented in README. Emitted in the JSON error envelope.++### Error envelope (JSON mode)++```jsonc+// stderr, on failure+{+ "error": "token_expired",+ "message": "JWT expired or invalid",+ "hint": "traceway login --profile stormwind",+ "exit_code": 4+}+```++- stdout stays empty on failure. `| jq` pipelines never see partial garbage.+- `error` is a stable enum the LLM can branch on: `token_expired`, `not_authenticated`, `forbidden`, `no_profile`, `no_project`, `invalid_time_range`, `not_found`, `rate_limited`, `connection_failed`, `server_error`, `usage_error`, `api_error`, `internal`.+- `hint` is best-effort; absent for errors with no actionable next step.++### Error envelope (TTY / table mode)++```+Error: session expired+ Hint: traceway login --profile stormwind+```++`Error:` prefix in red when stderr is a TTY.++### `pkg/client` → CLI mapping++| `pkg/client` error | Exit | JSON `error` |+|---|---|---|+| `ErrUnauthorized` | 4 | `token_expired` (or `not_authenticated` if no JWT was sent) |+| `ErrForbidden` | 4 | `forbidden` |+| `ErrNotFound` | 5 | `not_found` |+| `ErrRateLimited` | 6 | `rate_limited` |+| `*APIError` 5xx | 7 | `server_error` |+| `*APIError` other | 1 | `api_error` |+| `*url.Error` (network) | 3 | `connection_failed` |+| Cobra usage errors | 2 | `usage_error` |+| Config load failure | 4 | `not_authenticated` |+| Mutation w/o `--yes` non-TTY | 2 | `usage_error` |++### Explicitly NOT done++- No retry/backoff inside the CLI for 5xx or rate-limiting. Caller decides.+- No partial-success accumulation. One command = one HTTP call = one outcome.++## Testing++### Layer 1 — Unit tests (`pkg/client/*_test.go`)++Cover: request encoding, response decoding, error mapping, time-range conversion, pagination shape.++Pattern: `httptest.NewServer` per test. Test server returns canned JSON or specific status codes. Verify request body, headers, and decoded response shape.++```go+func TestListExceptions_decodesResponse(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // assert path, method, auth header, body+ json.NewEncoder(w).Encode(canned)+ }))+ defer srv.Close()++ c := client.New(srv.URL, client.WithJWT("test-token"))+ resp, err := c.ListExceptions(ctx, "proj-1", req)+ // assert resp shape+}+```++Coverage target: ~80% on `pkg/client`.++### Layer 2 — CLI behavior tests (`cmd/traceway/*_test.go`)++Cover: flag parsing, profile/project resolution, output format selection, error rendering, exit codes, mutation gates.++Pattern: same `httptest` setup, but invoke commands via `cobra.Command.Execute()` with captured stdout/stderr/stdin. `t.TempDir()` as `XDG_CONFIG_HOME`.++Key cases:++- `--profile X` overrides `current_profile`+- `--project X` overrides profile's `current_project_id`+- Missing profile → exit 4 + `not_authenticated`+- Mutation in non-TTY without `--yes` → exit 2 + `usage_error`+- 401 in non-TTY → exit 4 + `token_expired`, no retry+- `--output json` produces valid JSON; `--fields a,b` projects correctly+- `--since 1h` and `--from`/`--to` both produce correct RFC3339+- `--since` + `--from` together → exit 2 + `usage_error`++### Layer 3 — Smoke tests against real Traceway (`test/smoke/*_test.go`)++Cover: that response shapes still match what stormwind actually returns. Early warning for upstream API drift.++Build-tag-gated (`//go:build smoke`). Reads `TRACEWAY_SMOKE_URL`, `TRACEWAY_SMOKE_USERNAME`, `TRACEWAY_SMOKE_PASSWORD`, `TRACEWAY_SMOKE_PROJECT_ID` from env. Skipped if any are absent. Hits each endpoint, decodes into our types, asserts no decode errors.++Run on demand or weekly cron in CI. Not blocking.++### Non-goals for v1++- No mock generators. `httptest` is enough.+- No fuzzing. Inputs are well-typed.+- No shell-level e2e tests (`bats`). Cobra-level tests cover the same ground.++## Tooling++`flake.nix` adds `just` to the dev shell. A `justfile` at repo root provides task aliases:++```just+default: test++test:+ gotestsum --format pkgname -- ./...++smoke-test:+ gotestsum --format pkgname -- -tags smoke ./test/smoke/...++lint:+ golangci-lint run++vulncheck:+ govulncheck ./...++# convenience: run everything that should pass before a commit+check: lint test vulncheck+```++`gotestsum` is preferred over bare `go test` for nicer output (clean per-package summary, end-of-run failure list, JUnit support if needed). It's already in the dev shell.++## Open questions to resolve during implementation++1. **Personal access tokens in Traceway UI.** Research said no, but it's source-only. If stormwind's UI exposes "API tokens," we should support paste-a-token as an alternative auth path. Check before implementing `login`.+2. **JWT TTL.** Read `backend/app/middleware/use_app_auth.middleware.go` upstream to learn the lifetime. Drives nothing in v1 (we always re-login on 401), but worth knowing.+3. **Session replay handling.** Out of scope for v1, but if added later: return the recording URL/ID, don't stream the (large) events.++## Build order++1. `go mod init github.com/tracewayapp/traceway/cli`. Add `.gitignore` for `.go/`.+2. `pkg/client`: constructor, `Login`, error types, time helper, `httptest` unit tests.+3. `internal/config`: load/save, `Active()`, tests.+4. `internal/output`: JSON renderer, error envelope, TTY detection.+5. `cmd/traceway`: root, `login`, `logout`, `profiles`. Smoke against stormwind.+6. `internal/output/table.go`. `cmd/traceway/projects.go`.+7. `cmd/traceway/exceptions.go` (`list`, `show`) + matching `pkg/client/exceptions.go` reads.+8. Add mutations: `exceptions {archive,resolve}`. Confirmation gate.+9. `cmd/traceway/logs.go`, `endpoints.go`, `metrics.go` — one slice at a time.+10. `test/smoke/`. `justfile`. README.++Get one full vertical slice working (`pkg/client` → `cmd/traceway` → real HTTP call → decoded result against stormwind) before broadening. The patterns from that first slice repeat 6–8 times.++## Reference — Traceway API surface++Self-hosted Traceway: single Go binary, Gin web framework, default port 80, all routes under `/api/...`. PostgreSQL (metadata) + ClickHouse (telemetry). No GraphQL, no OpenAPI spec.++| CLI verb | Endpoint | Notes |+|---|---|---|+| `traceway projects list` | `GET /api/projects` | Bootstrap; bare array, no pagination wrapper |+| `traceway exceptions list` | `POST /api/exception-stack-traces` | Grouped by hash |+| `traceway exceptions show <hash>` | `POST /api/exception-stack-traces/:hash` | Full stack + occurrences |+| `traceway exceptions archive <hash>` | (TBD — read controller) | v1 mutation |+| `traceway exceptions resolve <hash>` | (TBD — read controller) | v1 mutation |+| `traceway logs query` | `POST /api/logs` | Filter by service/severity/trace-id/attrs; >24h needs a selector |+| `traceway endpoints list` | `POST /api/endpoints` | p50/p95/p99, error rates per HTTP endpoint |+| `traceway metrics query` | `POST /api/metrics/query` | name + aggregation + tag filters + groupBy |++All request bodies JSON; all responses paginated `{data: [...], pagination: {...}}`. Time filters use `fromDate`/`toDate` as RFC3339. **Exception:** `GET /api/projects` returns a bare JSON array with no pagination wrapper.++Authoritative response types live in `backend/app/models/*.model.go` upstream — read them, don't import them. Use `gh api repos/tracewayapp/traceway/contents/<path>` to fetch files without cloning.++Key files to read when implementing each subcommand:++- Routes: `backend/app/controllers/routes.go`+- Auth: `backend/app/controllers/auth.controller.go`, `backend/app/middleware/use_app_auth.middleware.go`+- Exceptions: `backend/app/controllers/exception_stack_trace.controller.go` + `backend/app/models/exception_stack_trace.model.go`+- Logs: `backend/app/controllers/log.controller.go` + `backend/app/models/log_record.model.go`+- Endpoints: `backend/app/controllers/endpoint.controller.go` + `backend/app/models/endpoint.model.go`+- Metrics: `backend/app/controllers/metric_query.controller.go` + `backend/app/models/metric_record.model.go`+- Projects: `backend/app/controllers/project.controller.go` + `backend/app/models/project.model.go`+- Config: `backend/app/config/config.go`+- Entry: `backend/cmd/run.go`diff --git a/cli/flake.lock b/cli/flake.locknew file mode 100644index 00000000..503ff2a9--- /dev/null+++ b/cli/flake.lock@@ -0,0 +1,61 @@+{+ "nodes": {+ "flake-utils": {+ "inputs": {+ "systems": "systems"+ },+ "locked": {+ "lastModified": 1731533236,+ "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",+ "owner": "numtide",+ "repo": "flake-utils",+ "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",+ "type": "github"+ },+ "original": {+ "owner": "numtide",+ "repo": "flake-utils",+ "type": "github"+ }+ },+ "nixpkgs": {+ "locked": {+ "lastModified": 1779357205,+ "narHash": "sha256-cCO8aTqss5x9Ky8GWkpY0Hy5fyTZEbtifSUV8QjSzic=",+ "owner": "NixOS",+ "repo": "nixpkgs",+ "rev": "f83fc3c307e74bc5fd5adb7eb6b8b13ffd2a36e1",+ "type": "github"+ },+ "original": {+ "owner": "NixOS",+ "ref": "nixos-unstable",+ "repo": "nixpkgs",+ "type": "github"+ }+ },+ "root": {+ "inputs": {+ "flake-utils": "flake-utils",+ "nixpkgs": "nixpkgs"+ }+ },+ "systems": {+ "locked": {+ "lastModified": 1681028828,+ "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",+ "owner": "nix-systems",+ "repo": "default",+ "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",+ "type": "github"+ },+ "original": {+ "owner": "nix-systems",+ "repo": "default",+ "type": "github"+ }+ }+ },+ "root": "root",+ "version": 7+}diff --git a/cli/flake.nix b/cli/flake.nixnew file mode 100644index 00000000..4a342668--- /dev/null+++ b/cli/flake.nix@@ -0,0 +1,53 @@+{+ description = "traceway-cli — command-line client for Traceway observability";++ inputs = {+ nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";+ flake-utils.url = "github:numtide/flake-utils";+ };++ outputs =+ { nixpkgs, flake-utils, ... }:+ flake-utils.lib.eachDefaultSystem (+ system:+ let+ pkgs = import nixpkgs { inherit system; };+ in+ {+ devShells.default = pkgs.mkShell {+ packages = with pkgs; [+ go+ gopls+ gotools+ delve+ golangci-lint+ gofumpt+ govulncheck+ gomodifytags+ impl+ gotestsum++ gh+ git+ jq+ just+ ];++ shellHook = ''+ export GOPATH="$PWD/.go"+ export GOCACHE="$PWD/.go/cache"+ export GOBIN="$PWD/.go/bin"+ export PATH="$GOBIN:$PATH"++ echo "traceway-cli dev shell"+ echo " go $(go version | cut -d' ' -f3)"+ echo " golangci-lint $(golangci-lint version --short 2>/dev/null || echo unknown)"+ echo " dlv $(dlv version 2>/dev/null | grep Version | awk '{print $2}')"+ echo " gh $(gh --version | head -1 | cut -d' ' -f3)"+ '';+ };++ formatter = pkgs.nixfmt;+ }+ );+}diff --git a/cli/go.mod b/cli/go.modnew file mode 100644index 00000000..a5f02651--- /dev/null+++ b/cli/go.mod@@ -0,0 +1,16 @@+module github.com/tracewayapp/traceway/cli++go 1.26.2++require (+ github.com/google/uuid v1.6.0+ github.com/spf13/cobra v1.10.2+ golang.org/x/term v0.43.0+ gopkg.in/yaml.v3 v3.0.1+)++require (+ github.com/inconshreveable/mousetrap v1.1.0 // indirect+ github.com/spf13/pflag v1.0.9 // indirect+ golang.org/x/sys v0.44.0 // indirect+)diff --git a/cli/go.sum b/cli/go.sumnew file mode 100644index 00000000..e969e3e0--- /dev/null+++ b/cli/go.sum@@ -0,0 +1,19 @@+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=+github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=+golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=+golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=+golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/cli/internal/config/config.go b/cli/internal/config/config.gonew file mode 100644index 00000000..1b2da560--- /dev/null+++ b/cli/internal/config/config.go@@ -0,0 +1,159 @@+package config++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"++ "github.com/tracewayapp/traceway/cli/internal/state"+)++// Config is the on-disk declarative configuration file. It contains only+// stable fields suitable for dotfile management (url, username per profile).+// Runtime fields (JWT, current project, active profile pointer) live in State.+type Config struct {+ Profiles map[string]Profile `json:"profiles"`+}++// Profile holds connection parameters for a single Traceway instance.+type Profile struct {+ URL string `json:"url"`+ Username string `json:"username"`+}++// legacyProfile is used only for migration detection.+type legacyProfile struct {+ URL string `json:"url"`+ Username string `json:"username"`+ JWT string `json:"jwt"`+ CurrentProjectID string `json:"current_project_id,omitempty"`+}++// legacyConfig is used only for migration detection.+type legacyConfig struct {+ CurrentProfile string `json:"current_profile"`+ Profiles map[string]legacyProfile `json:"profiles"`+}++// Load reads the config file from disk. A missing file yields an empty Config+// (not an error) — the caller treats absence of credentials as an auth error+// only when an actual command needs them.+//+// If the on-disk file is in the old shape (has current_profile at top level or+// any profile has jwt / current_project_id), Load migrates those fields into+// the state file automatically and rewrites config.json without them.+func Load() (*Config, error) {+ path, err := configPath()+ if err != nil {+ return nil, err+ }+ data, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return &Config{Profiles: map[string]Profile{}}, nil+ }+ if err != nil {+ return nil, fmt.Errorf("reading config: %w", err)+ }++ // Parse into the legacy shape first to detect migration need.+ var legacy legacyConfig+ if err := json.Unmarshal(data, &legacy); err != nil {+ return nil, fmt.Errorf("parsing config %s: %w", path, err)+ }+ if legacy.Profiles == nil {+ legacy.Profiles = map[string]legacyProfile{}+ }++ needsMigration := legacy.CurrentProfile != ""+ if !needsMigration {+ for _, lp := range legacy.Profiles {+ if lp.JWT != "" || lp.CurrentProjectID != "" {+ needsMigration = true+ break+ }+ }+ }++ if needsMigration {+ // Build a State from the legacy fields.+ st := &state.State{+ CurrentProfile: legacy.CurrentProfile,+ Profiles: map[string]state.ProfileState{},+ }+ for name, lp := range legacy.Profiles {+ if lp.JWT != "" || lp.CurrentProjectID != "" {+ st.Profiles[name] = state.ProfileState{+ JWT: lp.JWT,+ CurrentProjectID: lp.CurrentProjectID,+ }+ }+ }+ if err := st.Save(); err != nil {+ return nil, fmt.Errorf("migrating state: %w", err)+ }++ // Build a clean Config with only stable fields.+ cfg := &Config{Profiles: map[string]Profile{}}+ for name, lp := range legacy.Profiles {+ cfg.Profiles[name] = Profile{URL: lp.URL, Username: lp.Username}+ }+ if err := cfg.Save(); err != nil {+ return nil, fmt.Errorf("saving migrated config: %w", err)+ }+ return cfg, nil+ }++ // No migration needed — parse normally into the clean shape.+ var cfg Config+ if err := json.Unmarshal(data, &cfg); err != nil {+ return nil, fmt.Errorf("parsing config %s: %w", path, err)+ }+ if cfg.Profiles == nil {+ cfg.Profiles = map[string]Profile{}+ }+ return &cfg, nil+}++// Save atomically writes the config to disk. Creates parent dirs (0700) and the+// file (0600). Atomicity is achieved by writing to a tempfile in the same+// directory and renaming over the destination.+func (c *Config) Save() error {+ path, err := configPath()+ if err != nil {+ return err+ }+ dir := filepath.Dir(path)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return fmt.Errorf("creating config dir: %w", err)+ }++ data, err := json.MarshalIndent(c, "", " ")+ if err != nil {+ return fmt.Errorf("marshalling config: %w", err)+ }++ tmp, err := os.CreateTemp(dir, ".config.json.*")+ if err != nil {+ return fmt.Errorf("creating temp file: %w", err)+ }+ tmpName := tmp.Name()+ defer os.Remove(tmpName) // no-op if rename succeeded++ if err := tmp.Chmod(0o600); err != nil {+ tmp.Close()+ return fmt.Errorf("chmod temp: %w", err)+ }+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return fmt.Errorf("writing temp: %w", err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("closing temp: %w", err)+ }+ if err := os.Rename(tmpName, path); err != nil {+ return fmt.Errorf("renaming into place: %w", err)+ }+ return nil+}diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.gonew file mode 100644index 00000000..ab24df3b--- /dev/null+++ b/cli/internal/config/config_test.go@@ -0,0 +1,252 @@+package config++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+)++func TestLoad_missingFile_returnsEmpty(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ if cfg == nil {+ t.Fatal("Load() returned nil cfg")+ }+ if len(cfg.Profiles) != 0 {+ t.Errorf("expected empty Profiles, got %v", cfg.Profiles)+ }+}++func TestLoad_existingFile_readsJSON(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ if err := os.MkdirAll(filepath.Join(dir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }+ body := `{+ "profiles": {+ "stormwind": {+ "url": "https://traceway.stormwind.local",+ "username": "[email protected]"+ }+ }+ }`+ if err := os.WriteFile(filepath.Join(dir, "traceway", "config.json"), []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ p, ok := cfg.Profiles["stormwind"]+ if !ok {+ t.Fatal("stormwind profile not loaded")+ }+ if p.URL != "https://traceway.stormwind.local" {+ t.Errorf("URL = %q", p.URL)+ }+ if p.Username != "[email protected]" {+ t.Errorf("Username = %q", p.Username)+ }+}++func TestLoad_corruptFile_returnsError(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ if err := os.MkdirAll(filepath.Join(dir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "traceway", "config.json"), []byte("not json"), 0o600); err != nil {+ t.Fatal(err)+ }++ if _, err := Load(); err == nil {+ t.Fatal("expected Load() to fail on corrupt JSON")+ }+}++func TestSave_writesAtomicallyWith0600(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ cfg := &Config{+ Profiles: map[string]Profile{+ "default": {+ URL: "https://cloud.traceway.com",+ Username: "[email protected]",+ },+ },+ }+ if err := cfg.Save(); err != nil {+ t.Fatalf("Save() error: %v", err)+ }++ path := filepath.Join(dir, "traceway", "config.json")+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if perm := info.Mode().Perm(); perm != 0o600 {+ t.Errorf("file perm = %o, want 0600", perm)+ }++ dirInfo, err := os.Stat(filepath.Join(dir, "traceway"))+ if err != nil {+ t.Fatalf("stat dir: %v", err)+ }+ if perm := dirInfo.Mode().Perm(); perm != 0o700 {+ t.Errorf("dir perm = %o, want 0700", perm)+ }+}++func TestSave_overwritesExisting(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", dir)+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ first := &Config{+ Profiles: map[string]Profile{"a": {URL: "https://a"}},+ }+ if err := first.Save(); err != nil {+ t.Fatalf("first Save: %v", err)+ }++ second := &Config{+ Profiles: map[string]Profile{"b": {URL: "https://b"}},+ }+ if err := second.Save(); err != nil {+ t.Fatalf("second Save: %v", err)+ }++ loaded, err := Load()+ if err != nil {+ t.Fatalf("Load: %v", err)+ }+ if _, ok := loaded.Profiles["a"]; ok {+ t.Error("profile 'a' should have been overwritten")+ }+ if _, ok := loaded.Profiles["b"]; !ok {+ t.Error("profile 'b' should exist after second Save")+ }+}++func TestSave_thenLoad_roundTrips(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ want := &Config{+ Profiles: map[string]Profile{+ "stormwind": {+ URL: "https://traceway.stormwind.local",+ Username: "[email protected]",+ },+ },+ }+ if err := want.Save(); err != nil {+ t.Fatal(err)+ }+ got, err := Load()+ if err != nil {+ t.Fatal(err)+ }+ if got.Profiles["stormwind"] != want.Profiles["stormwind"] {+ t.Errorf("Profile mismatch: got %+v want %+v", got.Profiles["stormwind"], want.Profiles["stormwind"])+ }+}++func TestLoad_migratesLegacyShape(t *testing.T) {+ cfgDir := t.TempDir()+ stateDir := t.TempDir()+ t.Setenv("XDG_CONFIG_HOME", cfgDir)+ t.Setenv("XDG_STATE_HOME", stateDir)++ if err := os.MkdirAll(filepath.Join(cfgDir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }++ // Write a config.json in the OLD shape (has current_profile, jwt, current_project_id).+ legacy := `{+ "current_profile": "stormwind",+ "profiles": {+ "stormwind": {+ "url": "https://traceway.stormwind.local",+ "username": "[email protected]",+ "jwt": "abc.def.ghi",+ "current_project_id": "proj-1"+ }+ }+ }`+ if err := os.WriteFile(filepath.Join(cfgDir, "traceway", "config.json"), []byte(legacy), 0o600); err != nil {+ t.Fatal(err)+ }++ cfg, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }++ // Config should have only url+username; no jwt/current_project_id/current_profile.+ p, ok := cfg.Profiles["stormwind"]+ if !ok {+ t.Fatal("stormwind profile not present after migration")+ }+ if p.URL != "https://traceway.stormwind.local" {+ t.Errorf("URL = %q", p.URL)+ }+ if p.Username != "[email protected]" {+ t.Errorf("Username = %q", p.Username)+ }++ // Verify the on-disk config.json has no legacy fields.+ rawCfg, err := os.ReadFile(filepath.Join(cfgDir, "traceway", "config.json"))+ if err != nil {+ t.Fatal(err)+ }+ var raw map[string]any+ if err := json.Unmarshal(rawCfg, &raw); err != nil {+ t.Fatal(err)+ }+ if _, has := raw["current_profile"]; has {+ t.Error("config.json still has current_profile after migration")+ }+ profiles, _ := raw["profiles"].(map[string]any)+ sw, _ := profiles["stormwind"].(map[string]any)+ if _, has := sw["jwt"]; has {+ t.Error("config.json still has jwt after migration")+ }+ if _, has := sw["current_project_id"]; has {+ t.Error("config.json still has current_project_id after migration")+ }++ // Verify state.json was created with the moved fields.+ stateFile := filepath.Join(stateDir, "traceway", "state.json")+ rawState, err := os.ReadFile(stateFile)+ if err != nil {+ t.Fatalf("state.json not created: %v", err)+ }+ var rawSt map[string]any+ if err := json.Unmarshal(rawState, &rawSt); err != nil {+ t.Fatal(err)+ }+ if rawSt["current_profile"] != "stormwind" {+ t.Errorf("state current_profile = %v, want stormwind", rawSt["current_profile"])+ }+ stateProfiles, _ := rawSt["profiles"].(map[string]any)+ swState, _ := stateProfiles["stormwind"].(map[string]any)+ if swState["jwt"] != "abc.def.ghi" {+ t.Errorf("state jwt = %v, want abc.def.ghi", swState["jwt"])+ }+ if swState["current_project_id"] != "proj-1" {+ t.Errorf("state current_project_id = %v, want proj-1", swState["current_project_id"])+ }+}diff --git a/cli/internal/config/paths.go b/cli/internal/config/paths.gonew file mode 100644index 00000000..bac9b635--- /dev/null+++ b/cli/internal/config/paths.go@@ -0,0 +1,20 @@+package config++import (+ "errors"+ "os"+ "path/filepath"+)++// 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+ }+ 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+}diff --git a/cli/internal/config/paths_test.go b/cli/internal/config/paths_test.gonew file mode 100644index 00000000..a6fc0882--- /dev/null+++ b/cli/internal/config/paths_test.go@@ -0,0 +1,43 @@+package config++import (+ "path/filepath"+ "testing"+)++func TestConfigPath_xdgSet(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", "/tmp/xdg")+ t.Setenv("HOME", "/tmp/home")++ got, err := configPath()+ if err != nil {+ t.Fatalf("configPath() error: %v", err)+ }+ want := filepath.Join("/tmp/xdg", "traceway", "config.json")+ if got != want {+ t.Errorf("configPath() = %q, want %q", got, want)+ }+}++func TestConfigPath_xdgUnset(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", "")+ t.Setenv("HOME", "/tmp/home")++ got, err := configPath()+ if err != nil {+ t.Fatalf("configPath() error: %v", err)+ }+ want := filepath.Join("/tmp/home", ".config", "traceway", "config.json")+ if got != want {+ t.Errorf("configPath() = %q, want %q", got, want)+ }+}++func TestConfigPath_neither(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", "")+ t.Setenv("HOME", "")++ if _, err := configPath(); err == nil {+ t.Fatal("expected error when both XDG_CONFIG_HOME and HOME are empty")+ }+}diff --git a/cli/internal/exitcode/codes.go b/cli/internal/exitcode/codes.gonew file mode 100644index 00000000..f05d26af--- /dev/null+++ b/cli/internal/exitcode/codes.go@@ -0,0 +1,14 @@+// Package exitcode defines the stable exit codes emitted by the traceway CLI.+// LLMs and scripts may branch on these values; do not renumber.+package exitcode++const (+ Success = 0+ Generic = 1+ Usage = 2+ Connection = 3+ Auth = 4+ NotFound = 5+ RateLimited = 6+ Server = 7+)diff --git a/cli/internal/exitcode/codes_test.go b/cli/internal/exitcode/codes_test.gonew file mode 100644index 00000000..1f5178a3--- /dev/null+++ b/cli/internal/exitcode/codes_test.go@@ -0,0 +1,25 @@+package exitcode++import "testing"++func TestCodes_areStable(t *testing.T) {+ cases := []struct {+ name string+ got int+ want int+ }{+ {"Success", Success, 0},+ {"Generic", Generic, 1},+ {"Usage", Usage, 2},+ {"Connection", Connection, 3},+ {"Auth", Auth, 4},+ {"NotFound", NotFound, 5},+ {"RateLimited", RateLimited, 6},+ {"Server", Server, 7},+ }+ for _, c := range cases {+ if c.got != c.want {+ t.Errorf("%s = %d, want %d", c.name, c.got, c.want)+ }+ }+}diff --git a/cli/internal/output/error.go b/cli/internal/output/error.gonew file mode 100644index 00000000..27dbb9ef--- /dev/null+++ b/cli/internal/output/error.go@@ -0,0 +1,34 @@+package output++import (+ "encoding/json"+ "fmt"+ "io"+)++// ErrorEnvelope is the stable error contract written to stderr on any failure.+// Code is a snake_case stable identifier; LLMs may branch on it.+type ErrorEnvelope struct {+ Code string `json:"error"`+ Message string `json:"message"`+ Hint string `json:"hint,omitempty"`+ ExitCode int `json:"exit_code"`+}++// RenderError writes the envelope to w. Compact JSON for ModeJSON/ModeYAML;+// prose for ModeTable. (YAML mode uses JSON for errors — easier for callers+// to parse and matches gh's behavior for machine-formatted errors.)+func RenderError(w io.Writer, mode Mode, env ErrorEnvelope) error {+ if mode == ModeJSON || mode == ModeYAML {+ return json.NewEncoder(w).Encode(env)+ }+ if _, err := fmt.Fprintf(w, "Error: %s\n", env.Message); err != nil {+ return err+ }+ if env.Hint != "" {+ if _, err := fmt.Fprintf(w, " Hint: %s\n", env.Hint); err != nil {+ return err+ }+ }+ return nil+}diff --git a/cli/internal/output/error_test.go b/cli/internal/output/error_test.gonew file mode 100644index 00000000..9cd0a62d--- /dev/null+++ b/cli/internal/output/error_test.go@@ -0,0 +1,85 @@+package output++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"+)++func TestRenderError_jsonShape(t *testing.T) {+ var buf bytes.Buffer+ err := RenderError(&buf, ModeJSON, ErrorEnvelope{+ Code: "token_expired",+ Message: "JWT expired or invalid",+ Hint: "traceway login --profile stormwind",+ ExitCode: 4,+ })+ if err != nil {+ t.Fatal(err)+ }++ var got map[string]any+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("invalid JSON: %v\nout: %s", err, buf.String())+ }+ if got["error"] != "token_expired" {+ t.Errorf("error = %v", got["error"])+ }+ if got["message"] != "JWT expired or invalid" {+ t.Errorf("message = %v", got["message"])+ }+ if got["hint"] != "traceway login --profile stormwind" {+ t.Errorf("hint = %v", got["hint"])+ }+ if int(got["exit_code"].(float64)) != 4 {+ t.Errorf("exit_code = %v", got["exit_code"])+ }+}++func TestRenderError_jsonOmitsEmptyHint(t *testing.T) {+ var buf bytes.Buffer+ _ = RenderError(&buf, ModeJSON, ErrorEnvelope{+ Code: "internal",+ Message: "boom",+ ExitCode: 1,+ })+ var got map[string]any+ _ = json.Unmarshal(buf.Bytes(), &got)+ if _, ok := got["hint"]; ok {+ t.Errorf("hint should be omitted when empty, got: %v", got)+ }+}++func TestRenderError_proseHasErrorPrefix(t *testing.T) {+ var buf bytes.Buffer+ _ = RenderError(&buf, ModeTable, ErrorEnvelope{+ Code: "token_expired",+ Message: "session expired",+ Hint: "traceway login --profile stormwind",+ ExitCode: 4,+ })+ out := buf.String()+ if !strings.HasPrefix(out, "Error:") {+ t.Errorf("prose form should start with 'Error:', got:\n%s", out)+ }+ if !strings.Contains(out, "session expired") {+ t.Errorf("missing message, got:\n%s", out)+ }+ if !strings.Contains(out, "Hint:") {+ t.Errorf("missing hint line, got:\n%s", out)+ }+}++func TestRenderError_proseOmitsHintLineWhenAbsent(t *testing.T) {+ var buf bytes.Buffer+ _ = RenderError(&buf, ModeTable, ErrorEnvelope{+ Code: "internal",+ Message: "boom",+ ExitCode: 1,+ })+ out := buf.String()+ if strings.Contains(out, "Hint:") {+ t.Errorf("Hint line should be omitted, got:\n%s", out)+ }+}diff --git a/cli/internal/output/format.go b/cli/internal/output/format.gonew file mode 100644index 00000000..b46ee19a--- /dev/null+++ b/cli/internal/output/format.go@@ -0,0 +1,76 @@+// Package output renders command results as JSON, YAML, or tables, plus the+// stable error envelope.+package output++import (+ "fmt"+ "os"+ "strings"++ "golang.org/x/term"+)++// Mode controls how Render formats its output.+type Mode int++const (+ ModeJSON Mode = iota+ ModeYAML+ ModeTable+)++func (m Mode) String() string {+ switch m {+ case ModeJSON:+ return "json"+ case ModeYAML:+ return "yaml"+ case ModeTable:+ return "table"+ default:+ return "unknown"+ }+}++// ParseMode converts the user-facing flag value to a Mode.+func ParseMode(s string) (Mode, error) {+ switch strings.ToLower(s) {+ case "json":+ return ModeJSON, nil+ case "yaml":+ return ModeYAML, nil+ case "table":+ return ModeTable, nil+ default:+ return 0, fmt.Errorf("invalid output mode %q (valid: json, yaml, table)", s)+ }+}++// ResolveMode picks an effective Mode. An explicit user value wins; otherwise+// default to table on TTY and json on non-TTY.+//+// The error returned by ParseMode for invalid explicit values is intentionally+// suppressed here — the caller should validate via ParseMode at flag-parse time.+func ResolveMode(explicit string, isTTY bool) Mode {+ if explicit != "" {+ if m, err := ParseMode(explicit); err == nil {+ return m+ }+ }+ if isTTY {+ return ModeTable+ }+ return ModeJSON+}++// IsTerminal reports whether the given file descriptor is a terminal.+// Wraps golang.org/x/term so callers don't import it directly.+func IsTerminal(fd uintptr) bool {+ return term.IsTerminal(int(fd))+}++// StdoutIsTerminal is a convenience shortcut.+func StdoutIsTerminal() bool { return IsTerminal(os.Stdout.Fd()) }++// StderrIsTerminal is a convenience shortcut.+func StderrIsTerminal() bool { return IsTerminal(os.Stderr.Fd()) }diff --git a/cli/internal/output/format_test.go b/cli/internal/output/format_test.gonew file mode 100644index 00000000..9c7753bf--- /dev/null+++ b/cli/internal/output/format_test.go@@ -0,0 +1,50 @@+package output++import (+ "testing"+)++func TestParseMode_validValues(t *testing.T) {+ cases := map[string]Mode{+ "json": ModeJSON,+ "JSON": ModeJSON,+ "yaml": ModeYAML,+ "table": ModeTable,+ }+ for in, want := range cases {+ got, err := ParseMode(in)+ if err != nil {+ t.Errorf("ParseMode(%q) error: %v", in, err)+ continue+ }+ if got != want {+ t.Errorf("ParseMode(%q) = %v, want %v", in, got, want)+ }+ }+}++func TestParseMode_invalid(t *testing.T) {+ if _, err := ParseMode("xml"); err == nil {+ t.Error("expected error for invalid mode")+ }+}++func TestResolveMode_explicitWins(t *testing.T) {+ got := ResolveMode("json", false)+ if got != ModeJSON {+ t.Errorf("got %v", got)+ }+ got = ResolveMode("table", false)+ if got != ModeTable {+ t.Errorf("got %v", got)+ }+}++func TestResolveMode_emptyDefaultsByTTY(t *testing.T) {+ if got := ResolveMode("", true); got != ModeTable {+ t.Errorf("TTY default = %v, want ModeTable", got)+ }+ if got := ResolveMode("", false); got != ModeJSON {+ t.Errorf("non-TTY default = %v, want ModeJSON", got)+ }+}diff --git a/cli/internal/output/json.go b/cli/internal/output/json.gonew file mode 100644index 00000000..4987c0a0--- /dev/null+++ b/cli/internal/output/json.go@@ -0,0 +1,98 @@+package output++import (+ "encoding/json"+ "io"+ "strings"+)++// ParseFieldsFlag splits "a, b, c" → []string{"a", "b", "c"}. Empty input → nil.+func ParseFieldsFlag(s string) []string {+ if strings.TrimSpace(s) == "" {+ return nil+ }+ parts := strings.Split(s, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ p = strings.TrimSpace(p)+ if p != "" {+ out = append(out, p)+ }+ }+ if len(out) == 0 {+ return nil+ }+ return out+}++// RenderJSON marshals v as compact JSON to w (one record per line, no indent).+// If fields is non-nil, projects each item of a top-level "data" array+// (Traceway's wrapper shape) — or the top-level object itself if it has no+// "data" key — to just the named fields. "pagination" and other top-level+// wrapper keys pass through unchanged.+//+// Compact output is intentional: it minimizes tokens for LLM consumers and+// matches what real APIs return. Humans wanting pretty output can pipe to+// `jq` (or use `--output table`).+func RenderJSON(w io.Writer, v any, fields []string) error {+ if fields == nil {+ return json.NewEncoder(w).Encode(v)+ }++ // Round-trip through JSON to a generic any so we can project by string keys.+ raw, err := json.Marshal(v)+ if err != nil {+ return err+ }+ var generic any+ if err := json.Unmarshal(raw, &generic); err != nil {+ return err+ }+ projected := projectFields(generic, fields)+ return json.NewEncoder(w).Encode(projected)+}++// projectFields keeps only the named keys, with awareness of Traceway's+// {data: [...], pagination: {...}} wrapper. See RenderJSON for the contract.+func projectFields(v any, fields []string) any {+ set := make(map[string]bool, len(fields))+ for _, f := range fields {+ set[f] = true+ }++ if m, ok := v.(map[string]any); ok {+ if data, hasData := m["data"]; hasData {+ if arr, ok := data.([]any); ok {+ out := make([]any, len(arr))+ for i, item := range arr {+ out[i] = projectMap(item, set)+ }+ m["data"] = out+ return m+ }+ }+ return projectMap(v, set)+ }+ if arr, ok := v.([]any); ok {+ out := make([]any, len(arr))+ for i, item := range arr {+ out[i] = projectMap(item, set)+ }+ return out+ }+ return v+}++func projectMap(v any, fields map[string]bool) any {+ m, ok := v.(map[string]any)+ if !ok {+ return v+ }+ out := make(map[string]any, len(fields))+ for k, val := range m {+ if fields[k] {+ out[k] = val+ }+ }+ return out+}diff --git a/cli/internal/output/json_test.go b/cli/internal/output/json_test.gonew file mode 100644index 00000000..e461bb06--- /dev/null+++ b/cli/internal/output/json_test.go@@ -0,0 +1,107 @@+package output++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"+)++type project struct {+ ID string `json:"id"`+ Name string `json:"name"`+ URL string `json:"url"`+}++type wrappedResp struct {+ Data []project `json:"data"`+ Pagination struct {+ Total int `json:"total"`+ } `json:"pagination"`+}++func TestRenderJSON_passThroughWhenNoFields(t *testing.T) {+ in := wrappedResp{+ Data: []project{{ID: "p1", Name: "alpha", URL: "https://a"}},+ }+ in.Pagination.Total = 1++ var buf bytes.Buffer+ if err := RenderJSON(&buf, in, nil); err != nil {+ t.Fatal(err)+ }++ var got wrappedResp+ if err := json.Unmarshal(buf.Bytes(), &got); err != nil {+ t.Fatalf("invalid JSON output: %v\noutput: %s", err, buf.String())+ }+ if got.Data[0].URL != "https://a" {+ t.Errorf("URL was stripped; pass-through expected")+ }+}++func TestRenderJSON_projectsFieldsInWrappedData(t *testing.T) {+ in := wrappedResp{+ Data: []project{+ {ID: "p1", Name: "alpha", URL: "https://a"},+ {ID: "p2", Name: "beta", URL: "https://b"},+ },+ }++ var buf bytes.Buffer+ if err := RenderJSON(&buf, in, []string{"id", "name"}); err != nil {+ t.Fatal(err)+ }+ out := buf.String()++ if !strings.Contains(out, `"id"`) || !strings.Contains(out, `"name"`) {+ t.Errorf("expected id and name in projection, got: %s", out)+ }+ if strings.Contains(out, `"url"`) {+ t.Errorf("url should have been projected away, got: %s", out)+ }+ // Pagination stays at the top level even when fields are projected.+ if !strings.Contains(out, `"pagination"`) {+ t.Errorf("pagination should pass through, got: %s", out)+ }+}++func TestRenderJSON_projectsTopLevelObject(t *testing.T) {+ in := project{ID: "p1", Name: "alpha", URL: "https://a"}++ var buf bytes.Buffer+ if err := RenderJSON(&buf, in, []string{"id"}); err != nil {+ t.Fatal(err)+ }+ out := buf.String()+ if !strings.Contains(out, `"id"`) {+ t.Errorf("expected id, got: %s", out)+ }+ if strings.Contains(out, `"name"`) {+ t.Errorf("name should have been projected away, got: %s", out)+ }+}++func TestParseFieldsFlag(t *testing.T) {+ cases := []struct {+ in string+ want []string+ }{+ {"", nil},+ {"a", []string{"a"}},+ {"a,b,c", []string{"a", "b", "c"}},+ {" a , b ", []string{"a", "b"}},+ }+ for _, c := range cases {+ got := ParseFieldsFlag(c.in)+ if len(got) != len(c.want) {+ t.Errorf("ParseFieldsFlag(%q) = %v, want %v", c.in, got, c.want)+ continue+ }+ for i := range got {+ if got[i] != c.want[i] {+ t.Errorf("ParseFieldsFlag(%q)[%d] = %q, want %q", c.in, i, got[i], c.want[i])+ }+ }+ }+}diff --git a/cli/internal/output/table.go b/cli/internal/output/table.gonew file mode 100644index 00000000..69d289c9--- /dev/null+++ b/cli/internal/output/table.go@@ -0,0 +1,18 @@+package output++import (+ "io"+ "text/tabwriter"+)++// NewTabWriter returns a *text/tabwriter.Writer configured for traceway's+// table output style: left-aligned columns separated by two spaces. Callers+// must call Flush() after writing all rows.+//+// tw := output.NewTabWriter(w)+// fmt.Fprintln(tw, "ID\tNAME")+// fmt.Fprintf(tw, "%s\t%s\n", id, name)+// tw.Flush()+func NewTabWriter(w io.Writer) *tabwriter.Writer {+ return tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)+}diff --git a/cli/internal/output/yaml.go b/cli/internal/output/yaml.gonew file mode 100644index 00000000..9d61969f--- /dev/null+++ b/cli/internal/output/yaml.go@@ -0,0 +1,30 @@+package output++import (+ "encoding/json"+ "io"++ "gopkg.in/yaml.v3"+)++// RenderYAML marshals v as YAML to w, applying the same field projection as+// RenderJSON when fields is non-nil. Internally we round-trip through JSON so+// that callers' types only need json struct tags (no need for parallel yaml+// tags on every struct in pkg/client).+func RenderYAML(w io.Writer, v any, fields []string) error {+ raw, err := json.Marshal(v)+ if err != nil {+ return err+ }+ var generic any+ if err := json.Unmarshal(raw, &generic); err != nil {+ return err+ }+ if fields != nil {+ generic = projectFields(generic, fields)+ }+ enc := yaml.NewEncoder(w)+ enc.SetIndent(2)+ defer enc.Close()+ return enc.Encode(generic)+}diff --git a/cli/internal/output/yaml_test.go b/cli/internal/output/yaml_test.gonew file mode 100644index 00000000..dffb506b--- /dev/null+++ b/cli/internal/output/yaml_test.go@@ -0,0 +1,42 @@+package output++import (+ "bytes"+ "strings"+ "testing"+)++func TestRenderYAML_passThrough(t *testing.T) {+ in := project{ID: "p1", Name: "alpha", URL: "https://a"}++ var buf bytes.Buffer+ if err := RenderYAML(&buf, in, nil); err != nil {+ t.Fatal(err)+ }+ out := buf.String()+ if !strings.Contains(out, "id: p1") {+ t.Errorf("expected 'id: p1' in YAML, got:\n%s", out)+ }+ if !strings.Contains(out, "name: alpha") {+ t.Errorf("expected 'name: alpha' in YAML, got:\n%s", out)+ }+ if !strings.Contains(out, "url: https://a") {+ t.Errorf("expected 'url: https://a' in YAML, got:\n%s", out)+ }+}++func TestRenderYAML_projectsFields(t *testing.T) {+ in := project{ID: "p1", Name: "alpha", URL: "https://a"}++ var buf bytes.Buffer+ if err := RenderYAML(&buf, in, []string{"id"}); err != nil {+ t.Fatal(err)+ }+ out := buf.String()+ if !strings.Contains(out, "id: p1") {+ t.Errorf("expected id in projection, got:\n%s", out)+ }+ if strings.Contains(out, "name:") {+ t.Errorf("name should be projected away, got:\n%s", out)+ }+}diff --git a/cli/internal/state/paths.go b/cli/internal/state/paths.gonew file mode 100644index 00000000..2495af14--- /dev/null+++ b/cli/internal/state/paths.go@@ -0,0 +1,20 @@+package state++import (+ "errors"+ "os"+ "path/filepath"+)++// 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+ }+ 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+}diff --git a/cli/internal/state/state.go b/cli/internal/state/state.gonew file mode 100644index 00000000..feb8871d--- /dev/null+++ b/cli/internal/state/state.go@@ -0,0 +1,108 @@+// Package state manages runtime data that changes frequently and must not be+// managed declaratively: JWT tokens, current project selection, and the active+// profile pointer. It mirrors the XDG Base Directory Specification by storing+// data under XDG_STATE_HOME (default: $HOME/.local/state).+package state++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+)++// State is the on-disk runtime state file.+type State struct {+ CurrentProfile string `json:"current_profile"`+ Profiles map[string]ProfileState `json:"profiles"`+}++// ProfileState holds runtime state for a single Traceway profile.+type ProfileState struct {+ JWT string `json:"jwt"`+ CurrentProjectID string `json:"current_project_id,omitempty"`+}++// Load reads the state file from disk. A missing file yields an empty State+// (not an error) — the caller treats absence of credentials as an auth error+// only when an actual command needs them.+func Load() (*State, error) {+ path, err := statePath()+ if err != nil {+ return nil, err+ }+ data, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return &State{Profiles: map[string]ProfileState{}}, nil+ }+ if err != nil {+ return nil, fmt.Errorf("reading state: %w", err)+ }+ var st State+ if err := json.Unmarshal(data, &st); err != nil {+ return nil, fmt.Errorf("parsing state %s: %w", path, err)+ }+ if st.Profiles == nil {+ st.Profiles = map[string]ProfileState{}+ }+ return &st, nil+}++// Save atomically writes the state to disk. Creates parent dirs (0700) and the+// file (0600). Atomicity is achieved by writing to a tempfile in the same+// directory and renaming over the destination.+func (s *State) Save() error {+ path, err := statePath()+ if err != nil {+ return err+ }+ dir := filepath.Dir(path)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return fmt.Errorf("creating state dir: %w", err)+ }++ data, err := json.MarshalIndent(s, "", " ")+ if err != nil {+ return fmt.Errorf("marshalling state: %w", err)+ }++ tmp, err := os.CreateTemp(dir, ".state.json.*")+ if err != nil {+ return fmt.Errorf("creating temp file: %w", err)+ }+ tmpName := tmp.Name()+ defer os.Remove(tmpName) // no-op if rename succeeded++ if err := tmp.Chmod(0o600); err != nil {+ tmp.Close()+ return fmt.Errorf("chmod temp: %w", err)+ }+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return fmt.Errorf("writing temp: %w", err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("closing temp: %w", err)+ }+ if err := os.Rename(tmpName, path); err != nil {+ return fmt.Errorf("renaming into place: %w", err)+ }+ return nil+}++// Active resolves the effective profile name by precedence:+//+// explicit name > s.CurrentProfile > "default"+//+// It returns the resolved name only. Callers should index into s.Profiles+// themselves; the profile may not exist in state yet (e.g., before first login).+func (s *State) Active(name string) string {+ if name != "" {+ return name+ }+ if s.CurrentProfile != "" {+ return s.CurrentProfile+ }+ return "default"+}diff --git a/cli/internal/state/state_test.go b/cli/internal/state/state_test.gonew file mode 100644index 00000000..5c59e97c--- /dev/null+++ b/cli/internal/state/state_test.go@@ -0,0 +1,207 @@+package state++import (+ "os"+ "path/filepath"+ "testing"+)++func TestStatePath_xdgSet(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", "/tmp/xdgstate")+ t.Setenv("HOME", "/tmp/home")++ got, err := statePath()+ if err != nil {+ t.Fatalf("statePath() error: %v", err)+ }+ want := filepath.Join("/tmp/xdgstate", "traceway", "state.json")+ if got != want {+ t.Errorf("statePath() = %q, want %q", got, want)+ }+}++func TestStatePath_xdgUnset(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", "")+ t.Setenv("HOME", "/tmp/home")++ got, err := statePath()+ if err != nil {+ t.Fatalf("statePath() error: %v", err)+ }+ want := filepath.Join("/tmp/home", ".local", "state", "traceway", "state.json")+ if got != want {+ t.Errorf("statePath() = %q, want %q", got, want)+ }+}++func TestStatePath_neither(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", "")+ t.Setenv("HOME", "")++ if _, err := statePath(); err == nil {+ t.Fatal("expected error when both XDG_STATE_HOME and HOME are empty")+ }+}++func TestLoad_missingFile_returnsEmpty(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ st, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ if st == nil {+ t.Fatal("Load() returned nil state")+ }+ if len(st.Profiles) != 0 {+ t.Errorf("expected empty Profiles, got %v", st.Profiles)+ }+ if st.CurrentProfile != "" {+ t.Errorf("expected empty CurrentProfile, got %q", st.CurrentProfile)+ }+}++func TestLoad_existingFile_readsJSON(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_STATE_HOME", dir)+ if err := os.MkdirAll(filepath.Join(dir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }+ body := `{+ "current_profile": "stormwind",+ "profiles": {+ "stormwind": {+ "jwt": "abc.def.ghi",+ "current_project_id": "proj-1"+ }+ }+ }`+ if err := os.WriteFile(filepath.Join(dir, "traceway", "state.json"), []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }++ st, err := Load()+ if err != nil {+ t.Fatalf("Load() error: %v", err)+ }+ if st.CurrentProfile != "stormwind" {+ t.Errorf("CurrentProfile = %q, want %q", st.CurrentProfile, "stormwind")+ }+ p, ok := st.Profiles["stormwind"]+ if !ok {+ t.Fatal("stormwind profile not loaded")+ }+ if p.JWT != "abc.def.ghi" {+ t.Errorf("JWT = %q", p.JWT)+ }+ if p.CurrentProjectID != "proj-1" {+ t.Errorf("CurrentProjectID = %q", p.CurrentProjectID)+ }+}++func TestLoad_corruptFile_returnsError(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_STATE_HOME", dir)+ if err := os.MkdirAll(filepath.Join(dir, "traceway"), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "traceway", "state.json"), []byte("not json"), 0o600); err != nil {+ t.Fatal(err)+ }++ if _, err := Load(); err == nil {+ t.Fatal("expected Load() to fail on corrupt JSON")+ }+}++func TestSave_writesAtomicallyWith0600(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("XDG_STATE_HOME", dir)++ st := &State{+ CurrentProfile: "default",+ Profiles: map[string]ProfileState{+ "default": {JWT: "tok", CurrentProjectID: "proj-1"},+ },+ }+ if err := st.Save(); err != nil {+ t.Fatalf("Save() error: %v", err)+ }++ path := filepath.Join(dir, "traceway", "state.json")+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if perm := info.Mode().Perm(); perm != 0o600 {+ t.Errorf("file perm = %o, want 0600", perm)+ }++ dirInfo, err := os.Stat(filepath.Join(dir, "traceway"))+ if err != nil {+ t.Fatalf("stat dir: %v", err)+ }+ if perm := dirInfo.Mode().Perm(); perm != 0o700 {+ t.Errorf("dir perm = %o, want 0700", perm)+ }+}++func TestSave_thenLoad_roundTrips(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ want := &State{+ CurrentProfile: "stormwind",+ Profiles: map[string]ProfileState{+ "stormwind": {JWT: "tok", CurrentProjectID: "proj-1"},+ },+ }+ if err := want.Save(); err != nil {+ t.Fatal(err)+ }+ got, err := Load()+ if err != nil {+ t.Fatal(err)+ }+ if got.CurrentProfile != want.CurrentProfile {+ t.Errorf("CurrentProfile mismatch: got %q want %q", got.CurrentProfile, want.CurrentProfile)+ }+ if got.Profiles["stormwind"] != want.Profiles["stormwind"] {+ t.Errorf("Profile mismatch: got %+v want %+v", got.Profiles["stormwind"], want.Profiles["stormwind"])+ }+}++func TestActive_explicitName(t *testing.T) {+ st := &State{+ CurrentProfile: "stormwind",+ Profiles: map[string]ProfileState{+ "stormwind": {JWT: "a"},+ "cloud": {JWT: "b"},+ },+ }+ if got := st.Active("cloud"); got != "cloud" {+ t.Errorf("Active(cloud) = %q, want cloud", got)+ }+}++func TestActive_emptyName_usesCurrentProfile(t *testing.T) {+ st := &State{+ CurrentProfile: "stormwind",+ Profiles: map[string]ProfileState{+ "stormwind": {JWT: "a"},+ },+ }+ if got := st.Active(""); got != "stormwind" {+ t.Errorf("Active(\"\") = %q, want stormwind", got)+ }+}++func TestActive_emptyName_emptyCurrent_usesDefault(t *testing.T) {+ st := &State{+ Profiles: map[string]ProfileState{+ "default": {JWT: "d"},+ },+ }+ if got := st.Active(""); got != "default" {+ t.Errorf("Active(\"\") = %q, want default", got)+ }+}diff --git a/cli/justfile b/cli/justfilenew file mode 100644index 00000000..2617682e--- /dev/null+++ b/cli/justfile@@ -0,0 +1,19 @@+default: test++build:+ go build -o bin/traceway ./cmd/traceway++test:+ gotestsum --format pkgname -- ./...++smoke-test:+ gotestsum --format pkgname -- -tags smoke ./test/smoke/...++lint:+ golangci-lint run++vulncheck:+ govulncheck ./...++# Run everything that should pass before a commit+check: lint test vulncheckdiff --git a/cli/pkg/client/auth.go b/cli/pkg/client/auth.gonew file mode 100644index 00000000..590c2ccb--- /dev/null+++ b/cli/pkg/client/auth.go@@ -0,0 +1,30 @@+package client++import (+ "context"+ "errors"+ "net/http"+)++type loginRequest struct {+ Email string `json:"email"`+ Password string `json:"password"`+}++type loginResponse struct {+ Token string `json:"token"`+}++// 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 {+ return "", err+ }+ if resp.Token == "" {+ return "", errors.New("login response did not include a token")+ }+ return resp.Token, nil+}diff --git a/cli/pkg/client/auth_test.go b/cli/pkg/client/auth_test.gonew file mode 100644index 00000000..3aa3ff0f--- /dev/null+++ b/cli/pkg/client/auth_test.go@@ -0,0 +1,53 @@+package client++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestLogin_success(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/login" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Errorf("method = %q", r.Method)+ }+ var req map[string]string+ _ = json.NewDecoder(r.Body).Decode(&req)+ if req["email"] != "[email protected]" {+ t.Errorf("email = %q", req["email"])+ }+ if req["password"] != "hunter2" {+ t.Errorf("password = %q", req["password"])+ }+ _, _ = w.Write([]byte(`{"token": "jwt.value.here"}`))+ }))+ defer srv.Close()++ c := New(srv.URL)+ jwt, err := c.Login(context.Background(), "[email protected]", "hunter2")+ if err != nil {+ t.Fatalf("Login: %v", err)+ }+ if jwt != "jwt.value.here" {+ t.Errorf("jwt = %q", jwt)+ }+}++func TestLogin_invalidCredentials_returnsUnauthorized(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(401)+ }))+ defer srv.Close()++ c := New(srv.URL)+ _, err := c.Login(context.Background(), "x", "y")+ if !errors.Is(err, ErrUnauthorized) {+ t.Errorf("got %v, want ErrUnauthorized", err)+ }+}diff --git a/cli/pkg/client/client.go b/cli/pkg/client/client.gonew file mode 100644index 00000000..c65cacc0--- /dev/null+++ b/cli/pkg/client/client.go@@ -0,0 +1,120 @@+package client++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++// Client talks to a Traceway HTTP API.+type Client struct {+ BaseURL string+ HTTPClient *http.Client+ JWT string+ UserAgent string+}++// Option mutates a Client during construction.+type Option func(*Client)++// New returns a Client with sane defaults. The baseURL is normalized by+// stripping trailing slashes; do() prepends "/api/..." paths.+func New(baseURL string, opts ...Option) *Client {+ c := &Client{+ BaseURL: strings.TrimRight(baseURL, "/"),+ HTTPClient: &http.Client{Timeout: 30 * time.Second},+ UserAgent: "traceway-cli/0.1",+ }+ for _, opt := range opts {+ opt(c)+ }+ return c+}++// WithHTTPClient injects a custom *http.Client (useful for tests).+func WithHTTPClient(h *http.Client) Option {+ return func(c *Client) { c.HTTPClient = h }+}++// WithJWT sets the bearer token to send on every request.+func WithJWT(jwt string) Option {+ return func(c *Client) { c.JWT = jwt }+}++// do is the internal HTTP transport. It JSON-encodes body (if non-nil),+// JSON-decodes the response into out (if non-nil), and maps non-2xx status+// codes to typed errors.+func (c *Client) do(ctx context.Context, method, path string, body, out any) error {+ var reqBody io.Reader+ if body != nil {+ buf, err := json.Marshal(body)+ if err != nil {+ return fmt.Errorf("encoding request body: %w", err)+ }+ reqBody = bytes.NewReader(buf)+ }++ req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, reqBody)+ if err != nil {+ return fmt.Errorf("building request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", c.UserAgent)+ if c.JWT != "" {+ req.Header.Set("Authorization", "Bearer "+c.JWT)+ }++ resp, err := c.HTTPClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 200 && resp.StatusCode < 300 {+ if out == nil {+ return nil+ }+ if err := json.NewDecoder(resp.Body).Decode(out); err != nil {+ return fmt.Errorf("decoding response: %w", err)+ }+ return nil+ }++ switch resp.StatusCode {+ case http.StatusUnauthorized:+ return ErrUnauthorized+ case http.StatusForbidden:+ return ErrForbidden+ case http.StatusNotFound:+ return ErrNotFound+ case http.StatusTooManyRequests:+ return ErrRateLimited+ }+ respBody, _ := io.ReadAll(resp.Body)+ return &APIError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(respBody))}+}++// jsonMarshalNoHTMLEscape is a json.Marshal that doesn't escape <, >, & in+// strings. Used by request types with custom MarshalJSON to keep --output+// json human-readable. The default json.Marshal would otherwise turn+// "p < 5" into "p < 5" in the wire body.+func jsonMarshalNoHTMLEscape(v any) ([]byte, error) {+ var buf bytes.Buffer+ enc := json.NewEncoder(&buf)+ enc.SetEscapeHTML(false)+ if err := enc.Encode(v); err != nil {+ return nil, err+ }+ // json.Encoder appends a trailing newline; trim it so callers can compose.+ out := buf.Bytes()+ if len(out) > 0 && out[len(out)-1] == '\n' {+ out = out[:len(out)-1]+ }+ return out, nil+}diff --git a/cli/pkg/client/client_test.go b/cli/pkg/client/client_test.gonew file mode 100644index 00000000..f0ea83e3--- /dev/null+++ b/cli/pkg/client/client_test.go@@ -0,0 +1,131 @@+package client++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestNew_setsDefaults(t *testing.T) {+ c := New("https://example.com")+ if c.BaseURL != "https://example.com" {+ t.Errorf("BaseURL = %q", c.BaseURL)+ }+ if c.HTTPClient == nil {+ t.Error("HTTPClient should default to a non-nil client")+ }+ if c.UserAgent == "" {+ t.Error("UserAgent should have a default value")+ }+}++func TestWithJWT_setsJWT(t *testing.T) {+ c := New("https://example.com", WithJWT("tok"))+ if c.JWT != "tok" {+ t.Errorf("JWT = %q", c.JWT)+ }+}++func TestDo_setsHeadersAndDecodes(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.Header.Get("Content-Type"); got != "application/json" {+ t.Errorf("Content-Type = %q", got)+ }+ if got := r.Header.Get("Authorization"); got != "Bearer tok" {+ t.Errorf("Authorization = %q", got)+ }+ if got := r.Header.Get("User-Agent"); !strings.HasPrefix(got, "traceway-cli") {+ t.Errorf("User-Agent = %q", got)+ }+ var body map[string]string+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["foo"] != "bar" {+ t.Errorf("body.foo = %q", body["foo"])+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"ok": true}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ var resp struct {+ OK bool `json:"ok"`+ }+ err := c.do(context.Background(), http.MethodPost, "/api/test", map[string]string{"foo": "bar"}, &resp)+ if err != nil {+ t.Fatalf("do(): %v", err)+ }+ if !resp.OK {+ t.Error("expected resp.OK = true")+ }+}++func TestDo_omitsAuthHeaderWhenJWTEmpty(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.Header.Get("Authorization"); got != "" {+ t.Errorf("expected no Authorization header, got %q", got)+ }+ w.Write([]byte(`{}`))+ }))+ defer srv.Close()++ c := New(srv.URL)+ var resp struct{}+ if err := c.do(context.Background(), http.MethodPost, "/api/x", nil, &resp); err != nil {+ t.Fatal(err)+ }+}++func TestDo_mapsStatusCodes(t *testing.T) {+ cases := []struct {+ status int+ want error+ }{+ {401, ErrUnauthorized},+ {403, ErrForbidden},+ {404, ErrNotFound},+ {429, ErrRateLimited},+ }+ for _, c := range cases {+ c := c+ t.Run(http.StatusText(c.status), func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(c.status)+ }))+ defer srv.Close()++ cli := New(srv.URL)+ var resp struct{}+ err := cli.do(context.Background(), http.MethodPost, "/api/x", nil, &resp)+ if !errors.Is(err, c.want) {+ t.Errorf("got %v, want errors.Is(_, %v)", err, c.want)+ }+ })+ }+}++func TestDo_returnsAPIErrorForOtherStatus(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(500)+ _, _ = w.Write([]byte("boom"))+ }))+ defer srv.Close()++ cli := New(srv.URL)+ var resp struct{}+ err := cli.do(context.Background(), http.MethodPost, "/api/x", nil, &resp)+ var apiErr *APIError+ if !errors.As(err, &apiErr) {+ t.Fatalf("expected APIError, got %T: %v", err, err)+ }+ if apiErr.StatusCode != 500 {+ t.Errorf("StatusCode = %d", apiErr.StatusCode)+ }+ if apiErr.Body != "boom" {+ t.Errorf("Body = %q", apiErr.Body)+ }+}diff --git a/cli/pkg/client/endpoints.go b/cli/pkg/client/endpoints.gonew file mode 100644index 00000000..9dcc8c36--- /dev/null+++ b/cli/pkg/client/endpoints.go@@ -0,0 +1,60 @@+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"+)++// EndpointStats matches the upstream models.EndpointStats. Durations are+// time.Duration values which Go marshals/unmarshals as nanoseconds.+type EndpointStats struct {+ Endpoint string `json:"endpoint"`+ Count uint64 `json:"count"`+ P50Duration time.Duration `json:"p50Duration"`+ P95Duration time.Duration `json:"p95Duration"`+ P99Duration time.Duration `json:"p99Duration"`+ AvgDuration time.Duration `json:"avgDuration"`+ LastSeen time.Time `json:"lastSeen"`+ Impact float64 `json:"impact"`+ ImpactReason string `json:"impactReason"`+}++// ListEndpointsRequest is the body for POST /api/endpoints/grouped.+type ListEndpointsRequest struct {+ TimeRange TimeRange `json:"-"`+ Pagination PaginationParams `json:"pagination"`+ OrderBy string `json:"orderBy,omitempty"`+ SortDirection string `json:"sortDirection,omitempty"`+ Search string `json:"search,omitempty"`+}++// MarshalJSON expands TimeRange into top-level fromDate/toDate.+func (r ListEndpointsRequest) MarshalJSON() ([]byte, error) {+ type alias ListEndpointsRequest+ wire := struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ alias+ }{r.TimeRange.From, r.TimeRange.To, alias(r)}+ return jsonMarshalNoHTMLEscape(wire)+}++// ListEndpointsResponse mirrors PaginatedResponse[EndpointStats].+type ListEndpointsResponse struct {+ Data []EndpointStats `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// ListEndpoints returns p50/p95/p99 stats grouped by endpoint route. We use+// the /grouped variant rather than the bare /endpoints (which returns one row+// per request).+func (c *Client) ListEndpoints(ctx context.Context, projectID string, req ListEndpointsRequest) (*ListEndpointsResponse, error) {+ path := "/api/endpoints/grouped?projectId=" + url.QueryEscape(projectID)+ var resp ListEndpointsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}diff --git a/cli/pkg/client/endpoints_test.go b/cli/pkg/client/endpoints_test.gonew file mode 100644index 00000000..a8be64c6--- /dev/null+++ b/cli/pkg/client/endpoints_test.go@@ -0,0 +1,58 @@+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestListEndpoints_callsGroupedRoute(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/endpoints/grouped" {+ t.Errorf("path = %q (want grouped)", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["fromDate"] == nil || body["toDate"] == nil {+ t.Errorf("body missing fromDate/toDate: %v", body)+ }+ // p50/p95/p99 are time.Duration in upstream — JSON encoded as nanoseconds (int64)+ _, _ = w.Write([]byte(`{+ "data":[+ {"endpoint":"GET /api/projects","count":120,"p50Duration":50000000,"p95Duration":150000000,"p99Duration":300000000,"avgDuration":80000000,"lastSeen":"2026-05-13T12:00:00Z","impact":0.42,"impactReason":"high p95"}+ ],+ "pagination":{"page":1,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListEndpoints(context.Background(), "proj-1", ListEndpointsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ Pagination: PaginationParams{Page: 1, PageSize: 50},+ })+ if err != nil {+ t.Fatalf("ListEndpoints: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("got %d endpoints", len(resp.Data))+ }+ if resp.Data[0].Endpoint != "GET /api/projects" {+ t.Errorf("Endpoint = %q", resp.Data[0].Endpoint)+ }+ if resp.Data[0].Count != 120 {+ t.Errorf("Count = %d", resp.Data[0].Count)+ }+ if resp.Data[0].P50Duration != 50*time.Millisecond {+ t.Errorf("P50Duration = %v, want 50ms", resp.Data[0].P50Duration)+ }+ if resp.Data[0].Impact != 0.42 {+ t.Errorf("Impact = %v", resp.Data[0].Impact)+ }+}diff --git a/cli/pkg/client/errors.go b/cli/pkg/client/errors.gonew file mode 100644index 00000000..02ff2463--- /dev/null+++ b/cli/pkg/client/errors.go@@ -0,0 +1,32 @@+// Package client is the HTTP client and types for talking to a Traceway instance.+//+// This package has no dependencies on Cobra, Viper, or any CLI machinery so+// that a future MCP server can import it directly.+package client++import (+ "errors"+ "fmt"+)++// Sentinel errors returned by client methods. Use errors.Is to test.+var (+ ErrUnauthorized = errors.New("unauthorized (401)")+ ErrForbidden = errors.New("forbidden (403)")+ ErrNotFound = errors.New("not found (404)")+ ErrRateLimited = errors.New("rate limited (429)")+)++// APIError is returned for any non-2xx response that isn't covered by a sentinel.+// Inspect StatusCode and Body for diagnostics.+type APIError struct {+ StatusCode int+ Body string+}++func (e *APIError) Error() string {+ if e.Body == "" {+ return fmt.Sprintf("traceway API error: status %d", e.StatusCode)+ }+ return fmt.Sprintf("traceway API error: status %d: %s", e.StatusCode, e.Body)+}diff --git a/cli/pkg/client/errors_test.go b/cli/pkg/client/errors_test.gonew file mode 100644index 00000000..4b64b06c--- /dev/null+++ b/cli/pkg/client/errors_test.go@@ -0,0 +1,35 @@+package client++import (+ "errors"+ "testing"+)++func TestAPIError_Error(t *testing.T) {+ e := &APIError{StatusCode: 500, Body: "boom"}+ got := e.Error()+ if got == "" {+ t.Fatal("Error() returned empty string")+ }+}++func TestSentinelErrors_areDistinct(t *testing.T) {+ all := []error{ErrUnauthorized, ErrForbidden, ErrNotFound, ErrRateLimited}+ for i, a := range all {+ for j, b := range all {+ if i == j {+ continue+ }+ if errors.Is(a, b) {+ t.Errorf("errors.Is(%v, %v) = true; expected distinct", a, b)+ }+ }+ }+}++func TestAPIError_doesNotMatchSentinels(t *testing.T) {+ apiErr := &APIError{StatusCode: 418}+ if errors.Is(apiErr, ErrUnauthorized) {+ t.Error("APIError(418) should not match ErrUnauthorized")+ }+}diff --git a/cli/pkg/client/exceptions.go b/cli/pkg/client/exceptions.gonew file mode 100644index 00000000..a59989f0--- /dev/null+++ b/cli/pkg/client/exceptions.go@@ -0,0 +1,131 @@+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"++ "github.com/google/uuid"+)++// ExceptionGroup matches Traceway's models.ExceptionGroup. Hourly trends are+// only present on list responses; on the detail endpoint they're absent.+type ExceptionGroup struct {+ ExceptionHash string `json:"exceptionHash"`+ StackTrace string `json:"stackTrace"`+ FirstSeen time.Time `json:"firstSeen"`+ LastSeen time.Time `json:"lastSeen"`+ Count uint64 `json:"count"`+ HourlyTrend []ExceptionTrendPoint `json:"hourlyTrend,omitempty"`+}++// ExceptionTrendPoint is one entry in an exception's hourly trend.+type ExceptionTrendPoint struct {+ Timestamp time.Time `json:"timestamp"`+ Count uint64 `json:"count"`+}++// ListExceptionsRequest is the body for POST /api/exception-stack-traces.+// projectId travels as a URL query param (handled by ListExceptions), not in+// the body — the upstream RequireProjectAccess middleware reads it via+// c.Query("projectId").+type ListExceptionsRequest struct {+ TimeRange TimeRange `json:"-"` // serialized as fromDate/toDate via MarshalJSON+ Pagination PaginationParams `json:"pagination"`+ OrderBy string `json:"orderBy,omitempty"`+ Search string `json:"search,omitempty"`+ SearchType string `json:"searchType,omitempty"`+ IncludeArchived bool `json:"includeArchived,omitempty"`+}++// MarshalJSON expands TimeRange.From / TimeRange.To into top-level fromDate /+// toDate so the wire shape matches Traceway's ExceptionSearchRequest.+func (r ListExceptionsRequest) MarshalJSON() ([]byte, error) {+ type alias ListExceptionsRequest+ wire := struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ alias+ }{+ FromDate: r.TimeRange.From,+ ToDate: r.TimeRange.To,+ alias: alias(r),+ }+ return jsonMarshalNoHTMLEscape(wire)+}++// ListExceptionsResponse mirrors the upstream PaginatedResponse[ExceptionGroup].+type ListExceptionsResponse struct {+ Data []ExceptionGroup `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// ListExceptions returns one page of grouped exceptions for the given project.+func (c *Client) ListExceptions(ctx context.Context, projectID string, req ListExceptionsRequest) (*ListExceptionsResponse, error) {+ path := "/api/exception-stack-traces?projectId=" + url.QueryEscape(projectID)+ var resp ListExceptionsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// ExceptionStackTrace is one occurrence of a grouped exception.+type ExceptionStackTrace struct {+ Id uuid.UUID `json:"id"`+ ExceptionHash string `json:"exceptionHash"`+ StackTrace string `json:"stackTrace"`+ RecordedAt time.Time `json:"recordedAt"`+ TraceId *uuid.UUID `json:"traceId,omitempty"`+ TraceType string `json:"traceType,omitempty"`+ ServerName string `json:"serverName,omitempty"`+ AppVersion string `json:"appVersion,omitempty"`+ IsMessage bool `json:"isMessage,omitempty"`+ Attributes map[string]string `json:"attributes,omitempty"`+ DistributedTraceId *uuid.UUID `json:"distributedTraceId,omitempty"`+ SessionId *uuid.UUID `json:"sessionId,omitempty"`+}++// getExceptionRequest is the body for POST /api/exception-stack-traces/:hash.+type getExceptionRequest struct {+ Pagination PaginationParams `json:"pagination"`+}++// GetExceptionResponse is the upstream ExceptionDetailResponse minus the+// session-recording blob (we don't expose recordings in v1).+type GetExceptionResponse struct {+ Group *ExceptionGroup `json:"group"`+ Occurrences []ExceptionStackTrace `json:"occurrences"`+ Pagination Pagination `json:"pagination"`+}++// GetException returns the group + paginated occurrences for the given hash.+func (c *Client) GetException(ctx context.Context, projectID, hash string, page PaginationParams) (*GetExceptionResponse, error) {+ path := "/api/exception-stack-traces/" + url.PathEscape(hash) + "?projectId=" + url.QueryEscape(projectID)+ var resp GetExceptionResponse+ if err := c.do(ctx, http.MethodPost, path, getExceptionRequest{Pagination: page}, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}++// archiveRequest is the body for POST /api/exception-stack-traces/archive+// and .../unarchive. Same shape for both routes.+type archiveRequest struct {+ Hashes []string `json:"hashes"`+}++// ArchiveExceptions marks the given exception hashes as archived for the+// project. The upstream response is just {"success": true}; on success this+// returns nil and the caller can report the count back to the user.+func (c *Client) ArchiveExceptions(ctx context.Context, projectID string, hashes []string) error {+ path := "/api/exception-stack-traces/archive?projectId=" + url.QueryEscape(projectID)+ return c.do(ctx, http.MethodPost, path, archiveRequest{Hashes: hashes}, nil)+}++// UnarchiveExceptions reverses ArchiveExceptions for the given hashes.+func (c *Client) UnarchiveExceptions(ctx context.Context, projectID string, hashes []string) error {+ path := "/api/exception-stack-traces/unarchive?projectId=" + url.QueryEscape(projectID)+ return c.do(ctx, http.MethodPost, path, archiveRequest{Hashes: hashes}, nil)+}diff --git a/cli/pkg/client/exceptions_test.go b/cli/pkg/client/exceptions_test.gonew file mode 100644index 00000000..02d4a957--- /dev/null+++ b/cli/pkg/client/exceptions_test.go@@ -0,0 +1,226 @@+package client++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestListExceptions_sendsProjectIdAsQueryParam(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId query = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["fromDate"] == nil || body["toDate"] == nil {+ t.Errorf("body missing fromDate/toDate: %v", body)+ }+ _, _ = w.Write([]byte(`{+ "data": [+ {"exceptionHash":"h1","stackTrace":"...","count":42,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"}+ ],+ "pagination":{"page":1,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListExceptions(context.Background(), "proj-1", ListExceptionsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ Pagination: PaginationParams{Page: 1, PageSize: 50},+ })+ if err != nil {+ t.Fatalf("ListExceptions: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("got %d exceptions, want 1", len(resp.Data))+ }+ if resp.Data[0].ExceptionHash != "h1" {+ t.Errorf("ExceptionHash = %q", resp.Data[0].ExceptionHash)+ }+ if resp.Data[0].Count != 42 {+ t.Errorf("Count = %d", resp.Data[0].Count)+ }+ if resp.Pagination.Total != 1 {+ t.Errorf("Pagination.Total = %d", resp.Pagination.Total)+ }+}++func TestListExceptions_emptyResults(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"data":[],"pagination":{"page":1,"pageSize":50,"total":0,"totalPages":0}}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.ListExceptions(context.Background(), "proj-1", ListExceptionsRequest{})+ if err != nil {+ t.Fatal(err)+ }+ if len(resp.Data) != 0 {+ t.Errorf("expected empty Data")+ }+}++func TestListExceptions_passesSearchParameters(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["search"] != "NullPointer" {+ t.Errorf("search = %v", body["search"])+ }+ if body["searchType"] != "text" {+ t.Errorf("searchType = %v", body["searchType"])+ }+ if body["includeArchived"] != true {+ t.Errorf("includeArchived = %v", body["includeArchived"])+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.ListExceptions(context.Background(), "proj-1", ListExceptionsRequest{+ Search: "NullPointer",+ SearchType: "text",+ IncludeArchived: true,+ })+ if err != nil {+ t.Fatal(err)+ }+}++func TestGetException_sendsHashInPath(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/exception-stack-traces/abc123" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ _, _ = w.Write([]byte(`{+ "group": {"exceptionHash":"abc123","stackTrace":"trace","count":7,"firstSeen":"2026-05-13T00:00:00Z","lastSeen":"2026-05-13T01:00:00Z"},+ "occurrences": [+ {"id":"00000000-0000-0000-0000-000000000001","exceptionHash":"abc123","stackTrace":"trace","recordedAt":"2026-05-13T00:30:00Z"}+ ],+ "pagination": {"page":1,"pageSize":20,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.GetException(context.Background(), "proj-1", "abc123", PaginationParams{Page: 1, PageSize: 20})+ if err != nil {+ t.Fatalf("GetException: %v", err)+ }+ if resp.Group == nil || resp.Group.ExceptionHash != "abc123" {+ t.Errorf("Group missing or wrong hash: %+v", resp.Group)+ }+ if len(resp.Occurrences) != 1 {+ t.Fatalf("got %d occurrences, want 1", len(resp.Occurrences))+ }+ if resp.Occurrences[0].ExceptionHash != "abc123" {+ t.Errorf("Occurrence ExceptionHash = %q", resp.Occurrences[0].ExceptionHash)+ }+}++func TestGetException_404_returnsErrNotFound(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.GetException(context.Background(), "proj-1", "missing", PaginationParams{})+ if err == nil {+ t.Fatal("expected an error")+ }+ if !errors.Is(err, ErrNotFound) {+ t.Errorf("expected ErrNotFound, got %v", err)+ }+}++func TestArchiveExceptions_postsHashesAndProjectId(t *testing.T) {+ var gotPath string+ var gotProject string+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("method = %q", r.Method)+ }+ if r.Header.Get("Authorization") != "Bearer tok" {+ t.Errorf("Authorization = %q", r.Header.Get("Authorization"))+ }+ gotPath = r.URL.Path+ gotProject = r.URL.Query().Get("projectId")+ _ = json.NewDecoder(r.Body).Decode(&gotBody)+ _, _ = w.Write([]byte(`{"success":true}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ err := c.ArchiveExceptions(context.Background(), "proj-1", []string{"h1", "h2", "h3"})+ if err != nil {+ t.Fatalf("ArchiveExceptions: %v", err)+ }+ if gotPath != "/api/exception-stack-traces/archive" {+ t.Errorf("path = %q", gotPath)+ }+ if gotProject != "proj-1" {+ t.Errorf("projectId = %q", gotProject)+ }+ hashes, _ := gotBody["hashes"].([]any)+ if len(hashes) != 3 || hashes[0] != "h1" || hashes[2] != "h3" {+ t.Errorf("body hashes = %v", hashes)+ }+}++func TestArchiveExceptions_403_returnsErrForbidden(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ err := c.ArchiveExceptions(context.Background(), "proj-1", []string{"h1"})+ if !errors.Is(err, ErrForbidden) {+ t.Errorf("expected ErrForbidden, got %v", err)+ }+}++func TestUnarchiveExceptions_postsHashesAndProjectId(t *testing.T) {+ var gotPath string+ var gotProject string+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ gotProject = r.URL.Query().Get("projectId")+ _ = json.NewDecoder(r.Body).Decode(&gotBody)+ _, _ = w.Write([]byte(`{"success":true}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ err := c.UnarchiveExceptions(context.Background(), "proj-1", []string{"h1"})+ if err != nil {+ t.Fatalf("UnarchiveExceptions: %v", err)+ }+ if gotPath != "/api/exception-stack-traces/unarchive" {+ t.Errorf("path = %q", gotPath)+ }+ if gotProject != "proj-1" {+ t.Errorf("projectId = %q", gotProject)+ }+ hashes, _ := gotBody["hashes"].([]any)+ if len(hashes) != 1 || hashes[0] != "h1" {+ t.Errorf("body hashes = %v", hashes)+ }+}diff --git a/cli/pkg/client/logs.go b/cli/pkg/client/logs.gonew file mode 100644index 00000000..de6d6024--- /dev/null+++ b/cli/pkg/client/logs.go@@ -0,0 +1,66 @@+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"++ "github.com/google/uuid"+)++// LogRecord matches the upstream models.LogRecord (subset — we drop fields+// we don't surface in v1, like resource/scope schema URLs).+type LogRecord struct {+ Id uuid.UUID `json:"id"`+ Timestamp time.Time `json:"timestamp"`+ SeverityText string `json:"severityText"`+ SeverityNumber uint8 `json:"severityNumber"`+ ServiceName string `json:"serviceName"`+ Body string `json:"body"`+ TraceId string `json:"traceId,omitempty"`+ SpanId string `json:"spanId,omitempty"`+ ResourceAttributes map[string]string `json:"resourceAttributes,omitempty"`+ ScopeName string `json:"scopeName,omitempty"`+ LogAttributes map[string]string `json:"logAttributes,omitempty"`+}++// QueryLogsRequest is the body for POST /api/logs.+type QueryLogsRequest struct {+ TimeRange TimeRange `json:"-"`+ Pagination PaginationParams `json:"pagination"`+ OrderBy string `json:"orderBy,omitempty"`+ SortDirection string `json:"sortDirection,omitempty"`+ Search string `json:"search,omitempty"`+ SearchType string `json:"searchType,omitempty"`+ MinSeverity uint8 `json:"minSeverity,omitempty"`+ ServiceName string `json:"serviceName,omitempty"`+ TraceId string `json:"traceId,omitempty"`+}++// MarshalJSON expands TimeRange into top-level fromDate/toDate.+func (r QueryLogsRequest) MarshalJSON() ([]byte, error) {+ type alias QueryLogsRequest+ wire := struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ alias+ }{r.TimeRange.From, r.TimeRange.To, alias(r)}+ return jsonMarshalNoHTMLEscape(wire)+}++// QueryLogsResponse mirrors the upstream PaginatedResponse[LogRecord].+type QueryLogsResponse struct {+ Data []LogRecord `json:"data"`+ Pagination Pagination `json:"pagination"`+}++// QueryLogs returns one page of log records for the given project and filters.+func (c *Client) QueryLogs(ctx context.Context, projectID string, req QueryLogsRequest) (*QueryLogsResponse, error) {+ path := "/api/logs?projectId=" + url.QueryEscape(projectID)+ var resp QueryLogsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}diff --git a/cli/pkg/client/logs_test.go b/cli/pkg/client/logs_test.gonew file mode 100644index 00000000..01890082--- /dev/null+++ b/cli/pkg/client/logs_test.go@@ -0,0 +1,80 @@+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestQueryLogs_basic(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/logs" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["fromDate"] == nil || body["toDate"] == nil {+ t.Errorf("body missing fromDate/toDate: %v", body)+ }+ _, _ = w.Write([]byte(`{+ "data":[+ {"id":"00000000-0000-0000-0000-000000000001","timestamp":"2026-05-13T12:00:00Z","severityText":"ERROR","severityNumber":17,"serviceName":"api","body":"boom"}+ ],+ "pagination":{"page":1,"pageSize":50,"total":1,"totalPages":1}+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.QueryLogs(context.Background(), "proj-1", QueryLogsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ Pagination: PaginationParams{Page: 1, PageSize: 50},+ ServiceName: "api",+ })+ if err != nil {+ t.Fatalf("QueryLogs: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("got %d logs", len(resp.Data))+ }+ if resp.Data[0].ServiceName != "api" {+ t.Errorf("ServiceName = %q", resp.Data[0].ServiceName)+ }+ if resp.Data[0].Body != "boom" {+ t.Errorf("Body = %q", resp.Data[0].Body)+ }+}++func TestQueryLogs_passesFilters(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ if body["serviceName"] != "api" {+ t.Errorf("serviceName = %v", body["serviceName"])+ }+ if int(body["minSeverity"].(float64)) != 13 { // WARN per OTel severity numbers+ t.Errorf("minSeverity = %v", body["minSeverity"])+ }+ if body["traceId"] != "abc123" {+ t.Errorf("traceId = %v", body["traceId"])+ }+ _, _ = w.Write([]byte(`{"data":[],"pagination":{}}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.QueryLogs(context.Background(), "proj-1", QueryLogsRequest{+ ServiceName: "api",+ MinSeverity: 13,+ TraceId: "abc123",+ })+ if err != nil {+ t.Fatal(err)+ }+}diff --git a/cli/pkg/client/metrics.go b/cli/pkg/client/metrics.gonew file mode 100644index 00000000..63103b7b--- /dev/null+++ b/cli/pkg/client/metrics.go@@ -0,0 +1,66 @@+package client++import (+ "context"+ "net/http"+ "net/url"+ "time"+)++// MetricQueryItem is one query within a QueryMetricsRequest.+type MetricQueryItem struct {+ Name string `json:"name"`+ Aggregation string `json:"aggregation,omitempty"`+ TagFilters map[string]string `json:"tagFilters,omitempty"`+ GroupBy string `json:"groupBy,omitempty"`+}++// QueryMetricsRequest is the body for POST /api/metrics/query.+//+// Note: metrics uses `from`/`to` (NOT fromDate/toDate like the other endpoints)+// and has no pagination — results are time-bucketed via IntervalMinutes.+type QueryMetricsRequest struct {+ TimeRange TimeRange `json:"-"`+ IntervalMinutes int `json:"intervalMinutes,omitempty"`+ Queries []MetricQueryItem `json:"queries"`+}++// MarshalJSON expands TimeRange into top-level from/to (NOT fromDate/toDate).+func (r QueryMetricsRequest) MarshalJSON() ([]byte, error) {+ type alias QueryMetricsRequest+ wire := struct {+ From time.Time `json:"from"`+ To time.Time `json:"to"`+ alias+ }{r.TimeRange.From, r.TimeRange.To, alias(r)}+ return jsonMarshalNoHTMLEscape(wire)+}++// TimeSeriesPoint is one data point in a metric query result.+type TimeSeriesPoint struct {+ Timestamp time.Time `json:"timestamp"`+ Value float64 `json:"value"`+}++// MetricQueryResult is one query's results, optionally grouped by tag.+// The map key is the group label ("all" if no GroupBy was specified).+type MetricQueryResult struct {+ Name string `json:"name"`+ Unit string `json:"unit"`+ Series map[string][]TimeSeriesPoint `json:"series"`+}++// QueryMetricsResponse is the upstream MetricQueryResponse.+type QueryMetricsResponse struct {+ Results []MetricQueryResult `json:"results"`+}++// QueryMetrics runs one or more metric queries against the project.+func (c *Client) QueryMetrics(ctx context.Context, projectID string, req QueryMetricsRequest) (*QueryMetricsResponse, error) {+ path := "/api/metrics/query?projectId=" + url.QueryEscape(projectID)+ var resp QueryMetricsResponse+ if err := c.do(ctx, http.MethodPost, path, req, &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}diff --git a/cli/pkg/client/metrics_test.go b/cli/pkg/client/metrics_test.gonew file mode 100644index 00000000..dfe81174--- /dev/null+++ b/cli/pkg/client/metrics_test.go@@ -0,0 +1,109 @@+package client++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestQueryMetrics_singleQuery(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/metrics/query" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.URL.Query().Get("projectId") != "proj-1" {+ t.Errorf("projectId = %q", r.URL.Query().Get("projectId"))+ }+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ // metrics uses 'from'/'to', not fromDate/toDate+ if body["from"] == nil || body["to"] == nil {+ t.Errorf("body missing from/to: %v", body)+ }+ queries, _ := body["queries"].([]any)+ if len(queries) != 1 {+ t.Fatalf("expected 1 query, got %d", len(queries))+ }+ q := queries[0].(map[string]any)+ if q["name"] != "http.request.duration" {+ t.Errorf("query name = %v", q["name"])+ }+ if q["aggregation"] != "p95" {+ t.Errorf("aggregation = %v", q["aggregation"])+ }+ _, _ = w.Write([]byte(`{+ "results":[+ {+ "name":"http.request.duration",+ "unit":"ms",+ "series":{+ "all":[+ {"timestamp":"2026-05-13T12:00:00Z","value":42.5},+ {"timestamp":"2026-05-13T12:05:00Z","value":47.0}+ ]+ }+ }+ ]+ }`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ resp, err := c.QueryMetrics(context.Background(), "proj-1", QueryMetricsRequest{+ TimeRange: TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()},+ IntervalMinutes: 5,+ Queries: []MetricQueryItem{+ {Name: "http.request.duration", Aggregation: "p95"},+ },+ })+ if err != nil {+ t.Fatalf("QueryMetrics: %v", err)+ }+ if len(resp.Results) != 1 {+ t.Fatalf("got %d results", len(resp.Results))+ }+ r := resp.Results[0]+ if r.Name != "http.request.duration" {+ t.Errorf("Name = %q", r.Name)+ }+ if r.Unit != "ms" {+ t.Errorf("Unit = %q", r.Unit)+ }+ series, ok := r.Series["all"]+ if !ok {+ t.Fatal(`series["all"] missing`)+ }+ if len(series) != 2 {+ t.Errorf("got %d points, want 2", len(series))+ }+ if series[0].Value != 42.5 {+ t.Errorf("series[0].Value = %v", series[0].Value)+ }+}++func TestQueryMetrics_multiQuery(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ queries, _ := body["queries"].([]any)+ if len(queries) != 2 {+ t.Errorf("expected 2 queries, got %d", len(queries))+ }+ _, _ = w.Write([]byte(`{"results":[]}`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ _, err := c.QueryMetrics(context.Background(), "proj-1", QueryMetricsRequest{+ Queries: []MetricQueryItem{+ {Name: "metric.a", Aggregation: "avg"},+ {Name: "metric.b", Aggregation: "sum"},+ },+ })+ if err != nil {+ t.Fatal(err)+ }+}diff --git a/cli/pkg/client/pagination.go b/cli/pkg/client/pagination.gonew file mode 100644index 00000000..822b9a8c--- /dev/null+++ b/cli/pkg/client/pagination.go@@ -0,0 +1,16 @@+package client++// PaginationParams is the request-side pagination control.+type PaginationParams struct {+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+}++// Pagination is the response-side pagination block. Traceway returns this+// on every paginated list endpoint.+type Pagination struct {+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+ Total int64 `json:"total"`+ TotalPages int64 `json:"totalPages"`+}diff --git a/cli/pkg/client/pagination_test.go b/cli/pkg/client/pagination_test.gonew file mode 100644index 00000000..1e015a33--- /dev/null+++ b/cli/pkg/client/pagination_test.go@@ -0,0 +1,29 @@+package client++import (+ "encoding/json"+ "testing"+)++func TestPaginationParams_marshalsJSON(t *testing.T) {+ p := PaginationParams{Page: 0, PageSize: 50}+ b, err := json.Marshal(p)+ if err != nil {+ t.Fatal(err)+ }+ want := `{"page":0,"pageSize":50}`+ if string(b) != want {+ t.Errorf("got %s, want %s", b, want)+ }+}++func TestPagination_unmarshalsJSON(t *testing.T) {+ in := `{"page":2,"pageSize":50,"total":312,"totalPages":7}`+ var p Pagination+ if err := json.Unmarshal([]byte(in), &p); err != nil {+ t.Fatal(err)+ }+ if p.Page != 2 || p.PageSize != 50 || p.Total != 312 || p.TotalPages != 7 {+ t.Errorf("got %+v", p)+ }+}diff --git a/cli/pkg/client/projects.go b/cli/pkg/client/projects.gonew file mode 100644index 00000000..ed808dbc--- /dev/null+++ b/cli/pkg/client/projects.go@@ -0,0 +1,23 @@+package client++import (+ "context"+ "net/http"+)++// Project is the minimal project shape we need today. Add fields as commands+// require them; do not pre-emptively mirror the entire upstream model.+type Project struct {+ ID string `json:"id"`+ Name string `json:"name"`+}++// ListProjects returns all projects visible to the authenticated user.+// Upstream: GET /api/projects → []Project (direct array, no pagination wrapper).+func (c *Client) ListProjects(ctx context.Context) ([]Project, error) {+ var projects []Project+ if err := c.do(ctx, http.MethodGet, "/api/projects", nil, &projects); err != nil {+ return nil, err+ }+ return projects, nil+}diff --git a/cli/pkg/client/projects_test.go b/cli/pkg/client/projects_test.gonew file mode 100644index 00000000..552c314f--- /dev/null+++ b/cli/pkg/client/projects_test.go@@ -0,0 +1,39 @@+package client++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestListProjects_decodesData(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/projects" {+ t.Errorf("path = %q", r.URL.Path)+ }+ if r.Method != http.MethodGet {+ t.Errorf("method = %q", r.Method)+ }+ _, _ = w.Write([]byte(`[+ {"id": "p1", "name": "stormwind-prod"},+ {"id": "p2", "name": "stormwind-staging"}+ ]`))+ }))+ defer srv.Close()++ c := New(srv.URL, WithJWT("tok"))+ projects, err := c.ListProjects(context.Background())+ if err != nil {+ t.Fatalf("ListProjects: %v", err)+ }+ if len(projects) != 2 {+ t.Fatalf("got %d projects, want 2", len(projects))+ }+ if projects[0].ID != "p1" {+ t.Errorf("projects[0].ID = %q", projects[0].ID)+ }+ if projects[1].Name != "stormwind-staging" {+ t.Errorf("projects[1].Name = %q", projects[1].Name)+ }+}diff --git a/cli/pkg/client/time.go b/cli/pkg/client/time.gonew file mode 100644index 00000000..9f43034d--- /dev/null+++ b/cli/pkg/client/time.go@@ -0,0 +1,27 @@+package client++import "time"++// TimeRange is an inclusive [From, To] interval used in resource queries.+// It marshals to RFC3339 strings via the request structs that embed it.+type TimeRange struct {+ From time.Time+ To time.Time+}++// TimeRangeFromSince returns a TimeRange ending now and starting `d` ago.+// Equivalent to TimeRangeFromSinceAt(d, time.Now()).+func TimeRangeFromSince(d time.Duration) TimeRange {+ return TimeRangeFromSinceAt(d, time.Now())+}++// TimeRangeFromSinceAt is the testable form: caller supplies "now".+func TimeRangeFromSinceAt(d time.Duration, now time.Time) TimeRange {+ return TimeRange{From: now.Add(-d), To: now}+}++// TimeRangeFromExplicit constructs a TimeRange from two explicit instants.+// Caller is responsible for ensuring From <= To.+func TimeRangeFromExplicit(from, to time.Time) TimeRange {+ return TimeRange{From: from, To: to}+}diff --git a/cli/pkg/client/time_test.go b/cli/pkg/client/time_test.gonew file mode 100644index 00000000..4c9dff49--- /dev/null+++ b/cli/pkg/client/time_test.go@@ -0,0 +1,37 @@+package client++import (+ "testing"+ "time"+)++func TestTimeRange_zeroValueIsValid(t *testing.T) {+ tr := TimeRange{}+ if !tr.From.IsZero() || !tr.To.IsZero() {+ t.Error("zero TimeRange should have zero From/To")+ }+}++func TestTimeRangeFromSince_setsFromToNow(t *testing.T) {+ now := time.Date(2026, 5, 14, 12, 0, 0, 0, time.UTC)+ tr := TimeRangeFromSinceAt(time.Hour, now)+ if !tr.To.Equal(now) {+ t.Errorf("To = %v, want %v", tr.To, now)+ }+ wantFrom := now.Add(-time.Hour)+ if !tr.From.Equal(wantFrom) {+ t.Errorf("From = %v, want %v", tr.From, wantFrom)+ }+}++func TestTimeRangeFromExplicit(t *testing.T) {+ from := time.Date(2026, 5, 13, 0, 0, 0, 0, time.UTC)+ to := time.Date(2026, 5, 14, 0, 0, 0, 0, time.UTC)+ tr := TimeRangeFromExplicit(from, to)+ if !tr.From.Equal(from) {+ t.Errorf("From = %v, want %v", tr.From, from)+ }+ if !tr.To.Equal(to) {+ t.Errorf("To = %v, want %v", tr.To, to)+ }+}diff --git a/cli/test/smoke/coverage_test.go b/cli/test/smoke/coverage_test.gonew file mode 100644index 00000000..7ba89b6b--- /dev/null+++ b/cli/test/smoke/coverage_test.go@@ -0,0 +1,141 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "strings"+ "testing"+)++// TestSmokeFlagCoverage exercises positive-path flag combinations documented+// by the traceway-cli usage skill that have no other smoke coverage. They+// share one login + one projects-use to keep wall-clock cost down; each+// subtest is otherwise independent.+func TestSmokeFlagCoverage(t *testing.T) {+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }++ t.Run("exceptions-since-Nd", func(t *testing.T) {+ // 7d must parse as 168h (the 839e873 fix). Smoke already covers 7D+ // (capital) as the negative case; this is the missing positive.+ stdout, stderr, code := runCLI(t, "",+ "exceptions", "list", "--since", "7d", "--page-size", "1", "--output", "json")+ if code != 0 {+ t.Fatalf("exceptions list --since 7d exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("stdout not JSON: %v\n%s", err, stdout)+ }+ if resp.Pagination == nil {+ t.Errorf("response missing pagination wrapper: %s", stdout)+ }+ })++ t.Run("exceptions-search-type-text", func(t *testing.T) {+ _, stderr, code := runCLI(t, "",+ "exceptions", "list", "--since", "24h",+ "--search", "Exception", "--search-type", "text",+ "--page-size", "1", "--output", "json")+ if code != 0 {+ t.Fatalf("exceptions list --search-type text exit %d\nstderr: %s", code, stderr)+ }+ })++ t.Run("exceptions-include-archived", func(t *testing.T) {+ _, stderr, code := runCLI(t, "",+ "exceptions", "list", "--since", "24h",+ "--include-archived", "--page-size", "1", "--output", "json")+ if code != 0 {+ t.Fatalf("exceptions list --include-archived exit %d\nstderr: %s", code, stderr)+ }+ })++ t.Run("endpoints-order-by-valid", func(t *testing.T) {+ // Cycle through all documented valid --order-by choices to confirm+ // the enum validator accepts them (complements the bogus negative).+ for _, choice := range []string{"impact", "count", "p95", "lastSeen"} {+ _, stderr, code := runCLI(t, "",+ "endpoints", "list", "--since", "24h",+ "--order-by", choice, "--page-size", "1", "--output", "json")+ if code != 0 {+ t.Errorf("endpoints list --order-by %s exit %d\nstderr: %s", choice, code, stderr)+ }+ }+ })++ t.Run("logs-min-severity-and-service", func(t *testing.T) {+ // --min-severity is numeric (OTel severity). The doc warns against+ // the wrong-shaped --severity error form; this pins the real flag.+ // --service with a name that almost certainly doesn't exist still+ // exits 0 (empty filter result).+ stdout, stderr, code := runCLI(t, "",+ "logs", "query", "--since", "1h",+ "--min-severity", "17", "--service", "nonexistent-service-xyz",+ "--page-size", "1", "--output", "json")+ if code != 0 {+ t.Fatalf("logs query --min-severity 17 --service ... exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("stdout not JSON: %v\n%s", err, stdout)+ }+ if resp.Pagination == nil {+ t.Errorf("response missing pagination wrapper: %s", stdout)+ }+ })++ t.Run("projects-fields-projection", func(t *testing.T) {+ // --fields id should yield objects with id only (no name) when+ // applied to projects list (which is a bare array, not a wrapper).+ stdout, stderr, code := runCLI(t, "",+ "projects", "list", "--fields", "id", "--output", "json")+ if code != 0 {+ t.Fatalf("projects list --fields id exit %d\nstderr: %s", code, stderr)+ }+ var arr []map[string]any+ if err := json.Unmarshal([]byte(stdout), &arr); err != nil {+ t.Fatalf("stdout not a JSON array: %v\n%s", err, stdout)+ }+ if len(arr) == 0 {+ t.Fatalf("--fields id returned 0 projects: %s", stdout)+ }+ for i, p := range arr {+ if _, ok := p["id"]; !ok {+ t.Errorf("project[%d] missing 'id': %v", i, p)+ }+ if _, ok := p["name"]; ok {+ t.Errorf("project[%d] still has 'name' after --fields id: %v", i, p)+ }+ }+ })++ t.Run("default-output-when-piped", func(t *testing.T) {+ // runCLI captures stdout via a pipe (non-TTY). The CLI's auto-mode+ // resolution should pick JSON, not table. Run without --output and+ // assert the stdout parses as JSON.+ stdout, stderr, code := runCLI(t, "", "projects", "list")+ if code != 0 {+ t.Fatalf("projects list (default --output) exit %d\nstderr: %s", code, stderr)+ }+ var arr []map[string]any+ if err := json.Unmarshal([]byte(stdout), &arr); err != nil {+ t.Fatalf("piped default-output stdout not JSON: %v\n%s",+ err, strings.SplitN(stdout, "\n", 4))+ }+ if len(arr) == 0 {+ t.Fatalf("projects list returned 0 projects")+ }+ })+}diff --git a/cli/test/smoke/doc.go b/cli/test/smoke/doc.gonew file mode 100644index 00000000..bc7b4851--- /dev/null+++ b/cli/test/smoke/doc.go@@ -0,0 +1,15 @@+//go:build smoke++// Package smoke contains end-to-end tests that talk to a real Traceway+// instance via the built CLI binary. They are gated behind the "smoke"+// build tag so `go test ./...` skips them entirely.+//+// Run with: go test -tags smoke ./test/smoke/... (or `just smoke-test`).+//+// Required env vars (tests are skipped, not failed, if any are missing):+//+// TRACEWAY_SMOKE_URL e.g. https://traceway.stormwind.local+// TRACEWAY_SMOKE_USERNAME email used to log in+// TRACEWAY_SMOKE_PASSWORD password+// TRACEWAY_SMOKE_PROJECT_ID UUID of a project the user can access+package smokediff --git a/cli/test/smoke/endpoints_test.go b/cli/test/smoke/endpoints_test.gonew file mode 100644index 00000000..3fa527c9--- /dev/null+++ b/cli/test/smoke/endpoints_test.go@@ -0,0 +1,75 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "strings"+ "testing"+)++func endpointsLogin(t *testing.T) {+ t.Helper()+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }+}++func TestSmokeEndpointsList(t *testing.T) {+ endpointsLogin(t)++ stdout, stderr, code := runCLI(t, "", "endpoints", "list", "--since", "24h", "--output", "json")+ if code != 0 {+ t.Fatalf("endpoints list exit %d\nstderr: %s", code, stderr)+ }+ var resp map[string]any+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("endpoints list stdout not JSON: %v\n%s", err, stdout)+ }+ if _, ok := resp["data"]; !ok {+ t.Errorf("endpoints list response missing 'data' field: %s", stdout)+ }+}++func TestSmokeEndpointsListBadOrderBy(t *testing.T) {+ endpointsLogin(t)+ _, stderr, code := runCLI(t, "",+ "endpoints", "list", "--since", "1h",+ "--order-by", "bogus", "--output", "json")+ if code != 2 {+ t.Fatalf("endpoints list --order-by bogus exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("expected usage_error envelope, got: %s", stderr)+ }+}++func TestSmokeEndpointsListFarFuture(t *testing.T) {+ endpointsLogin(t)+ stdout, stderr, code := runCLI(t, "",+ "endpoints", "list",+ "--from", "2099-01-01T00:00:00Z",+ "--to", "2099-01-02T00:00:00Z",+ "--output", "json")+ if code != 0 {+ t.Fatalf("endpoints list (far future) exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Data []map[string]any `json:"data"`+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("endpoints list far-future stdout not JSON: %v\n%s", err, stdout)+ }+ if len(resp.Data) != 0 {+ t.Errorf("far-future window returned %d rows, expected 0: %s", len(resp.Data), stdout)+ }+ if resp.Pagination == nil {+ t.Errorf("far-future response missing pagination wrapper: %s", stdout)+ }+}diff --git a/cli/test/smoke/errors_test.go b/cli/test/smoke/errors_test.gonew file mode 100644index 00000000..4c1394d3--- /dev/null+++ b/cli/test/smoke/errors_test.go@@ -0,0 +1,59 @@+//go:build smoke++package smoke++import (+ "strings"+ "testing"+)++// TestSmokeUnknownProfile verifies that a global --profile flag pointing at+// a name that doesn't exist produces a clean not_authenticated envelope+// (exit 4), not a panic or stack trace.+func TestSmokeUnknownProfile(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }++ _, stderr, code := runCLI(t, "",+ "--profile", "no-such-profile",+ "projects", "list", "--output", "json")+ if code != 4 {+ t.Fatalf("--profile no-such-profile exit = %d, want 4\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "not_authenticated") {+ t.Errorf("expected not_authenticated envelope, got: %s", stderr)+ }+ if strings.Contains(stderr, "panic:") || strings.Contains(stderr, "goroutine ") {+ t.Errorf("stderr contains panic/stack trace: %s", stderr)+ }+}++// TestSmokeUnknownProject verifies that a global --project flag pointing at+// a UUID the user can't access fails cleanly. The exact exit code depends on+// what the server returns (400/403/404 are all plausible — observed: 400 →+// api_error → exit 1). What we actually care about is: non-zero exit, no+// panic, no connection_failed (which would mean the URL plumbing broke).+func TestSmokeUnknownProject(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }++ _, stderr, code := runCLI(t, "",+ "--project", "00000000-0000-0000-0000-000000000000",+ "exceptions", "list", "--since", "1h",+ "--page-size", "1", "--output", "json")+ if code == 0 {+ t.Fatalf("--project <zeros> exited 0; expected a server-side error\nstderr: %s", stderr)+ }+ if strings.Contains(stderr, "panic:") || strings.Contains(stderr, "goroutine ") {+ t.Errorf("stderr contains panic/stack trace: %s", stderr)+ }+ if strings.Contains(stderr, "connection_failed") {+ t.Errorf("got connection_failed for a server-side auth/not-found case: %s", stderr)+ }+}diff --git a/cli/test/smoke/exceptions_test.go b/cli/test/smoke/exceptions_test.gonew file mode 100644index 00000000..3348c72a--- /dev/null+++ b/cli/test/smoke/exceptions_test.go@@ -0,0 +1,137 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "strings"+ "testing"+)++// exceptionsLogin runs the login + projects-use prelude shared by the+// exceptions subtests.+func exceptionsLogin(t *testing.T) {+ t.Helper()+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }+}++func TestSmokeExceptionsList(t *testing.T) {+ exceptionsLogin(t)++ stdout, stderr, code := runCLI(t, "", "exceptions", "list", "--since", "24h", "--output", "json")+ if code != 0 {+ t.Fatalf("exceptions list exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Data []map[string]any `json:"data"`+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("exceptions list stdout not JSON: %v\n%s", err, stdout)+ }+ if resp.Pagination == nil {+ t.Errorf("exceptions list response missing pagination wrapper: %s", stdout)+ }+}++func TestSmokeExceptionsListBadSearchType(t *testing.T) {+ exceptionsLogin(t)+ _, stderr, code := runCLI(t, "",+ "exceptions", "list", "--since", "1h",+ "--search-type", "bogus", "--output", "json")+ if code != 2 {+ t.Fatalf("exceptions list --search-type bogus exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("expected usage_error envelope, got: %s", stderr)+ }+}++func TestSmokeExceptionsListBadDuration(t *testing.T) {+ exceptionsLogin(t)+ // 7D (capital D) is not parseable — should trigger invalid_time_range.+ _, stderr, code := runCLI(t, "",+ "exceptions", "list", "--since", "7D", "--output", "json")+ if code != 2 {+ t.Fatalf("exceptions list --since 7D exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "invalid_time_range") {+ t.Errorf("expected invalid_time_range envelope, got: %s", stderr)+ }+}++func TestSmokeExceptionsListFromWithoutTo(t *testing.T) {+ exceptionsLogin(t)+ _, stderr, code := runCLI(t, "",+ "exceptions", "list",+ "--from", "2026-01-01T00:00:00Z", "--output", "json")+ if code != 2 {+ t.Fatalf("exceptions list --from (no --to) exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "invalid_time_range") {+ t.Errorf("expected invalid_time_range envelope, got: %s", stderr)+ }+}++func TestSmokeExceptionsListSinceAndAbsolute(t *testing.T) {+ exceptionsLogin(t)+ _, stderr, code := runCLI(t, "",+ "exceptions", "list", "--since", "1h",+ "--from", "2026-01-01T00:00:00Z",+ "--to", "2026-01-02T00:00:00Z",+ "--output", "json")+ if code != 2 {+ t.Fatalf("exceptions list (mixing --since + --from/--to) exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "invalid_time_range") {+ t.Errorf("expected invalid_time_range envelope, got: %s", stderr)+ }+}++func TestSmokeExceptionsListFarFuture(t *testing.T) {+ exceptionsLogin(t)+ stdout, stderr, code := runCLI(t, "",+ "exceptions", "list",+ "--from", "2099-01-01T00:00:00Z",+ "--to", "2099-01-02T00:00:00Z",+ "--output", "json")+ if code != 0 {+ t.Fatalf("exceptions list (far future) exit %d\nstderr: %s", code, stderr)+ }+ // Server returns data:null for empty result sets; assert clean JSON shape+ // and that data is null OR an empty slice.+ var resp struct {+ Data []map[string]any `json:"data"`+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("exceptions list far-future stdout not JSON: %v\n%s", err, stdout)+ }+ if len(resp.Data) != 0 {+ t.Errorf("far-future window returned %d rows, expected 0: %s", len(resp.Data), stdout)+ }+ if resp.Pagination == nil {+ t.Errorf("far-future response missing pagination wrapper: %s", stdout)+ }+}++func TestSmokeExceptionsShowBogusHash(t *testing.T) {+ exceptionsLogin(t)+ _, stderr, code := runCLI(t, "",+ "exceptions", "show",+ "0000000000000000000000000000000000000000000000000000000000000000",+ "--output", "json")+ if code != 5 {+ t.Fatalf("exceptions show <zeros> exit = %d, want 5\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "not_found") {+ t.Errorf("expected not_found envelope, got: %s", stderr)+ }+}diff --git a/cli/test/smoke/formats_test.go b/cli/test/smoke/formats_test.gonew file mode 100644index 00000000..87de4969--- /dev/null+++ b/cli/test/smoke/formats_test.go@@ -0,0 +1,51 @@+//go:build smoke++package smoke++import (+ "strings"+ "testing"+)++// TestSmokeOutputFormats exercises --output table and --output yaml on every+// list-shaped command. Only JSON shape is covered elsewhere; this test exists+// to catch regressions in the table/yaml renderers (which have no JSON+// schema to assert against, only "exit 0 and stdout is non-empty").+func TestSmokeOutputFormats(t *testing.T) {+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }++ cases := []struct {+ name string+ args []string+ }{+ {"projects-table", []string{"projects", "list", "--output", "table"}},+ {"projects-yaml", []string{"projects", "list", "--output", "yaml"}},+ {"profiles-table", []string{"profiles", "list", "--output", "table"}},+ {"profiles-yaml", []string{"profiles", "list", "--output", "yaml"}},+ {"exceptions-table", []string{"exceptions", "list", "--since", "24h", "--output", "table"}},+ {"exceptions-yaml", []string{"exceptions", "list", "--since", "24h", "--output", "yaml"}},+ {"endpoints-table", []string{"endpoints", "list", "--since", "24h", "--output", "table"}},+ {"endpoints-yaml", []string{"endpoints", "list", "--since", "24h", "--output", "yaml"}},+ {"logs-table", []string{"logs", "query", "--since", "1h", "--page-size", "5", "--output", "table"}},+ {"logs-yaml", []string{"logs", "query", "--since", "1h", "--page-size", "5", "--output", "yaml"}},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ stdout, stderr, code := runCLI(t, "", tc.args...)+ if code != 0 {+ t.Fatalf("exit %d\nargs: %v\nstderr: %s", code, tc.args, stderr)+ }+ if strings.TrimSpace(stdout) == "" {+ t.Errorf("empty stdout\nargs: %v", tc.args)+ }+ })+ }+}diff --git a/cli/test/smoke/harness_test.go b/cli/test/smoke/harness_test.gonew file mode 100644index 00000000..cad5376e--- /dev/null+++ b/cli/test/smoke/harness_test.go@@ -0,0 +1,93 @@+//go:build smoke++package smoke++import (+ "bytes"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+)++var binaryPath string++func TestMain(m *testing.M) {+ tmp, err := os.MkdirTemp("", "traceway-smoke-bin-")+ if err != nil {+ panic(err)+ }++ binaryPath = filepath.Join(tmp, "traceway")+ cmd := exec.Command("go", "build", "-o", binaryPath, "./cmd/traceway")+ cmd.Dir = repoRoot()+ if out, err := cmd.CombinedOutput(); err != nil {+ panic("smoke harness: go build failed: " + err.Error() + "\n" + string(out))+ }+ code := m.Run()+ _ = os.RemoveAll(tmp)+ os.Exit(code)+}++// repoRoot walks up from the current working dir to find go.mod.+func repoRoot() string {+ wd, err := os.Getwd()+ if err != nil {+ panic(err)+ }+ for d := wd; d != "/"; d = filepath.Dir(d) {+ if _, err := os.Stat(filepath.Join(d, "go.mod")); err == nil {+ return d+ }+ }+ panic("smoke harness: go.mod not found above " + wd)+}++// requireEnv reads the four smoke env vars and skips the test cleanly if+// any are missing. Returns (url, username, password, projectID).+func requireEnv(t *testing.T) (string, string, string, string) {+ t.Helper()+ url := os.Getenv("TRACEWAY_SMOKE_URL")+ user := os.Getenv("TRACEWAY_SMOKE_USERNAME")+ pass := os.Getenv("TRACEWAY_SMOKE_PASSWORD")+ proj := os.Getenv("TRACEWAY_SMOKE_PROJECT_ID")+ if url == "" || user == "" || pass == "" || proj == "" {+ t.Skip("smoke env not set (TRACEWAY_SMOKE_URL/USERNAME/PASSWORD/PROJECT_ID)")+ }+ return url, user, pass, proj+}++// freshXDG isolates each test by pointing XDG_CONFIG_HOME and XDG_STATE_HOME+// at fresh temp dirs. Cleanup is handled by t.TempDir.+func freshXDG(t *testing.T) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+}++// runCLI invokes the built binary with the given args. stdinBody is fed+// to the process stdin; pass "" for none. Returns stdout, stderr, exit code.+func runCLI(t *testing.T, stdinBody string, args ...string) (string, string, int) {+ t.Helper()+ cmd := exec.Command(binaryPath, args...)+ cmd.Env = os.Environ() // inherit XDG_* and any other vars+ if stdinBody != "" {+ cmd.Stdin = strings.NewReader(stdinBody)+ }+ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ err := cmd.Run()+ code := 0+ if err != nil {+ var ee *exec.ExitError+ if errors.As(err, &ee) {+ code = ee.ExitCode()+ } else {+ t.Fatalf("runCLI: failed to run %v: %v", args, err)+ }+ }+ return stdout.String(), stderr.String(), code+}diff --git a/cli/test/smoke/login_test.go b/cli/test/smoke/login_test.gonew file mode 100644index 00000000..5ddd1fcc--- /dev/null+++ b/cli/test/smoke/login_test.go@@ -0,0 +1,27 @@+//go:build smoke++package smoke++import (+ "strings"+ "testing"+)++// TestSmokeLogin authenticates against the real instance and verifies the+// resulting session works for one follow-up call. This is the prerequisite+// every other smoke test depends on.+func TestSmokeLogin(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)++ stdout, stderr, code := runCLI(t,+ pass+"\n",+ "login", "--url", url, "--username", user, "--password-stdin",+ )+ if code != 0 {+ t.Fatalf("login exit %d\nstdout: %s\nstderr: %s", code, stdout, stderr)+ }+ if !strings.Contains(stdout, "Logged in as "+user) {+ t.Errorf("login stdout = %q", stdout)+ }+}diff --git a/cli/test/smoke/logs_test.go b/cli/test/smoke/logs_test.gonew file mode 100644index 00000000..44d4348f--- /dev/null+++ b/cli/test/smoke/logs_test.go@@ -0,0 +1,94 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "strings"+ "testing"+)++func logsLogin(t *testing.T) {+ t.Helper()+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }+}++func TestSmokeLogsQuery(t *testing.T) {+ logsLogin(t)++ stdout, stderr, code := runCLI(t, "",+ "logs", "query", "--since", "1h", "--page-size", "5", "--output", "json")+ if code != 0 {+ t.Fatalf("logs query exit %d\nstderr: %s", code, stderr)+ }+ var resp map[string]any+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("logs query stdout not JSON: %v\n%s", err, stdout)+ }+ if _, ok := resp["data"]; !ok {+ t.Errorf("logs query response missing 'data' field: %s", stdout)+ }+}++func TestSmokeLogsQueryBadSortDirection(t *testing.T) {+ logsLogin(t)+ _, stderr, code := runCLI(t, "",+ "logs", "query", "--since", "1h",+ "--sort-direction", "bogus", "--output", "json")+ if code != 2 {+ t.Fatalf("logs query --sort-direction bogus exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("expected usage_error envelope, got: %s", stderr)+ }+}++func TestSmokeLogsQueryZeroTraceID(t *testing.T) {+ logsLogin(t)+ stdout, stderr, code := runCLI(t, "",+ "logs", "query", "--since", "1h",+ "--trace-id", "00000000000000000000000000000000",+ "--output", "json")+ if code != 0 {+ t.Fatalf("logs query --trace-id <zeros> exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Data []map[string]any `json:"data"`+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("logs query stdout not JSON: %v\n%s", err, stdout)+ }+ if len(resp.Data) != 0 {+ t.Errorf("zero trace-id returned %d rows, expected 0: %s", len(resp.Data), stdout)+ }+}++func TestSmokeLogsQueryFarFuture(t *testing.T) {+ logsLogin(t)+ stdout, stderr, code := runCLI(t, "",+ "logs", "query",+ "--from", "2099-01-01T00:00:00Z",+ "--to", "2099-01-02T00:00:00Z",+ "--output", "json")+ if code != 0 {+ t.Fatalf("logs query (far future) exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Data []map[string]any `json:"data"`+ Pagination map[string]any `json:"pagination"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("logs query far-future stdout not JSON: %v\n%s", err, stdout)+ }+ if len(resp.Data) != 0 {+ t.Errorf("far-future window returned %d rows, expected 0: %s", len(resp.Data), stdout)+ }+}diff --git a/cli/test/smoke/metrics_test.go b/cli/test/smoke/metrics_test.gonew file mode 100644index 00000000..75f7b3de--- /dev/null+++ b/cli/test/smoke/metrics_test.go@@ -0,0 +1,84 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "strings"+ "testing"+)++// metricsLogin runs the login + projects-use prelude shared by all metrics+// subtests so we don't repeat it five times.+func metricsLogin(t *testing.T) {+ t.Helper()+ url, user, pass, proj := requireEnv(t)+ freshXDG(t)+ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }+ if _, _, code := runCLI(t, "", "projects", "use", proj); code != 0 {+ t.Fatalf("projects use %s failed", proj)+ }+}++func TestSmokeMetricsQueryMissingName(t *testing.T) {+ metricsLogin(t)+ _, stderr, code := runCLI(t, "", "metrics", "query", "--since", "1h", "--output", "json")+ if code != 2 {+ t.Fatalf("metrics query (no --name) exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("expected usage_error envelope, got: %s", stderr)+ }+}++func TestSmokeMetricsQueryBogusName(t *testing.T) {+ metricsLogin(t)+ stdout, stderr, code := runCLI(t, "",+ "metrics", "query", "--name", "__no_such_metric_xyz__",+ "--since", "1h", "--output", "json")+ if code != 0 {+ t.Fatalf("metrics query (bogus name) exit = %d, want 0\nstderr: %s", code, stderr)+ }+ var resp struct {+ Results []struct {+ Name string `json:"name"`+ Series map[string]any `json:"series"`+ } `json:"results"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("metrics query stdout not JSON: %v\n%s", err, stdout)+ }+ for _, r := range resp.Results {+ if len(r.Series) != 0 {+ t.Errorf("bogus metric %q returned non-empty series: %v", r.Name, r.Series)+ }+ }+}++func TestSmokeMetricsQueryBadAggregation(t *testing.T) {+ metricsLogin(t)+ _, stderr, code := runCLI(t, "",+ "metrics", "query", "--name", "any",+ "--aggregation", "nopenope", "--since", "1h", "--output", "json")+ if code != 2 {+ t.Fatalf("metrics query (bad --aggregation) exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("expected usage_error envelope, got: %s", stderr)+ }+}++func TestSmokeMetricsQueryBadTag(t *testing.T) {+ metricsLogin(t)+ _, stderr, code := runCLI(t, "",+ "metrics", "query", "--name", "any",+ "--tag", "missingequals", "--since", "1h", "--output", "json")+ if code != 2 {+ t.Fatalf("metrics query (bad --tag) exit = %d, want 2\nstderr: %s", code, stderr)+ }+ if !strings.Contains(stderr, "usage_error") {+ t.Errorf("expected usage_error envelope, got: %s", stderr)+ }+}diff --git a/cli/test/smoke/profiles_test.go b/cli/test/smoke/profiles_test.gonew file mode 100644index 00000000..b0b7ee3d--- /dev/null+++ b/cli/test/smoke/profiles_test.go@@ -0,0 +1,48 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "testing"+)++func TestSmokeProfilesList(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)++ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed")+ }++ stdout, stderr, code := runCLI(t, "", "profiles", "list", "--output", "json")+ if code != 0 {+ t.Fatalf("profiles list exit %d\nstderr: %s", code, stderr)+ }+ var resp struct {+ Current string `json:"current"`+ Data []struct {+ Name string `json:"name"`+ URL string `json:"url"`+ Current bool `json:"current"`+ } `json:"data"`+ }+ if err := json.Unmarshal([]byte(stdout), &resp); err != nil {+ t.Fatalf("profiles list stdout not JSON: %v\n%s", err, stdout)+ }+ if resp.Current == "" {+ t.Errorf("profiles list response missing 'current': %s", stdout)+ }+ if len(resp.Data) == 0 {+ t.Fatalf("profiles list returned 0 profiles after login: %s", stdout)+ }+ foundCurrent := false+ for _, p := range resp.Data {+ if p.Current && p.Name == resp.Current {+ foundCurrent = true+ }+ }+ if !foundCurrent {+ t.Errorf("no profile marked current matches top-level current=%q: %s", resp.Current, stdout)+ }+}diff --git a/cli/test/smoke/projects_test.go b/cli/test/smoke/projects_test.gonew file mode 100644index 00000000..fe119d27--- /dev/null+++ b/cli/test/smoke/projects_test.go@@ -0,0 +1,32 @@+//go:build smoke++package smoke++import (+ "encoding/json"+ "testing"+)++func TestSmokeProjectsList(t *testing.T) {+ url, user, pass, _ := requireEnv(t)+ freshXDG(t)++ if _, _, code := runCLI(t, pass+"\n", "login", "--url", url, "--username", user, "--password-stdin"); code != 0 {+ t.Fatal("login failed (see TestSmokeLogin)")+ }++ stdout, stderr, code := runCLI(t, "", "projects", "list", "--output", "json")+ if code != 0 {+ t.Fatalf("projects list exit %d\nstderr: %s", code, stderr)+ }+ var arr []map[string]any+ if err := json.Unmarshal([]byte(stdout), &arr); err != nil {+ t.Fatalf("projects list stdout not a JSON array: %v\n%s", err, stdout)+ }+ if len(arr) == 0 {+ t.Fatal("projects list returned 0 projects; smoke account should have at least one")+ }+ if _, ok := arr[0]["id"]; !ok {+ t.Errorf("first project missing 'id' field: %v", arr[0])+ }+}