# BookNest Product Requirements and Automation Context

**Document status:** Implemented-system baseline  
**Product:** BookNest Testing Sandbox  
**API version:** v1  
**Primary purpose:** A fictional bookstore application for evaluating low-code, no-code, AI-assisted, and code-based software-testing tools.

## 1. How to use this document

This document is the normative functional baseline for the currently implemented BookNest PoC. It is written for:

- QA engineers and developers;
- AI coding and testing agents;
- low-code testing tools;
- UI, API, accessibility, resilience, and end-to-end test authors.

The keywords **MUST**, **SHOULD**, and **MAY** express requirement strength. A behavior not described here, in the OpenAPI document, or in an approved change request must not be assumed to be required.

When generated tests and the implementation disagree, record the mismatch instead of silently changing expected behavior. Verify intentional variants such as `?ui=v2` and Test Lab scenarios before classifying a result as a defect.

## 2. Product scope

BookNest provides:

- a responsive customer storefront;
- a synthetic catalogue of 40 books;
- search, filter, sorting, pagination, and book details;
- anonymous and authenticated carts;
- customer registration, login, logout, and one-hour bearer sessions;
- simulated promotions, checkout, orders, cancellation, and inventory restoration;
- a versioned REST API and OpenAPI description;
- isolated test executions identified by a Test Run ID;
- a protected Test Lab for deterministic failure and data scenarios;
- a controlled alternative UI at `?ui=v2` for locator-resilience testing.

BookNest does not process real payments, sell or deliver products, or support real customer data.

## 3. Out of scope and deliberate limitations

The following are not current product requirements:

- real payment processing, tax calculation, fulfilment, email, or SMS;
- real books, authors, ISBNs, customers, addresses, reviews, or transactions;
- social login, MFA, password recovery, or email verification;
- a customer wishlist, despite the decorative save/heart controls;
- real delivery-method or payment-method processing;
- an administration console or catalogue-management UI;
- native iOS or Android applications;
- production-grade authentication, password hashing, or regulatory compliance;
- permanent preservation of PoC data.

The delivery and payment selectors shown during checkout are synthetic UI controls. They do not change the order total and are not submitted to the current order API.

## 4. Actors and access levels

| Actor | Description | Permitted behavior |
| --- | --- | --- |
| Visitor | Unauthenticated storefront user | Browse, search, filter, view books, maintain an anonymous cart, apply promotions, open authentication |
| Customer | Authenticated synthetic user | Visitor behavior plus checkout, order history, cancellation, and logout |
| Test operator | Tester with the Test Lab secret | Read and activate scenarios and reset one isolated test run |
| Automation client | UI or API automation process | Use unique run/client identifiers, exercise supported flows, and use synthetic data only |

## 5. Environments and entry points

| Purpose | Production | Staging |
| --- | --- | --- |
| Storefront | `https://booknest-testing.com` | `https://staging.booknest-testing.com` |
| API documentation | `/api-docs` | `/api-docs` |
| OpenAPI 3.1 JSON | `/api/openapi` | `/api/openapi` |
| Test Lab | `/test-lab` | `/test-lab` |
| API base | `/api/v1` | `/api/v1` |
| Resilience UI | `/?ui=v2` | `/?ui=v2` |

Failure injection, destructive reset, large-data, malformed-response, and concurrency tests SHOULD run against staging. Production testing SHOULD be limited to non-destructive smoke journeys with unique Test Run IDs.

## 6. Global business rules

### BR-001 — Synthetic data only

All data entered into BookNest MUST be synthetic. Users MUST NOT enter real personal, payment, customer, production, confidential, or regulated information.

### BR-002 — Fictional application

BookNest MUST identify itself as demonstration software and MUST NOT imply affiliation with a similarly named company, product, or service.

### BR-003 — USD pricing

The storefront MUST display money using US dollar formatting. Backend monetary values MUST be calculated in integer cents and returned as decimal dollar values.

