docs: bedroom developer documentation — complete docs/developers/ set

Adds the full bedroom-developer-docs OpenSpec change implementation:

- docs/developers/README.md — index page
- docs/developers/quick-start.md — bootstrap to working token in 7 steps
- docs/developers/concepts.md — AgentIdP, AGNTCY, lifecycle, OAuth 2.0, free tier
- docs/developers/guides/README.md — guide index
- docs/developers/guides/register-an-agent.md — all fields, validation, common errors
- docs/developers/guides/manage-credentials.md — generate, list, rotate, revoke
- docs/developers/guides/issue-and-revoke-tokens.md — OAuth 2.0 flow, introspect, revoke
- docs/developers/guides/query-audit-logs.md — filters, pagination, 90-day retention
- docs/developers/api-reference.md — all 14 endpoints, all error codes, curl examples

Also commits deferred OpenSpec housekeeping from previous session:
- Archives phase-1-mvp-implementation change to openspec/changes/archive/
- Adds bedroom-developer-docs change artifacts (30/30 tasks complete)
- Syncs 4 delta specs to openspec/specs/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
SentryAgent.ai Developer
2026-03-28 14:13:03 +00:00
parent d3530285b9
commit 61ea975c79
29 changed files with 2397 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-03-28

View File

@@ -0,0 +1,63 @@
## Context
Phase 1 MVP is complete: 46 source files, 14 API endpoints across 4 OpenAPI 3.0 specs, 244 passing tests. The implementation is production-grade and live on `git.sentryagent.ai`. However, the developer experience stops at the code. There is no entry point for a bedroom developer who has never heard of AgentIdP, AGNTCY, or client credentials OAuth 2.0.
The documentation must be written, owned, and maintained as a first-class deliverable — not an afterthought. It is produced by a Virtual Technical Writer subagent with full access to the codebase and OpenAPI specs.
**Constraints:**
- Audience: bedroom developers — assume competence with HTTP and basic programming, assume no prior knowledge of AgentIdP or AGNTCY
- Format: Markdown only — renders on GitHub, no external tooling required
- No build step — docs are static `.md` files in `docs/developers/`
- All code examples must be real, runnable, and copy-pasteable
- Tone: direct, practical, no enterprise jargon
## Goals / Non-Goals
**Goals:**
- Bedroom developer can register their first agent and issue a token in under 5 minutes using only the quick-start guide
- Every API endpoint is documented in plain English with at least one working curl example
- Core concepts are explained without assuming prior knowledge of OAuth 2.0 or AGNTCY
- All four P0 workflows (register, credential, token, audit) have step-by-step guides
- FAQ covers the most likely failure points and free-tier limits
**Non-Goals:**
- No web-rendered documentation site (Phase 2 — out of scope)
- No SDK documentation (Node.js SDK not yet built — Phase 1 P1 remaining)
- No video tutorials or interactive demos
- No multi-language code examples (Node.js + curl only for now)
- No enterprise deployment documentation (separate from bedroom developer focus)
## Decisions
**Decision 1: Single flat folder vs nested structure**
Chosen: flat `docs/developers/` with a `tutorials/` subfolder only for multi-step guides.
Alternative considered: deep nesting by category. Rejected — adds navigation friction for a small doc set.
**Decision 2: Raw OpenAPI YAML as API reference vs human-written reference**
Chosen: human-written `api-reference.md` alongside the existing OpenAPI specs.
Alternative considered: link to raw YAML only. Rejected — YAML is not readable for bedroom developers; the whole point is accessibility.
**Decision 3: Standalone docs vs inline code comments**
Chosen: standalone Markdown files in `docs/developers/`.
Alternative considered: JSDoc-generated docs. Rejected — JSDoc is for library consumers, not REST API users.
**Decision 4: Who writes the docs**
Chosen: Virtual Technical Writer subagent — spawned by CTO with full codebase + OpenAPI spec context.
Alternative considered: Virtual Principal Developer writes docs. Rejected — developer time should stay on code; writing accessible prose for non-technical audiences is a distinct skill warranting a dedicated role.
**Decision 5: Versioning**
Chosen: docs live in the same repo as code, versioned together via git. No separate docs versioning scheme in Phase 1.
## Risks / Trade-offs
- **[Risk] Docs drift from implementation** → Mitigation: Virtual QA Engineer verifies API reference examples against actual endpoints before sign-off; curl examples are tested against a running instance
- **[Risk] Tone inconsistency across docs** → Mitigation: Technical Writer receives a unified style brief in the subagent prompt (plain English, second person, imperative voice, no jargon)
- **[Risk] Quick-start prerequisites unclear** → Mitigation: Quick-start lists exact prerequisites (Docker, curl, nothing else) and links to docker-compose.yml
## Migration Plan
Documentation only — no migration required. Files are added to `docs/developers/` and committed to `develop`. No rollback needed.
## Open Questions
*(none — scope is fully defined)*

View File