### BR-004 — Test-run isolation

Mutable state MUST be scoped by a Test Run ID. State from one valid Test Run ID MUST NOT affect another Test Run ID.

### BR-005 — Default run

When no run identifier is supplied, the API MUST use `shared-demo`. Automated tests SHOULD NOT use `shared-demo` because concurrent runs may interfere with one another.

### BR-006 — Scenario exclusivity

At most one Test Lab scenario MAY be active for a Test Run ID at a time.

### BR-007 — Synthetic checkout

Checkout MUST NOT collect real card details, contact a payment provider, initiate a financial transaction, or fulfil an order.

## 7. Catalogue requirements

### CAT-001 — Initial catalogue

The normal catalogue MUST contain 40 deterministic synthetic books across these categories:

`Fiction`, `Mystery`, `Science`, `History`, `Business`, `Design`, `Cooking`, and `Young Adult`.

### CAT-002 — Book information

Each normal book MUST have:

- numeric ID;
- title and author;
- category;
- current price and optional original price;
- rating and review count;
- stock quantity;
- format (`Hardcover`, `Paperback`, or `E-book`);
- publication year;
- synthetic ISBN-like identifier;
- description and cover palette;
- optional badge (`Bestseller`, `New`, or `Staff pick`).

### CAT-003 — Catalogue display

The storefront MUST show book title, author, price, rating, availability, format/category context, and an add action. Out-of-stock books MUST show an unavailable state and MUST NOT be addable.

### CAT-004 — Search

Search MUST be case-insensitive and match title, author, ISBN, or category. Typing more than one character SHOULD display at most five title/author suggestions.

### CAT-005 — Filters

The storefront MUST support:

- category;
- maximum price from `$10` through `$50` in `$1` steps;
- in-stock-only filtering;
- combined filtering with search.

Clearing filters MUST restore the empty query, `All categories`, maximum price `$50`, availability filter off, and `Featured` sorting.

### CAT-006 — Sorting

The storefront MUST support:

- featured;
- price low to high;
- price high to low;
- highest rated;
- newest.

### CAT-007 — Pagination

The storefront MUST display eight matching books per page and MUST reset to page one when search, filter, or sorting criteria change.

### CAT-008 — Empty result

When no books match, the storefront MUST display a no-results state and a control that clears all filters.

### CAT-009 — Product details

Selecting a book MUST open product details containing title, author, category, format, rating, reviews, description, year, ISBN, availability, price, and an add action when stock is available.

### CAT-010 — Catalogue API

`GET /api/v1/books` MUST support query, category, availability, maximum price, sorting, page, and page-size parameters. Page size MUST be constrained to `1..100`.

`GET /api/v1/books/{id}` MUST return the requested book or `404 BOOK_NOT_FOUND`.

## 8. Cart and pricing requirements

### CART-001 — Anonymous cart identity

Anonymous carts MUST be identified by the combination of Test Run ID and `X-Client-Id`. The browser SHOULD retain a stable generated client ID in local storage.

### CART-002 — Add to cart

Adding a book MUST increase its existing quantity by the requested amount. The resulting quantity MUST NOT exceed current stock.

The API MUST return:

- `404 BOOK_NOT_FOUND` for an unknown book;
- `409 OUT_OF_STOCK` for a book with no stock;
- `409 STOCK_LIMIT` when the resulting quantity exceeds stock.

### CART-003 — Set quantity

Setting quantity MUST accept a non-negative integer. Quantity zero MUST remove the line. A negative or non-integer quantity MUST return `422 INVALID_QUANTITY`.

### CART-004 — Remove items

The cart API MUST support removing one book by ID and clearing all books when no ID is supplied.

### CART-005 — Price snapshot

When a book is added or its quantity is updated, the cart MUST store the current unit price as a snapshot for later conflict detection.

### CART-006 — Promotion invalidation

Adding, updating, or removing cart contents MUST clear the applied promotion.

### CART-007 — Totals

The cart MUST calculate:

- `subtotal = sum(price snapshot × quantity)`;
- `discount = 10% of subtotal` when `BOOK10` is valid;
- `shipping = $4.99` when subtotal is greater than `$0` and less than `$40`;
- `shipping = $0` when subtotal is `$40` or more;
- `total = subtotal - discount + shipping`.

### CART-008 — Cross-tab synchronization

Cart updates in one browser tab SHOULD cause another BookNest tab using the same Test Run ID and browser storage context to reload its cart.

## 9. Promotion requirements

### PROMO-001 — Valid promotion

`BOOK10` MUST be case-insensitive and MUST apply a 10% discount to the current cart.

### PROMO-002 — Expired promotion

`EXPIRED20` MUST return `422 PROMOTION_EXPIRED`.

### PROMO-003 — Unknown promotion

Any other promotion code MUST return `422 PROMOTION_UNKNOWN`.

## 10. Registration and authentication requirements

### AUTH-001 — Registration fields

Registration MUST accept first name, last name, email, password, and optional password confirmation.

### AUTH-002 — Registration validation

The API MUST enforce:

- non-empty first and last names;
- a syntactically valid email;
- password length of at least eight characters;
- at least one uppercase letter and one digit;
- matching confirmation when confirmation is supplied;
- email uniqueness within the Test Run ID.

### AUTH-003 — Email normalization

Email addresses MUST be trimmed and stored/compared in lowercase.

### AUTH-004 — Demo customer

The seeded synthetic account MUST be available independently in each Test Run ID:

```text
Email: customer@example.com
Password: Password123!
Name: Alex Morgan
```

The account MAY be created lazily on the first login attempt for that run.

### AUTH-005 — Login

Successful login MUST create a bearer token valid for one hour and return the synthetic user and expiry timestamp. Invalid credentials MUST return `401 INVALID_CREDENTIALS`.

### AUTH-006 — Anonymous-cart merge

Successful login MUST merge the anonymous cart identified by `X-Client-Id` into the authenticated customer cart, then remove the anonymous cart state. The response MUST indicate whether a cart was merged.

### AUTH-007 — Protected operations

Order listing, order creation, and cancellation MUST require a valid, unexpired bearer session from the same Test Run ID.

### AUTH-008 — Logout

Logout MUST invalidate a supplied bearer token when present and MUST be idempotent when no token is supplied.

### AUTH-009 — Browser session behavior

The storefront SHOULD retain the current synthetic bearer token and user in local storage. When an authenticated API request returns `401`, the storefront MUST return to the unauthenticated state and require login again.

## 11. Checkout and order requirements

### ORD-001 — Authentication gate

An unauthenticated user starting checkout MUST be prompted to sign in. After successful authentication, the user SHOULD resume checkout without losing the cart.

### ORD-002 — Delivery fields

Order placement MUST require street address, city, and postal code. Missing fields MUST return `422 DELIVERY_REQUIRED`.

### ORD-003 — Non-empty cart

Checkout with no cart lines MUST return `422 EMPTY_CART`.

### ORD-004 — Idempotency

Order creation MUST accept `Idempotency-Key`. Repeating a request with the same key and Test Run ID MUST return the existing order and MUST NOT create or charge a second order.

### ORD-005 — Price conflict

Checkout MUST compare each current catalogue price with the cart price snapshot. A mismatch MUST return `409 PRICE_CHANGED` with previous and current price information.

### ORD-006 — Inventory conflict

Checkout MUST reject a quantity greater than available stock with `409 INVENTORY_CONFLICT`.

### ORD-007 — Successful order

A successful order MUST:

- use an ID formatted as `BN-<UTC year>-<six digits>`;
- have initial status `Confirmed`;
- persist item quantities and unit-price snapshots;
- decrement inventory;
- clear cart lines and promotion state;
- appear in the authenticated customer's order history;
- return HTTP `201` for first creation.

### ORD-008 — Order history