@@ -0,0 +1,34 @@
## Why
SentryAgent.ai AgentIdP Phase 1 MVP is fully implemented, tested, and live — but there is zero human-readable documentation for the developers we are building this for. A bedroom developer landing on this repo today cannot register their first agent without reading raw OpenAPI YAML or diving into source code. We fix that now.
## What Changes
- New `docs/developers/` folder containing a complete, self-contained documentation set for bedroom developers
- Quick-start guide: first agent registered and authenticated in under 5 minutes
- Core concepts doc: plain-English explanation of AgentIdP, AGNTCY alignment, and the agent identity model
- Step-by-step guides: agent registration, credential management, token issuance, audit log queries
- Human-friendly API reference: every endpoint documented with real curl examples and response samples
- FAQ: common errors, gotchas, and free-tier limits explained
- All docs written for a bedroom developer audience — no enterprise jargon, no assumed knowledge
## Capabilities
### New Capabilities
- `quick-start`: 5-minute guide from zero to first authenticated agent request — install, register, credential, token, done
- `core-concepts`: Plain-English explanation of what AgentIdP is, how it relates to AGNTCY, the agent identity lifecycle, and why it matters
- `developer-guides`: Step-by-step tutorials for the four core workflows: registering an agent, managing credentials, issuing and revoking tokens, querying the audit log
- `api-reference`: Human-friendly API reference covering all 14 endpoints with real examples, field descriptions, error codes, and rate limit notes
### Modified Capabilities
*(none — this change introduces documentation only; no existing API specs are modified)*
## Impact
- New folder: `docs/developers/` (7 markdown files)
- No code changes — documentation only
- No new dependencies
- No API changes
- Existing `docs/openapi/` specs are reference material for the Technical Writer but are not modified

View File