Order history MUST contain only orders belonging to the authenticated customer and current Test Run ID, newest first.

### ORD-009 — Cancellation

An authenticated customer MAY cancel their own order. Cancellation MUST set status to `Cancelled` and restore item quantities to inventory. Repeating cancellation MUST return success without restoring inventory twice.

An absent order, another customer's order, or an order from another Test Run ID MUST return `404 ORDER_NOT_FOUND`.

## 12. Test-run and reset requirements

### ISO-001 — Run identifier resolution

The backend MUST resolve the Test Run ID in this order:

1. `X-Test-Run-Id` request header;
2. `runId` URL query parameter;
3. `shared-demo`.

Valid IDs are 1–80 characters containing letters, digits, `.`, `_`, `:`, or `-`. Invalid values MUST fall back to `shared-demo`.

### ISO-002 — Isolated entities

Users, sessions, carts, cart items, inventory, orders, and scenario state MUST be isolated by Test Run ID.

### ISO-003 — Storefront reset

The storefront **Reset demo data** action MUST create a new unique manual Test Run ID and clear the current browser session view. It does not delete the previous run from the database.

### ISO-004 — Protected destructive reset

`POST /api/v1/test/reset` MUST require `X-Test-Admin-Key` and MUST delete users, sessions, carts, inventory, orders, order items, and scenario state only for the supplied Test Run ID.

## 13. Test Lab requirements

### LAB-001 — Authorization

Scenario read/write and destructive reset operations MUST require an `X-Test-Admin-Key` value equal to the encrypted deployment secret `BOOKNEST_TEST_ADMIN_KEY`.

The secret MUST NOT be committed to source control, placed in URLs, or included in screenshots and public test artifacts.

### LAB-002 — Test Lab secret handling

The Test Lab UI MUST keep the entered admin key only in the current in-memory browser state. It MUST NOT save the key to local storage.

### LAB-003 — Scenario storage

The active scenario, normalized settings, request count, and update time MUST be stored per Test Run ID.

### LAB-004 — Parameter validation

The scenario API MUST:

- reject unsupported scenario names with `422 UNKNOWN_SCENARIO`;
- discard unsupported setting keys;
- fill missing values with documented defaults;
- clamp numeric values to documented minimum and maximum values;
- trim text and limit it to 240 characters.

### LAB-005 — Supported scenarios

| Scenario | Behavior | Adjustable settings |
| --- | --- | --- |
| `normal` | Normal business behavior | None |
| `slow-api` | Adds a deterministic response delay | `delayMs` (`0..15000`, default `2000`) |
| `intermittent-error` | Fails every Nth business request | `failEvery` (`1..20`, default `2`), `statusCode` (`500..599`, default `500`) |
| `service-unavailable` | Returns a configured server error | `statusCode` (`500..599`, default `503`), `message` |
| `rate-limited` | Returns `429` after the allowed count | `requestsBeforeLimit` (`0..100`, default `3`), `retryAfterSeconds` (`1..3600`, default `10`) |
| `expired-session` | Makes authenticated operations return `401` after the threshold | `expireAfterRequests` (`0..100`, default `0`) |
| `inventory-conflict` | Makes checkout report a final-copy conflict | `bookId` (`1..40`, default `13`) |
| `price-change` | Makes checkout report a changed price | `bookId` (`0..40`, default `0`), `increaseCents` (`1..10000`, default `250`) |
| `payment-decline` | Makes checkout return a synthetic decline | `declineCode`, `message` |
| `partial-response` | Removes selected optional catalogue fields | `omitFields`, default `description,badge` |
| `empty-catalogue` | Returns a valid empty catalogue | None |
| `large-catalogue` | Generates a deterministic large catalogue | `itemCount` (`40..5000`, default `1000`) |
| `malformed-response` | Returns invalid catalogue response types | None |

### LAB-006 — Request count semantics

Business API calls that apply scenarios MUST increment the scenario request counter. Initial storefront catalogue and cart calls count toward intermittent, rate-limit, and session-expiry thresholds.

### LAB-007 — Scenario targeting

- General transport scenarios SHOULD affect catalogue, authentication, cart, promotion, order, and cancellation APIs that invoke the common scenario handler.
- Catalogue-data scenarios MUST affect catalogue responses.
- `inventory-conflict`, `price-change`, and `payment-decline` MUST affect order creation.
- `expired-session` MUST affect authenticated session resolution.

## 14. Intentional Defects Mode requirements

Intentional Defects Mode is an opt-in test fixture for evaluating whether QA engineers, AI agents, and low-code testing tools can detect, classify, explain, and recover from known product defects. It deliberately changes selected outcomes while keeping the normal BookNest experience defect-free. It is not a random fault injector: every defect has a stable identifier and repeatable behavior so results can be compared across tools and executions.

### DEF-001 — Activation and supported packs

The storefront MUST activate Intentional Defects Mode only through the comma-separated `defects` query parameter. API clients MUST be able to activate the same packs through either the query parameter or the `X-Test-Defects` header.

Examples:

```text
/?defects=smoke
/?defects=ui,functional
/api/v1/books?defects=api
X-Test-Defects: api,state
```

The following packs and stable defect identifiers MUST be supported:

| Pack | Testing purpose | Included defects |
| --- | --- | --- |
| `smoke` | Detect obvious failures in critical navigation and purchase paths | `DEF-NAV-001`, `DEF-SEARCH-001`, `DEF-CART-001`, `DEF-AUTH-001`, `DEF-CHECKOUT-001` |
| `ui` | Detect visual overlap, alignment, clipping, and responsive regressions | `DEF-UI-001`, `DEF-UI-002`, `DEF-UI-003`, `DEF-UI-004`, `DEF-UI-005` |
| `functional` | Detect incorrect cart and promotion behavior | `DEF-CART-002`, `DEF-CART-003`, `DEF-CART-004`, `DEF-PROMO-001`, `DEF-PROMO-002` |
| `validation` | Detect malformed or incomplete input accepted by forms and APIs | `DEF-FORM-001`, `DEF-FORM-002`, `DEF-FORM-003`, `DEF-FORM-004`, `DEF-FORM-005` |
| `api` | Detect contract violations involving status, fields, types, not-found responses, and idempotency | `DEF-API-001`, `DEF-API-003`, `DEF-API-005`, `DEF-API-006`, `DEF-API-007` |
| `state` | Detect failures spanning sessions, tabs, carts, inventory, and price changes | `DEF-STATE-001`, `DEF-STATE-003`, `DEF-STATE-004`, `DEF-STATE-005`, `DEF-STATE-006` |

### DEF-002 — Normal-mode isolation

Requests without a supported `defects` value MUST retain the documented normal behavior. Activating defects for one browser URL or API request MUST NOT globally enable them for other users or test runs.

### DEF-003 — Transparency and machine-readable evidence

Every intentional defect MUST define a stable identifier, title, expected behavior, and deliberately defective behavior. The storefront MUST show an **Intentional defect mode** banner and expose active pack names and defect IDs through `data-defect-packs` and `data-defect-ids` on the application root.

### DEF-004 — Determinism and reversibility

The same pack, input, state, and Test Run ID MUST produce the same intentional behavior, except for identifiers and timestamps already documented as dynamic. Removing the `defects` parameter or `X-Test-Defects` header MUST restore normal behavior without a database reset.

### DEF-005 — Pack composition and invalid values

Multiple supported packs MAY be combined with commas. Duplicate names MUST activate a pack only once. Names MUST be matched case-insensitively after surrounding whitespace is removed. Unknown or empty pack names MUST be ignored and MUST NOT produce an application error.

### DEF-006 — Browser-to-API propagation

When the storefront is opened with active packs, its business API requests MUST send the equivalent `X-Test-Defects` value. Direct API tests MAY use either the header or query parameter. If both are supplied, the header MUST take precedence.