@@ -0,0 +1,50 @@
## ADDED Requirements
### Requirement: API reference exists at docs/developers/api-reference.md
The system SHALL provide a human-readable API reference at `docs/developers/api-reference.md` covering all 14 endpoints across the four services: Agent Registry, OAuth 2.0 Token, Credential Management, and Audit Log.
#### Scenario: Developer finds any endpoint within 10 seconds
- **WHEN** the developer opens the API reference
- **THEN** they SHALL find a table of contents at the top linking to each of the four service sections
### Requirement: Every endpoint is documented with method, path, description, and auth requirements
For each of the 14 endpoints, the reference SHALL document: HTTP method, path, one-sentence description, and whether Bearer token auth is required.
#### Scenario: Developer knows which endpoints require authentication
- **WHEN** the developer scans the reference
- **THEN** they SHALL clearly see which endpoints require a Bearer token (all except POST /token) and which do not
### Requirement: Every endpoint includes a complete curl example
For each endpoint, the reference SHALL include at least one complete, runnable curl example with real placeholder values.
#### Scenario: Developer copies a curl example and runs it
- **WHEN** the developer copies a curl example from the reference
- **THEN** the command SHALL be complete — no ellipses, no `...`, no missing flags — requiring only substitution of their own agentId, token, and base URL
### Requirement: Every endpoint documents all request parameters and body fields
For each endpoint that accepts a request body or query parameters, the reference SHALL list every field with: name, type, required/optional, description, and validation constraints.
#### Scenario: Developer knows what fields are required for POST /agents
- **WHEN** the developer reads the POST /agents section
- **THEN** they SHALL see a table listing every field, its type, whether it is required, and any constraints (e.g. email format, max length)
### Requirement: Every endpoint documents all response codes and response body schemas
For each endpoint, the reference SHALL document every possible HTTP response code (2xx and 4xx/5xx) with a description and example response body.
#### Scenario: Developer understands a 429 response
- **WHEN** the developer reads the rate limit error documentation
- **THEN** they SHALL understand what triggered it, what the X-RateLimit-* headers mean, and when they can retry
### Requirement: API reference includes a base URL and versioning section
The reference SHALL include a section at the top explaining the base URL convention, port configuration, and that all endpoints are unversioned in Phase 1.
#### Scenario: Developer knows where to send requests
- **WHEN** the developer reads the base URL section
- **THEN** they SHALL see the default base URL (http://localhost:3000), how to change the port via environment variable, and a note that versioning will be introduced in Phase 2
### Requirement: API reference includes an errors section
The reference SHALL include a dedicated errors section listing all standard error response shapes, all custom error codes, and their HTTP status code mappings.
#### Scenario: Developer handles an AgentNotFoundError
- **WHEN** the developer reads the errors section
- **THEN** they SHALL see the exact JSON shape of the error response, the error code string, and the HTTP status (404)

View File

@@ -0,0 +1,43 @@
## ADDED Requirements
### Requirement: Core concepts guide exists at docs/developers/concepts.md
The system SHALL provide a concepts guide at `docs/developers/concepts.md` that explains the AgentIdP model in plain English with no assumed prior knowledge of AGNTCY or OAuth 2.0.
#### Scenario: Developer understands what AgentIdP is
- **WHEN** a developer reads the concepts guide
- **THEN** they SHALL be able to explain in one sentence what SentryAgent.ai AgentIdP does and why they need it
### Requirement: Concepts guide explains what an AI agent identity is
The guide SHALL explain in plain English what it means to give an AI agent an identity — how it differs from a human user account and why agents need their own identity model.
#### Scenario: Agent identity vs human identity distinction is clear
- **WHEN** the developer reads the agent identity section
- **THEN** they SHALL understand that agents are non-human, machine-operated identities that need persistent, auditable credentials — not session-based logins
### Requirement: Concepts guide explains the AGNTCY alignment
The guide SHALL explain what AGNTCY is (Linux Foundation standard), why SentryAgent.ai aligns to it, and what benefit that gives the developer — without requiring the developer to read the AGNTCY specification.
#### Scenario: Developer understands AGNTCY without external reading
- **WHEN** the developer reads the AGNTCY section
- **THEN** they SHALL understand that AGNTCY-aligned agent IDs are interoperable across the AI agent ecosystem, and that SentryAgent.ai implements this for free
### Requirement: Concepts guide explains the agent lifecycle
The guide SHALL explain the four lifecycle states of an agent (active, suspended, decommissioned) and what each state means for credential and token behaviour.
#### Scenario: Developer understands what happens when an agent is decommissioned
- **WHEN** the developer reads the lifecycle section
- **THEN** they SHALL understand that decommissioning is irreversible, all credentials are revoked, and no new tokens can be issued
### Requirement: Concepts guide explains OAuth 2.0 Client Credentials in plain English
The guide SHALL explain the Client Credentials grant in plain English — no RFC references, no formal OAuth jargon — focused on how agents use it to authenticate.
#### Scenario: Developer understands client_id and client_secret without prior OAuth knowledge
- **WHEN** the developer reads the OAuth section
- **THEN** they SHALL understand that client_id identifies the agent and client_secret proves it — analogous to a username and password for machines
### Requirement: Concepts guide explains the free-tier limits
The guide SHALL document all free-tier limits (100 agents, 10,000 tokens/month, 100 req/min, 90-day audit retention) in a clear table.
#### Scenario: Developer knows the limits before hitting them
- **WHEN** the developer reads the free-tier section
- **THEN** they SHALL see a table with all four limits and a note on what happens when each is exceeded

View File

@@ -0,0 +1,56 @@
## ADDED Requirements
### Requirement: Developer guides index exists at docs/developers/guides/README.md
The system SHALL provide a guides index at `docs/developers/guides/README.md` listing all available guides with one-line descriptions and links.
#### Scenario: Developer finds the right guide quickly
- **WHEN** the developer opens the guides folder
- **THEN** they SHALL see a list of all guides with descriptions so they can choose the one relevant to their task
### Requirement: Agent registration guide exists at docs/developers/guides/register-an-agent.md
The system SHALL provide a step-by-step guide for registering an agent, including all required and optional fields, validation rules, and how to handle the response.
#### Scenario: Developer registers their first agent
- **WHEN** the developer follows the registration guide
- **THEN** they SHALL successfully create an agent and understand what `agentId`, `clientId`, and `status` mean in the response
#### Scenario: Developer understands registration validation errors
- **WHEN** the guide covers validation
- **THEN** it SHALL show examples of common validation errors (missing required fields, invalid email format) and how to fix them
### Requirement: Credential management guide exists at docs/developers/guides/manage-credentials.md
The system SHALL provide a guide covering all four credential operations: generate, list, rotate, and revoke — with curl examples and explanation of when to use each.
#### Scenario: Developer rotates a compromised credential
- **WHEN** the developer follows the rotation section
- **THEN** they SHALL understand that rotation replaces the secret while keeping the same `credentialId`, and the old secret is immediately invalid
#### Scenario: Developer understands credential revocation vs agent decommission
- **WHEN** the developer reads the guide
- **THEN** they SHALL understand the difference: revoking a credential leaves the agent active with other credentials; decommissioning the agent revokes everything permanently
### Requirement: Token guide exists at docs/developers/guides/issue-and-revoke-tokens.md
The system SHALL provide a guide covering token issuance, introspection, and revocation — explaining the JWT structure, expiry, and how to use the Bearer token in API requests.
#### Scenario: Developer uses a token to authenticate a request
- **WHEN** the developer follows the token guide
- **THEN** they SHALL see an example of using the issued token as a Bearer token in an Authorization header on a subsequent API call
#### Scenario: Developer introspects a token to check validity
- **WHEN** the developer reads the introspection section
- **THEN** they SHALL understand what `active: true/false` means and what fields are returned
#### Scenario: Developer revokes a token
- **WHEN** the developer follows the revocation section
- **THEN** they SHALL understand that revoked tokens are immediately invalid even if not yet expired
### Requirement: Audit log guide exists at docs/developers/guides/query-audit-logs.md
The system SHALL provide a guide for querying the audit log — covering available filters (agentId, action, outcome, date range), pagination, and how to interpret audit events.
#### Scenario: Developer queries audit events for a specific agent
- **WHEN** the developer follows the audit guide
- **THEN** they SHALL see a curl example filtering by `agentId` and understand the structure of each audit event
#### Scenario: Developer understands audit log retention
- **WHEN** the developer reads the guide
- **THEN** they SHALL understand that free-tier audit logs are retained for 90 days and what happens after that window

View File

@@ -0,0 +1,45 @@
## ADDED Requirements
### Requirement: Quick-start guide exists at docs/developers/quick-start.md
The system SHALL provide a quick-start guide at `docs/developers/quick-start.md` that enables a bedroom developer to register their first agent and issue an OAuth 2.0 access token in under 5 minutes.
#### Scenario: Developer completes quick-start from zero
- **WHEN** a developer with no prior AgentIdP knowledge follows the quick-start guide
- **THEN** they SHALL have a registered agent, a valid credential, and a working access token by the end
### Requirement: Quick-start lists exact prerequisites
The quick-start guide SHALL list all prerequisites at the top before any steps, so the developer knows what they need before starting.
#### Scenario: Prerequisites are minimal and explicit
- **WHEN** the developer reads the prerequisites section
- **THEN** they SHALL see exactly: Docker (for running PostgreSQL and Redis) and curl (for API calls) — nothing else required
### Requirement: Quick-start provides a working docker-compose startup command
The quick-start guide SHALL include a single command to start the required infrastructure (PostgreSQL + Redis) using the project's `docker-compose.yml`.
#### Scenario: Developer starts infrastructure
- **WHEN** the developer runs the provided docker-compose command
- **THEN** the guide SHALL confirm what services are started and what ports they run on
### Requirement: Quick-start covers the full 4-step workflow
The quick-start guide SHALL cover exactly these four steps in order, each with a working curl command and the expected response:
1. Start the AgentIdP server
2. Register an agent (`POST /agents`)
3. Generate a credential (`POST /agents/{agentId}/credentials`)
4. Issue an access token (`POST /token`)
#### Scenario: Each step has a copy-pasteable curl command
- **WHEN** the developer reads any step
- **THEN** they SHALL find a complete curl command with real placeholder values they can substitute
#### Scenario: Each step shows the expected JSON response
- **WHEN** the developer runs a curl command from the guide
- **THEN** the guide SHALL show them what a successful response looks like so they can verify their output
### Requirement: Quick-start ends with a next-steps section
The quick-start guide SHALL end with a "What's Next" section linking to: core-concepts.md, developer-guides.md, and api-reference.md.
#### Scenario: Developer knows where to go after quick-start
- **WHEN** the developer reaches the end of the quick-start
- **THEN** they SHALL see at least 3 links to deeper documentation

View File

@@ -0,0 +1,50 @@
## 1. Folder Structure & Setup
- [x] 1.1 Create `docs/developers/` directory
- [x] 1.2 Create `docs/developers/guides/` subdirectory
- [x] 1.3 Create `docs/developers/README.md` — index page listing all docs with one-line descriptions and links
## 2. Quick-Start Guide
- [x] 2.1 Create `docs/developers/quick-start.md` — prerequisites section (Docker + curl only)
- [x] 2.2 Write Step 1: start infrastructure with docker-compose command + confirmation of services and ports
- [x] 2.3 Write Step 2: start AgentIdP server with npm command + expected startup output
- [x] 2.4 Write Step 3: register an agent — complete curl for `POST /agents` with example request body and expected JSON response
- [x] 2.5 Write Step 4: generate a credential — complete curl for `POST /agents/{agentId}/credentials` with example response showing `clientId` and `clientSecret`
- [x] 2.6 Write Step 5: issue an access token — complete curl for `POST /token` with form-encoded body and example JWT response
- [x] 2.7 Write "What's Next" section linking to concepts.md, guides/README.md, and api-reference.md
## 3. Core Concepts Guide
- [x] 3.1 Create `docs/developers/concepts.md` — intro section: what is AgentIdP in one paragraph
- [x] 3.2 Write "What is an AI Agent Identity" section — plain-English explanation of agent identities vs human identities
- [x] 3.3 Write "AGNTCY Alignment" section — what AGNTCY is, why it matters, benefit to the developer (no external reading required)
- [x] 3.4 Write "Agent Lifecycle" section — four states (active, suspended, decommissioned) and what each means for credentials and tokens, including irreversibility of decommission
- [x] 3.5 Write "OAuth 2.0 Client Credentials" section — plain-English explanation of client_id, client_secret, and how agents use them; no RFC jargon
- [x] 3.6 Write "Free Tier Limits" section — table of all four limits (100 agents, 10k tokens/month, 100 req/min, 90-day audit) with notes on what happens when each is exceeded
## 4. Developer Guides
- [x] 4.1 Create `docs/developers/guides/README.md` — index listing all four guides with descriptions and links
- [x] 4.2 Create `docs/developers/guides/register-an-agent.md` — step-by-step registration guide with all required/optional fields, validation rules, and example success + error responses (including common validation errors and fixes)
- [x] 4.3 Create `docs/developers/guides/manage-credentials.md` — guide covering all four credential operations: generate (with secret handling note), list (with pagination), rotate (explaining same credentialId, old secret immediately invalid), revoke (with comparison to agent decommission)
- [x] 4.4 Create `docs/developers/guides/issue-and-revoke-tokens.md` — token guide covering: issuance with form-encoded body, JWT structure explanation, using token as Bearer in subsequent requests, introspection (`active` field), revocation and immediate invalidation
- [x] 4.5 Create `docs/developers/guides/query-audit-logs.md` — audit log guide covering: available filters (agentId, action, outcome, date range), pagination params, audit event structure, 90-day retention behaviour
## 5. API Reference
- [x] 5.1 Create `docs/developers/api-reference.md` — top section: base URL, port config via env var, versioning note (Phase 1 unversioned)
- [x] 5.2 Write table of contents linking to all four service sections
- [x] 5.3 Write errors reference section: all error response shapes, all custom error codes (ValidationError, AgentNotFoundError, AgentAlreadyExistsError, CredentialError, AuthenticationError, AuthorizationError, RateLimitError, FreeTierLimitError), HTTP status mappings
- [x] 5.4 Document Agent Registry endpoints (5): `POST /agents`, `GET /agents`, `GET /agents/{agentId}`, `PATCH /agents/{agentId}`, `DELETE /agents/{agentId}` — each with method, path, auth requirement, request fields table, response codes table, and complete curl example
- [x] 5.5 Document OAuth 2.0 Token endpoints (3): `POST /token`, `POST /token/introspect`, `POST /token/revoke` — each with method, path, auth requirement, request fields table (noting form-encoded for /token), response codes table, curl example, and X-RateLimit header documentation for 429s
- [x] 5.6 Document Credential Management endpoints (4): `POST /agents/{agentId}/credentials`, `GET /agents/{agentId}/credentials`, `POST /agents/{agentId}/credentials/{credentialId}/rotate`, `DELETE /agents/{agentId}/credentials/{credentialId}` — each with method, path, auth requirement, request fields table, response codes table, and complete curl example
- [x] 5.7 Document Audit Log endpoints (2): `GET /audit`, `GET /audit/{eventId}` — each with method, path, auth requirement, query parameter table (including all filter options), response codes table, and complete curl example
## 6. QA & Review
- [x] 6.1 Verify all curl examples are syntactically correct and complete (no ellipses, no missing flags)
- [x] 6.2 Verify all 14 endpoints from the OpenAPI specs are covered in api-reference.md
- [x] 6.3 Verify all internal links (cross-references between docs) resolve correctly
- [x] 6.4 Verify free-tier limits in concepts.md match README.md Section 3.3
- [x] 6.5 Verify quick-start guide is self-contained — a developer can complete it using only that file

View File

@@ -0,0 +1,86 @@
## ADDED Requirements
### Requirement: Register a new AI agent
The system SHALL create a new agent identity record with a system-assigned immutable UUID (`agentId`) when a valid `CreateAgentRequest` is received. The `email` field SHALL be unique across all agents. The agent SHALL be created with `status: active`. The system SHALL enforce a free-tier limit of 100 registered agents per account.
#### Scenario: Successful agent registration
- **WHEN** a POST request to `/agents` is received with a valid `CreateAgentRequest` body and a valid Bearer token
- **THEN** the system creates the agent, assigns a UUID `agentId`, sets `status` to `active`, sets `createdAt` and `updatedAt` to the current timestamp, and returns `201` with the full `Agent` object
#### Scenario: Duplicate email rejected
- **WHEN** a POST request to `/agents` is received with an `email` that is already registered
- **THEN** the system returns `409 Conflict` with `code: AGENT_ALREADY_EXISTS`
#### Scenario: Free tier limit enforced
- **WHEN** a POST request to `/agents` is received and the account already has 100 registered agents
- **THEN** the system returns `403 Forbidden` with `code: FREE_TIER_LIMIT_EXCEEDED` and `details.limit: 100`
#### Scenario: Invalid request body rejected
- **WHEN** a POST request to `/agents` is received with a missing required field or invalid field value (e.g. invalid semver, invalid email, invalid capability pattern)
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details` identifying the failing field
### Requirement: Retrieve a single agent by ID
The system SHALL return the full `Agent` record for a given `agentId`.
#### Scenario: Agent found
- **WHEN** a GET request to `/agents/{agentId}` is received with a valid Bearer token and a UUID that exists in the registry
- **THEN** the system returns `200 OK` with the full `Agent` object
#### Scenario: Agent not found
- **WHEN** a GET request to `/agents/{agentId}` is received with a UUID that does not exist
- **THEN** the system returns `404 Not Found` with `code: AGENT_NOT_FOUND`
### Requirement: List agents with pagination and filtering
The system SHALL return a paginated list of agents, orderd by `createdAt` descending, optionally filtered by `owner`, `agentType`, and/or `status`.
#### Scenario: Successful paginated list
- **WHEN** a GET request to `/agents` is received with optional `page`, `limit`, `owner`, `agentType`, `status` query parameters and a valid Bearer token
- **THEN** the system returns `200 OK` with a `PaginatedAgentsResponse` containing `data`, `total`, `page`, and `limit`
#### Scenario: Invalid pagination parameters rejected
- **WHEN** a GET request to `/agents` is received with `limit` greater than 100 or `page` less than 1
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR`
### Requirement: Update agent metadata
The system SHALL partially update a mutable agent record. `agentId`, `email`, and `createdAt` SHALL be immutable. Setting `status` to `decommissioned` SHALL be a one-way irreversible operation.
#### Scenario: Successful partial update
- **WHEN** a PATCH request to `/agents/{agentId}` is received with a valid partial `UpdateAgentRequest` body and a valid Bearer token
- **THEN** the system updates only the provided fields, sets `updatedAt` to the current timestamp, and returns `200 OK` with the full updated `Agent` object
#### Scenario: Attempt to modify immutable field rejected
- **WHEN** a PATCH request to `/agents/{agentId}` contains the `email` field
- **THEN** the system returns `400 Bad Request` with `code: IMMUTABLE_FIELD` and `details.field: email`
#### Scenario: Decommissioned agent cannot be updated
- **WHEN** a PATCH request to `/agents/{agentId}` targets an agent with `status: decommissioned`
- **THEN** the system returns `403 Forbidden` with `code: AGENT_DECOMMISSIONED`
### Requirement: Decommission (soft-delete) an agent
The system SHALL set an agent's `status` to `decommissioned` and revoke all of its active credentials. The agent record SHALL be retained for audit purposes. This operation SHALL be irreversible.
#### Scenario: Successful decommission
- **WHEN** a DELETE request to `/agents/{agentId}` is received with a valid Bearer token and the agent exists and is not already decommissioned
- **THEN** the system sets `status` to `decommissioned`, revokes all active credentials for this agent, and returns `204 No Content`
#### Scenario: Already decommissioned agent rejected
- **WHEN** a DELETE request to `/agents/{agentId}` is received for an agent that is already `decommissioned`
- **THEN** the system returns `409 Conflict` with `code: AGENT_ALREADY_DECOMMISSIONED`
### Requirement: Authentication required on all agent endpoints
All agent endpoints SHALL require a valid Bearer JWT in the `Authorization` header.
#### Scenario: Missing token rejected
- **WHEN** any request to `/agents` or `/agents/{agentId}` is received without an `Authorization: Bearer` header
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
#### Scenario: Invalid token rejected
- **WHEN** any request to `/agents` or `/agents/{agentId}` is received with an expired, malformed, or revoked Bearer token
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`
### Requirement: Rate limiting on all agent endpoints
The system SHALL enforce a rate limit of 100 requests per minute per authenticated client. Rate limit state SHALL be tracked in Redis.
#### Scenario: Rate limit exceeded
- **WHEN** a client sends more than 100 requests to any agent endpoint within a 60-second window
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers

View File

@@ -0,0 +1,72 @@
## ADDED Requirements
### Requirement: Audit events are written internally for all significant actions
The system SHALL automatically create an immutable `AuditEvent` record for each of the following actions: `agent.created`, `agent.updated`, `agent.decommissioned`, `agent.suspended`, `agent.reactivated`, `token.issued`, `token.revoked`, `token.introspected`, `credential.generated`, `credential.rotated`, `credential.revoked`, `auth.failed`. No API endpoint SHALL allow external creation, modification, or deletion of audit records.
#### Scenario: Audit event created on agent registration
- **WHEN** a new agent is successfully registered via `POST /agents`
- **THEN** an `AuditEvent` with `action: agent.created`, `outcome: success`, and `metadata` containing `agentType` and `owner` is persisted
#### Scenario: Audit event created on failed authentication
- **WHEN** a `POST /token` request fails due to invalid credentials
- **THEN** an `AuditEvent` with `action: auth.failed`, `outcome: failure`, and `metadata` containing `reason` and `clientId` is persisted
#### Scenario: Audit event created on token issuance
- **WHEN** a token is successfully issued via `POST /token`
- **THEN** an `AuditEvent` with `action: token.issued`, `outcome: success`, and `metadata` containing `scope` and `expiresAt` is persisted
### Requirement: Query the audit log with pagination and filtering
The system SHALL return a paginated list of audit events ordered by `timestamp` descending. The caller SHALL hold a valid Bearer token with `audit:read` scope. Filtering SHALL support `agentId`, `action`, `outcome`, `fromDate`, and `toDate` — all optional, combined with logical AND.
#### Scenario: Successful audit log query
- **WHEN** a GET request to `/audit` is received with a valid Bearer token with `audit:read` scope
- **THEN** the system returns `200 OK` with a `PaginatedAuditEventsResponse` containing `data`, `total`, `page`, and `limit`
#### Scenario: Filter by agentId
- **WHEN** a GET request to `/audit?agentId={uuid}` is received
- **THEN** only events where `agentId` equals the provided UUID are returned
#### Scenario: Filter by action
- **WHEN** a GET request to `/audit?action=token.issued` is received
- **THEN** only events with `action: token.issued` are returned
#### Scenario: Filter by date range
- **WHEN** a GET request to `/audit?fromDate=2026-03-01T00:00:00.000Z&toDate=2026-03-28T23:59:59.999Z` is received
- **THEN** only events with `timestamp` within the specified range are returned
#### Scenario: fromDate after toDate rejected
- **WHEN** a GET request to `/audit` is received with `fromDate` that is chronologically after `toDate`
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details.reason` explaining the invalid date range
#### Scenario: Insufficient scope rejected
- **WHEN** a GET request to `/audit` is received with a valid Bearer token that does not have `audit:read` scope
- **THEN** the system returns `403 Forbidden` with `code: INSUFFICIENT_SCOPE`
### Requirement: Retrieve a single audit event by ID
The system SHALL return a single immutable `AuditEvent` by its `eventId`. The caller SHALL hold a valid Bearer token with `audit:read` scope.
#### Scenario: Audit event found
- **WHEN** a GET request to `/audit/{eventId}` is received with a valid Bearer token with `audit:read` scope and a UUID that exists in the audit log
- **THEN** the system returns `200 OK` with the full `AuditEvent` object
#### Scenario: Audit event not found
- **WHEN** a GET request to `/audit/{eventId}` is received with a UUID that does not exist in the audit log
- **THEN** the system returns `404 Not Found` with `code: AUDIT_EVENT_NOT_FOUND`
### Requirement: Free-tier 90-day audit log retention
On the free tier, the system SHALL only return audit events from the last 90 days. Events older than 90 days SHALL be treated as not accessible (return empty results for queries, `404` for direct lookups). The system SHALL return a `400` error with `code: RETENTION_WINDOW_EXCEEDED` if a `fromDate` query parameter falls outside the 90-day retention window.
#### Scenario: Query outside retention window rejected
- **WHEN** a GET request to `/audit` is received with `fromDate` more than 90 days before today
- **THEN** the system returns `400 Bad Request` with `code: RETENTION_WINDOW_EXCEEDED` and `details.retentionDays: 90`
#### Scenario: Direct lookup of expired event returns 404
- **WHEN** a GET request to `/audit/{eventId}` is received for an event with a `timestamp` older than 90 days
- **THEN** the system returns `404 Not Found` with `code: AUDIT_EVENT_NOT_FOUND`
### Requirement: Rate limiting on audit endpoints
The system SHALL enforce a rate limit of 100 requests per minute per authenticated client on all audit endpoints.
#### Scenario: Rate limit exceeded on audit endpoint
- **WHEN** a client sends more than 100 requests to any audit endpoint within a 60-second window
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers

View File

@@ -0,0 +1,83 @@
## ADDED Requirements
### Requirement: Generate new credentials for an agent
The system SHALL generate a new `client_id`/`client_secret` pair for a specified agent. The `client_id` SHALL equal the agent's `agentId`. The `client_secret` SHALL be a cryptographically random string with the prefix `sk_live_` followed by 64 hex characters (256 bits of entropy). The plain-text secret SHALL be returned in the response exactly once and SHALL never be stored in plain text — only a bcrypt hash (10 rounds) SHALL be persisted. The agent MUST be in `active` status to generate credentials.
#### Scenario: Successful credential generation
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with a valid Bearer token and the agent exists with `status: active`
- **THEN** the system generates a new credential, persists the bcrypt hash of the secret, and returns `201 Created` with a `CredentialWithSecret` response including the plain-text `clientSecret`
#### Scenario: clientSecret not returned after creation
- **WHEN** a GET request to `/agents/{agentId}/credentials` is made after credential creation
- **THEN** the `clientSecret` field is NOT present in any `Credential` object in the response
#### Scenario: Suspended agent cannot generate credentials
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for an agent with `status: suspended`
- **THEN** the system returns `403 Forbidden` with `code: AGENT_NOT_ACTIVE`
#### Scenario: Decommissioned agent cannot generate credentials
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for an agent with `status: decommissioned`
- **THEN** the system returns `403 Forbidden` with `code: AGENT_NOT_ACTIVE`
#### Scenario: Optional expiry respected
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with an `expiresAt` value that is a future date-time
- **THEN** the credential is created with the specified `expiresAt` value
#### Scenario: Past expiry rejected
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received with an `expiresAt` value that is in the past
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR` and `details.field: expiresAt`
#### Scenario: Agent not found
- **WHEN** a POST request to `/agents/{agentId}/credentials` is received for a `agentId` that does not exist
- **THEN** the system returns `404 Not Found` with `code: AGENT_NOT_FOUND`
### Requirement: List credentials for an agent
The system SHALL return a paginated list of all credentials (both `active` and `revoked`) for an agent, ordered by `createdAt` descending. The `clientSecret` SHALL never be included in list responses.
#### Scenario: Successful credential list
- **WHEN** a GET request to `/agents/{agentId}/credentials` is received with optional `page`, `limit`, `status` query parameters and a valid Bearer token
- **THEN** the system returns `200 OK` with a `PaginatedCredentialsResponse` containing `data`, `total`, `page`, and `limit`, with no `clientSecret` fields
#### Scenario: Filter by status
- **WHEN** a GET request to `/agents/{agentId}/credentials?status=active` is received
- **THEN** only credentials with `status: active` are returned
### Requirement: Rotate a credential
The system SHALL rotate an existing active credential by generating a new `clientSecret` for the same `credentialId`. The previous secret SHALL be immediately invalidated. The new plain-text secret SHALL be returned once and never persisted. Only `active` credentials can be rotated.
#### Scenario: Successful rotation
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received with a valid Bearer token and the credential exists with `status: active`
- **THEN** the system generates a new secret, replaces the stored bcrypt hash, and returns `200 OK` with a `CredentialWithSecret` response including the new plain-text `clientSecret`. The `credentialId` remains unchanged.
#### Scenario: Revoked credential cannot be rotated
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received for a credential with `status: revoked`
- **THEN** the system returns `409 Conflict` with `code: CREDENTIAL_ALREADY_REVOKED`
#### Scenario: Credential not found
- **WHEN** a POST request to `/agents/{agentId}/credentials/{credentialId}/rotate` is received with a `credentialId` that does not exist for the given agent
- **THEN** the system returns `404 Not Found` with `code: CREDENTIAL_NOT_FOUND`
### Requirement: Revoke a credential
The system SHALL permanently revoke a credential by setting its `status` to `revoked` and recording a `revokedAt` timestamp. The credential record SHALL be retained for audit purposes. Revocation SHALL be irreversible. Tokens previously issued with this credential SHALL remain valid until their natural expiry (token revocation is handled separately via `POST /token/revoke`). Revoking an already-revoked credential SHALL return `409 Conflict`.
#### Scenario: Successful revocation
- **WHEN** a DELETE request to `/agents/{agentId}/credentials/{credentialId}` is received with a valid Bearer token and the credential exists with `status: active`
- **THEN** the system sets `status` to `revoked`, sets `revokedAt` to the current timestamp, and returns `204 No Content`
#### Scenario: Already-revoked credential rejected
- **WHEN** a DELETE request to `/agents/{agentId}/credentials/{credentialId}` is received for a credential that is already `revoked`
- **THEN** the system returns `409 Conflict` with `code: CREDENTIAL_ALREADY_REVOKED`
### Requirement: Agent decommission cascades to credential revocation
When an agent is decommissioned via `DELETE /agents/{agentId}`, the system SHALL revoke all active credentials for that agent as part of the same operation.
#### Scenario: All credentials revoked on agent decommission
- **WHEN** an agent is successfully decommissioned via `DELETE /agents/{agentId}`
- **THEN** all credentials for that agent with `status: active` are set to `status: revoked` with `revokedAt` = current timestamp
### Requirement: Authentication required on all credential endpoints
All credential endpoints SHALL require a valid Bearer JWT. An agent MAY manage its own credentials using a self-issued token. Managing another agent's credentials SHALL return `403 Forbidden` unless the caller holds an admin-scoped token (admin scope is not implemented in Phase 1 — return `403` for all cross-agent requests).
#### Scenario: Unauthenticated request rejected
- **WHEN** any request to `/agents/{agentId}/credentials` is received without a valid Bearer token
- **THEN** the system returns `401 Unauthorized` with `code: UNAUTHORIZED`

View File

@@ -0,0 +1,76 @@
## ADDED Requirements
### Requirement: Issue access token via Client Credentials grant
The system SHALL issue a signed RS256 JWT access token when an agent authenticates with a valid `client_id` (agentId) and `client_secret` using the OAuth 2.0 Client Credentials grant (RFC 6749 §4.4). The request body SHALL use `application/x-www-form-urlencoded` encoding. The response SHALL include `Cache-Control: no-store` and `Pragma: no-cache` headers. The system SHALL enforce a free-tier limit of 10,000 token requests per calendar month per client.
#### Scenario: Successful token issuance
- **WHEN** a POST request to `/token` is received with `grant_type=client_credentials`, a valid `client_id`, and a valid `client_secret` for an `active` agent
- **THEN** the system verifies the credential, issues a signed JWT with `sub` = `agentId`, `scope` = requested (or default) scope, `exp` = now + 3600s, and returns `200 OK` with `TokenResponse`
#### Scenario: Invalid client credentials rejected
- **WHEN** a POST request to `/token` is received with a `client_id` that does not exist or a `client_secret` that does not match
- **THEN** the system returns `401 Unauthorized` with `error: invalid_client`
#### Scenario: Suspended agent cannot obtain tokens
- **WHEN** a POST request to `/token` is received for an agent with `status: suspended`
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client` and a description indicating the agent is suspended
#### Scenario: Decommissioned agent cannot obtain tokens
- **WHEN** a POST request to `/token` is received for an agent with `status: decommissioned`
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client`
#### Scenario: Unsupported grant type rejected
- **WHEN** a POST request to `/token` is received with a `grant_type` other than `client_credentials`
- **THEN** the system returns `400 Bad Request` with `error: unsupported_grant_type`
#### Scenario: Invalid scope rejected
- **WHEN** a POST request to `/token` is received with a `scope` value that contains an unrecognised scope identifier
- **THEN** the system returns `400 Bad Request` with `error: invalid_scope`
#### Scenario: Free tier monthly token limit enforced
- **WHEN** a POST request to `/token` is received and the agent has already made 10,000 token requests in the current calendar month
- **THEN** the system returns `403 Forbidden` with `error: unauthorized_client` and a description indicating the monthly free-tier limit is reached
### Requirement: Token introspection (RFC 7662)
The system SHALL determine whether a given access token is currently active (valid, not expired, not revoked). The endpoint SHALL return `200 OK` for both active and inactive tokens — the `active` field in the response SHALL indicate validity. The caller SHALL hold a valid Bearer token with `tokens:read` scope.
#### Scenario: Active token introspection
- **WHEN** a POST request to `/token/introspect` is received with a valid, non-expired, non-revoked token and the caller has `tokens:read` scope
- **THEN** the system returns `200 OK` with `active: true` and the token's claims (`sub`, `client_id`, `scope`, `token_type`, `iat`, `exp`)
#### Scenario: Expired or revoked token introspection
- **WHEN** a POST request to `/token/introspect` is received with a token that is expired or has been revoked
- **THEN** the system returns `200 OK` with `active: false` and no other claims
#### Scenario: Insufficient scope for introspection
- **WHEN** a POST request to `/token/introspect` is received with a valid Bearer token that does not have `tokens:read` scope
- **THEN** the system returns `403 Forbidden` with `code: INSUFFICIENT_SCOPE`
### Requirement: Token revocation (RFC 7009)
The system SHALL invalidate a given access token immediately. Revoking an already-revoked or expired token SHALL be a successful, idempotent operation (RFC 7009 §2.1). Revoked token JTIs SHALL be stored in Redis with TTL equal to the token's remaining lifetime.
#### Scenario: Successful token revocation
- **WHEN** a POST request to `/token/revoke` is received with a valid Bearer token and a `token` parameter containing a valid JWT
- **THEN** the system adds the token's JTI to the Redis revocation list, and returns `200 OK` with an empty body
#### Scenario: Revocation of already-revoked token is idempotent
- **WHEN** a POST request to `/token/revoke` is received with a token that is already in the Redis revocation list
- **THEN** the system returns `200 OK` with an empty body (no error)
#### Scenario: Missing token parameter rejected
- **WHEN** a POST request to `/token/revoke` is received with no `token` field in the body
- **THEN** the system returns `400 Bad Request` with `code: VALIDATION_ERROR`
### Requirement: JWT claims structure
All issued JWTs SHALL contain the following claims: `sub` (agentId), `client_id` (agentId), `scope` (space-separated granted scopes), `jti` (UUID, unique per token), `iat` (issued-at Unix timestamp), `exp` (expiry Unix timestamp). Tokens SHALL be signed with RS256.
#### Scenario: JWT contains required claims
- **WHEN** a token is issued via `POST /token`
- **THEN** the decoded JWT payload contains `sub`, `client_id`, `scope`, `jti`, `iat`, and `exp` fields
### Requirement: Rate limiting on token endpoints
The system SHALL enforce a rate limit of 100 requests per minute per `client_id` on all token endpoints.
#### Scenario: Rate limit exceeded on token endpoint
- **WHEN** a client sends more than 100 requests to any token endpoint within a 60-second window
- **THEN** the system returns `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining: 0`, and `X-RateLimit-Reset` headers