### DEF-007 — Discovery and Test Lab integration

The Test Lab MUST list all supported packs, descriptions, stable IDs, and launch links without requiring the admin key. `GET /api/v1/test/defects` MUST return the same machine-readable catalogue plus the packs and IDs active for that request.

### DEF-008 — Compatibility with scenarios and UI resilience mode

Intentional defect packs MUST remain separate from persisted Test Lab scenarios. Activating or disabling a pack MUST NOT change the stored scenario or scenario request counter. Packs MAY be combined with `?ui=v2` and a Test Run ID, for example `/?ui=v2&runId=poc-001&defects=ui,functional`.

### DEF-009 — Security and data constraints

Defect activation MUST NOT require, transmit, display, or persist `BOOKNEST_TEST_ADMIN_KEY`. It MUST NOT disable the synthetic-data notice, introduce real payment processing, expose secrets, weaken run isolation, or mutate state outside the supplied Test Run ID.

### DEF-010 — Recommended QA execution workflow

QA engineers and automation tools SHOULD:

1. execute the target journey without defect activation and record a passing baseline;
2. rerun it with exactly one defect pack and a clean Test Run ID;
3. map each observed failure to a documented `DEF-*` identifier;
4. capture evidence, expected behavior, actual behavior, and recovery diagnostics;
5. remove defect activation and confirm that the baseline passes again;
6. combine packs only after independent pack coverage is understood.

## 15. Resilience UI requirements

### UI-001 — Mode activation

The storefront MUST activate resilience mode only when the URL contains `ui=v2`. The root element MUST expose `data-ui-version="v1"` or `data-ui-version="v2"`.

### UI-002 — Business equivalence

The default UI and `?ui=v2` MUST preserve catalogue data, search results, pricing, stock rules, authentication, cart, promotions, checkout, orders, stable test IDs, and accessible action intent.

### UI-003 — Intentional presentation changes

`?ui=v2` intentionally changes:

- header action order;
- search placeholder and styling;
- catalogue headings;
- filter position and category control type;
- mobile filter side and wording;
- result-toolbar order;
- product-card layout and DOM hierarchy;
- selected labels, icons, and action wording;
- checkout action wording.

Tests SHOULD assert business outcomes rather than depend exclusively on visible copy, CSS classes, child positions, or brittle XPath expressions.

### UI-004 — Stable hooks

The following stable UI hooks are currently available:

- `data-testid="search-input"`;
- `data-testid="book-grid"`;
- `data-testid="book-card-<bookId>"`;
- `data-testid="add-to-cart-<bookId>"`;
- `data-testid="checkout-button"`;
- `data-testid="place-order-button"`.

Accessible names SHOULD be preferred where they express user intent and remain equivalent across modes.

## 16. API requirements

### API-001 — Versioning and discovery

Business endpoints MUST use `/api/v1`. `/api/openapi` MUST generate an OpenAPI 3.1 document using the hostname of the current request.

### API-002 — Response format

JSON responses MUST use `application/json; charset=utf-8` and `cache-control: no-store`.

### API-003 — Error contract

Handled errors MUST use this shape:

```json
{
  "error": {
    "status": 422,
    "code": "EXAMPLE_CODE",
    "message": "Human-readable explanation.",
    "details": null
  },
  "traceId": "generated-uuid"
}
```

Malformed JSON MUST return `400 INVALID_JSON`.

### API-004 — Endpoint inventory

| Method | Endpoint | Purpose | Authorization |
| --- | --- | --- | --- |
| GET | `/health` | Service health | Public |
| GET | `/books` | Catalogue search/filter/sort/page | Public |
| GET | `/books/{id}` | Book details | Public |
| POST | `/auth/register` | Register synthetic customer | Public |
| POST | `/auth/login` | Create bearer session and merge cart | Public |
| POST | `/auth/logout` | Invalidate bearer session | Optional bearer |
| GET | `/cart` | Read current cart | Anonymous or bearer |
| POST | `/cart` | Add book quantity | Anonymous or bearer |
| PATCH | `/cart` | Set book quantity | Anonymous or bearer |
| DELETE | `/cart` | Remove one or all cart items | Anonymous or bearer |
| POST | `/promotions/validate` | Validate/apply promotion | Anonymous or bearer |
| GET | `/orders` | List customer orders | Bearer required |
| POST | `/orders` | Create idempotent order | Bearer required |
| POST | `/orders/{id}/cancel` | Cancel order and restore stock | Bearer required |
| GET | `/test/defects` | Discover defect packs and active IDs | Public |
| GET | `/test/scenario` | Read scenario definitions/state | Test admin key required |
| POST | `/test/scenario` | Activate scenario/settings | Test admin key required |
| POST | `/test/reset` | Delete one run's synthetic state | Test admin key required |

Detailed bodies, examples, and status codes are maintained at `/api-docs` and `/api/openapi`.

## 17. AI and automation context

### AI-001 — Available browser model-context tools

When the browser exposes `document.modelContext`, the storefront SHOULD register:

| Tool | Behavior |
| --- | --- |
| `search_books` | Sets the visible catalogue query and returns the number of matching books |
| `add_book_to_cart` | Adds one available book by numeric ID |
| `reset_booknest_demo` | Creates a fresh isolated browser run |

### AI-002 — Agent safety rules

Agents and automation tools MUST:

- use synthetic data only;
- prefer staging for destructive and failure tests;
- use a unique Test Run ID per execution or parallel worker;
- keep `X-Test-Run-Id` identical across setup, UI, API, and cleanup steps;
- keep a stable `X-Client-Id` through anonymous-cart and login-merge steps;
- never print, commit, record, or place `X-Test-Admin-Key` in a URL;
- restore the scenario to `normal` or reset the run after failure-injection tests;
- treat dynamic UUIDs, tokens, timestamps, and order numbers as patterns rather than fixed values;
- account for initial page-load requests when using request-count scenarios;
- use the same business assertions against the default UI and `?ui=v2`.

### AI-003 — Preferred locator strategy

Automation SHOULD prefer, in order:

1. accessible role and accessible name;
2. stable `data-testid` hooks;
3. semantic labels and nearby business context;
4. visible text when wording is part of the requirement.

Automation SHOULD avoid generated CSS classes, absolute XPath, DOM child indexes, and assumptions that v1/v2 share identical visible text or hierarchy.

### AI-004 — Dynamic values

Tests MUST NOT hard-code:

- bearer tokens;
- generated user IDs;
- session-expiry timestamps;
- order numbers;
- trace IDs;
- scenario update timestamps.

Tests SHOULD extract and reuse these values or validate their documented formats.

## 18. Non-functional requirements

### NFR-001 — Responsive behavior

The storefront, API documentation, About page, and Test Lab MUST remain usable at desktop and mobile viewport sizes. Mobile filters MUST be available through a side panel.

### NFR-002 — Accessibility baseline

Interactive controls SHOULD expose meaningful accessible names. Dialogs, sheets, forms, alerts, listboxes, checkboxes, radios, selects, and buttons SHOULD be keyboard-operable and programmatically identifiable.

### NFR-003 — Determinism

Seed catalogue values and Test Lab scenarios MUST be deterministic for identical inputs, except explicitly dynamic identifiers and timestamps.

### NFR-004 — Parallel testability

Independent automation executions MUST be able to run in parallel using different Test Run IDs without state collision.

### NFR-005 — Security boundary

Test-control APIs MUST reject a missing or incorrect admin key with `403 ADMIN_KEY_REQUIRED`. Sensitive deployment secrets MUST be stored as encrypted runtime secrets, not repository variables.

### NFR-006 — Cache behavior

API responses MUST not be cached. Test tools SHOULD isolate learned locators/caches between environments when DOM or configuration differs.

### NFR-007 — Failure observability

The storefront MUST show observable error feedback for catalogue, cart, authentication, promotion, checkout, and order failures. Catalogue failure MUST offer a retry action.

## 19. Canonical test data

| Item | Value | Expected result |
| --- | --- | --- |
| Demo email | `customer@example.com` | Existing synthetic customer per run |
| Demo password | `Password123!` | Successful login |
| Valid promotion | `BOOK10` | 10% discount |
| Expired promotion | `EXPIRED20` | `422 PROMOTION_EXPIRED` |
| Unknown promotion | `INVALID` | `422 PROMOTION_UNKNOWN` |
| Out-of-stock books | IDs `8` and `24` | Add rejected |
| Low-stock book | ID `13` | One copy in initial inventory |
| Example searchable book | ID `10`, `The Quiet Algorithm` by `Daniel Cho` | Catalogue and details result |

## 20. Critical acceptance journeys

### E2E-001 — Anonymous purchase continuation

1. Start with a unique Test Run ID and client ID.
2. Add an available book anonymously.
3. Start checkout.
4. Sign in using the demo account.
5. Verify anonymous cart merge and preserved checkout intent.
6. Submit synthetic delivery information.
7. Verify one confirmed order, cleared cart, order history, and reduced stock.

### E2E-002 — Registration and checkout

1. Register a unique synthetic customer.
2. Verify automatic login through the storefront flow.
3. Add books and apply `BOOK10`.
4. Verify subtotal, discount, shipping, and total.
5. Place the order and verify its dynamic ID and persisted history.

### E2E-003 — Idempotent order

1. Prepare an authenticated cart.
2. Submit the same order twice using one Idempotency-Key.
3. Verify only one order exists and the replay reports the existing order.

### E2E-004 — Cancellation

1. Create an order.
2. Record post-purchase inventory.
3. Cancel the order.
4. Verify `Cancelled` status and restored inventory.
5. Cancel again and verify inventory is not restored twice.

### E2E-005 — Price conflict and recovery

1. Add a book to the cart.
2. Activate `price-change` for the same Test Run ID.
3. Attempt checkout and verify `409 PRICE_CHANGED`.
4. Return the scenario to `normal` and refresh the cart price.
5. Complete checkout successfully.

### E2E-006 — UI resilience

1. Execute catalogue search, add-to-cart, login, and checkout in v1.
2. Execute the same business journey with `?ui=v2` and a clean run.
3. Verify equivalent outcomes despite wording, layout, control-type, and DOM changes.

### E2E-007 — Isolation

1. Create state under run A.
2. Open run B with the same browser/client identity.
3. Verify run B cannot see run A's user, cart, inventory, order, or scenario state.

### E2E-008 — API resilience

1. Activate each transport scenario through the protected scenario API.
2. Exercise the matching business endpoint using the same Test Run ID.
3. Verify status, response contract, delay/header behavior, UI feedback, and retry/recovery.
4. Reset the run during teardown.

### E2E-009 — Intentional defect detection

1. Execute the baseline smoke flow without a `defects` parameter and verify it passes.
2. Repeat the flow with `?defects=smoke` and verify the five documented failures are detected and mapped to their stable defect IDs.
3. Exercise each remaining pack independently using a clean Test Run ID.
4. Activate the API pack through `X-Test-Defects: api` and verify contract tests report the documented status, missing-field, type, not-found, and idempotency violations.
5. Remove defect activation and verify the baseline passes again without resetting stored scenario state.

## 21. Requirement change rules

Any change that affects business outcomes, API contracts, test data, accessible intent, stable hooks, scenario definitions, or v1/v2 equivalence SHOULD update this document in the same pull request.

New planned capabilities—such as an administration console, editable catalogue, user management, promotion management, email, files, PWA, or native mobile applications—MUST be documented as future scope until their implementation and acceptance criteria are complete.
