<!--
  RQML (Requirements Markup Language) Schema v2.1.0
  =================================================

  PURPOSE
  =======
  RQML is an XML-based format for capturing software requirements in a structured,
  machine-readable way. It is designed for LLM-native workflows where:

  1. Requirements are the primary artifact (not code)
  2. LLMs use requirements to generate and validate implementations
  3. Traceability from goals to tests is explicit and queryable
  4. Human collaboration happens on intent; implementation is derived

  FOR LLMs: REQUIREMENTS ELICITATION
  ==================================
  When helping users write RQML documents:

  - Start with `meta` (required): capture document identity, ownership, and conventions
  - Add `catalogs` early: define glossary terms, actors, stakeholders, constraints, and
    risks to establish shared vocabulary and reduce ambiguity in requirements
  - Use `domain` to model key entities and business rules that requirements reference
  - Capture `goals` to document WHY the system exists (business objectives, quality goals)
  - Write `scenarios` to describe HOW users interact with the system (use cases, misuse cases)
  - Derive `requirements` from goals and scenarios - each requirement should be:
    * Necessary (traces to a goal or stakeholder need)
    * Verifiable (has acceptance criteria or can be tested)
    * Unambiguous (single interpretation)
    * Feasible (technically achievable)
  - Use `behavior` to formalize entity lifecycles as state machines (derived from requirements)
  - Document `interfaces` for system boundaries (APIs, events)
  - Add `verification` to define how requirements are tested
  - Create `trace` edges to link artifacts for impact analysis
  - Use `governance` for approval workflows and open issues

  FOR LLMs: CODE GENERATION
  =========================
  When generating code from RQML documents:

  - Read `domain/entities` for data models (classes, database schemas, types)
  - Read `domain/businessRules` for validation logic and constraints
  - Read `behavior/stateMachine` for state enums, transition logic, and lifecycle validation
  - Read `requirements` with type="FR" for features to implement
  - Read `requirements` with type="NFR" for quality attributes (performance, reliability)
  - Read `requirements` with type="IR" for API contracts and integrations
  - Read `requirements` with type="DR" for data validation rules
  - Read `requirements` with type="SR" for security controls
  - Read `interfaces/api/endpoint` for REST/HTTP endpoint implementations
  - Read `interfaces/event` for event handlers and message schemas
  - Use `acceptance/criterion` (given/when/then) for test case generation
  - Check `trace` edges with type="implements" for code-to-requirement mapping

  DOCUMENT STRUCTURE (in order)
  =============================
  1. meta (REQUIRED) - Document identity and metadata
  2. catalogs - Shared definitions: glossary, actors, stakeholders, constraints, policies, decisions, risks
  3. domain - Problem space: entities, attributes, business rules
  4. goals - Objectives: business goals, quality goals, obstacles, goal links
  5. scenarios - User journeys: use cases, misuse cases, edge cases
  6. requirements (REQUIRED) - Normative statements: packages and individual requirements
  7. behavior - State machines: formalized entity lifecycles derived from requirements
  8. interfaces - System boundaries: APIs, endpoints, events
  9. verification - Testing: test suites and test cases
  10. trace - Traceability: edges linking all artifacts
  11. governance - Change control: issues and approvals

  ID CONVENTIONS
  ==============
  All IDs must be unique within the document. Recommended patterns:
  - Requirements: REQ-<AREA>-NNN (e.g., REQ-AUTH-001)
  - Goals: GOAL-<AREA>-NNN (e.g., GOAL-AVAIL-001)
  - Quality Goals: QGOAL-<NAME> (e.g., QGOAL-LATENCY)
  - Test Cases: TC-<NAME>-NNN (e.g., TC-AUTH-001)
  - Entities: ENT-<NAME> (e.g., ENT-PAYMENT)
  - Actors: ACT-<NAME> (e.g., ACT-USER)
  - Stakeholders: STK-<NAME> (e.g., STK-RISK)
  - Scenarios: SCN-<NAME> (e.g., SCN-CHECKOUT)
  - Risks: RISK-<NAME> (e.g., RISK-FRAUD)
  - Decisions: DEC-<NAME> (e.g., DEC-IDEMPOTENCY)
  - State Machines: SM-<NAME> (e.g., SM-ORDER)
  - States: ST-<NAME> (e.g., ST-PENDING, ST-CONFIRMED)
  - Transitions: TR-<NAME> (e.g., TR-CONFIRM, TR-SHIP)

  STANDARDS ALIGNMENT
  ===================
  RQML aligns with requirements engineering best practices from:
  - IEEE 29148-2018: Systems and software engineering - Life cycle processes - Requirements engineering
  - ISO/IEC 25010: Systems and software quality models
  - KAOS/i* goal-oriented RE frameworks
  - Volere requirements template
  - BDD/Gherkin for acceptance criteria

  NAMESPACE: https://rqml.org/schema/2.1.0
-->
<xs:schema
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  targetNamespace="https://rqml.org/schema/2.1.0"
  xmlns="https://rqml.org/schema/2.1.0"
  elementFormDefault="qualified"
  attributeFormDefault="unqualified"
  version="2.1.0">

  <!-- =========================
       Simple types

       These define the controlled vocabularies and value constraints
       used throughout RQML. LLMs should use these exact values.
       ========================= -->

  <!--
    IdType: Identifier format for all referenceable elements

    Pattern: Start with letter, followed by letters, digits, dots, underscores, or hyphens
    Length: 2-80 characters

    EXAMPLES:
    - REQ-AUTH-001 (requirement)
    - GOAL-AVAIL (goal)
    - ENT-PAYMENT (entity)
    - ACT-USER (actor)
    - TC-LOGIN-001 (test case)

    FOR LLMs: When creating IDs, use descriptive prefixes that indicate the element type,
    followed by a meaningful name or area, optionally with a sequence number.
    Keep IDs stable across document revisions for traceability.
  -->
  <xs:simpleType name="IdType">
    <xs:restriction base="xs:token">
      <!-- Human-friendly IDs like REQ-LOGIN-001, GOAL_AUTH_01, TC-001 -->
      <xs:pattern value="[A-Za-z][A-Za-z0-9._-]*"/>
      <xs:minLength value="2"/>
      <xs:maxLength value="80"/>
    </xs:restriction>
  </xs:simpleType>

  <!--
    StatusType: Lifecycle state of requirements, goals, decisions, and other artifacts

    VALUES:
    - draft: Initial state; content is incomplete or unreviewed
    - review: Under stakeholder review; awaiting feedback or approval
    - approved: Formally accepted; ready for implementation
    - deprecated: No longer active; kept for historical reference

    FOR LLMs:
    - When eliciting requirements, start with status="draft"
    - Only requirements with status="approved" should drive implementation
    - Deprecated items should not be implemented but may explain historical decisions
  -->
  <xs:simpleType name="StatusType">
    <xs:restriction base="xs:token">
      <xs:enumeration value="draft"/>
      <xs:enumeration value="review"/>
      <xs:enumeration value="approved"/>
      <xs:enumeration value="deprecated"/>
    </xs:restriction>
  </xs:simpleType>

  <!--
    PriorityType: MoSCoW-style priority for requirements and goals

    VALUES (from RFC 2119 / IEEE 29148):
    - must: Mandatory; system is unacceptable without this. Non-negotiable for MVP.
    - should: Important; system is diminished without this. Include if feasible.
    - may: Optional; nice to have. Include if time/budget permits.

    FOR LLMs:
    - When generating code, implement all "must" requirements first
    - "should" requirements are strong candidates for the implementation
    - "may" requirements can be deferred or simplified
    - When eliciting, ask stakeholders to prioritize ruthlessly - too many "must" items
      indicates poor prioritization
  -->
  <xs:simpleType name="PriorityType">
    <xs:restriction base="xs:token">
      <xs:enumeration value="must"/>
      <xs:enumeration value="should"/>
      <xs:enumeration value="may"/>
    </xs:restriction>
  </xs:simpleType>

  <!--
    ReqType: Classification of requirement types

    This taxonomy helps organize requirements and determines how they should be
    implemented and verified. Each type has distinct characteristics:

    VALUES:
    - FR (Functional Requirement): What the system must DO
      * Features, behaviors, business functions, use case realizations
      * Example: "The system SHALL allow users to reset their password via email"
      * Code: Application logic, controllers, services, business rules

    - NFR (Non-Functional Requirement): How WELL the system must perform
      * Quality attributes: performance, reliability, scalability, usability, maintainability
      * Example: "The API SHALL respond within 200ms for 95th percentile requests"
      * Code: Caching, indexing, async processing, architecture decisions

    - IR (Interface Requirement): Contracts with external systems
      * APIs, protocols, message formats, integration points
      * Example: "The system SHALL expose a REST API conforming to OpenAPI 3.0"
      * Code: API controllers, serializers, protocol handlers, SDK clients

    - DR (Data Requirement): Data structure and handling rules
      * Data models, validation, retention, privacy classification
      * Example: "Payment card numbers SHALL be stored encrypted using AES-256"
      * Code: Database schemas, models, validators, data access layers

    - SR (Security Requirement): Security controls and protections
      * Authentication, authorization, encryption, audit logging, threat mitigations
      * Example: "The system SHALL enforce MFA for administrative operations"
      * Code: Auth middleware, encryption utilities, audit loggers, security filters

    - CR (Constraint Requirement): Hard limits on the solution space
      * Technology mandates, platform requirements, standards compliance
      * Example: "The system SHALL run on Kubernetes 1.28+"
      * Code: Deployment configurations, technology choices, compatibility layers

    - PR (Policy/Compliance Requirement): Regulatory and policy obligations
      * GDPR, HIPAA, PCI-DSS, SOX, internal policies
      * Example: "The system SHALL retain audit logs for 7 years per SOX requirements"
      * Code: Compliance features, audit trails, data retention, reporting

    - UXR (User Experience Requirement): UI and interaction expectations
      * Accessibility, internationalization, content, visual design, user flows
      * Example: "The application SHALL meet WCAG 2.1 Level AA accessibility"
      * Code: UI components, accessibility attributes, i18n, responsive design

    - OR (Operational Requirement): Run and maintain the system
      * Monitoring, logging, alerting, backups, disaster recovery, runbooks
      * Example: "The system SHALL emit structured logs to the central logging platform"
      * Code: Logging configuration, metrics endpoints, health checks, backup scripts

    FOR LLMs:
    - When eliciting requirements, ensure coverage across relevant types
    - FR requirements are the primary drivers of application code
    - NFR requirements shape architecture and infrastructure
    - Use the type to determine which team or component owns implementation
  -->
  <xs:simpleType name="ReqType">
    <xs:restriction base="xs:token">
      <xs:enumeration value="FR"/>
      <xs:enumeration value="NFR"/>
      <xs:enumeration value="IR"/>
      <xs:enumeration value="DR"/>
      <xs:enumeration value="SR"/>
      <xs:enumeration value="CR"/>
      <xs:enumeration value="PR"/>
      <xs:enumeration value="UXR"/>
      <xs:enumeration value="OR"/>
    </xs:restriction>
  </xs:simpleType>

  <!--
    TraceType: Relationship types for traceability links between artifacts

    Traceability enables impact analysis ("what breaks if this changes?") and
    coverage analysis ("is this goal satisfied?"). Choose the most specific type.

    VALUES:
    - refines: Source provides more detail for target (goal decomposition)
      * Example: Sub-goal refines parent goal; detailed req refines high-level req
      * Direction: child -> parent (more specific refines less specific)

    - satisfies: Source fulfills or achieves the target
      * Example: Requirement satisfies goal; implementation satisfies requirement
      * Direction: solution -> need (what satisfies why)

    - dependsOn: Source requires target to function
      * Example: Feature depends on infrastructure; requirement depends on constraint
      * Direction: dependent -> dependency (what needs what)

    - conflictsWith: Source and target cannot both be fully achieved
      * Example: Performance goal conflicts with detailed logging goal
      * Direction: bidirectional (both conflict with each other)

    - threatens: Source poses risk to achieving target
      * Example: Obstacle threatens goal; risk threatens requirement
      * Direction: threat -> threatened (what endangers what)

    - mitigates: Source reduces the impact or likelihood of target threat
      * Example: Requirement mitigates risk; control mitigates obstacle
      * Direction: mitigation -> threat (what addresses what)

    - verifiedBy: Source is validated by target test/inspection
      * Example: Requirement verifiedBy test case
      * Direction: requirement -> verification (what is proven by what)

    - covers: Source test addresses target requirement/scenario
      * Example: Test case covers requirement; test suite covers scenario
      * Direction: test -> requirement (what validates what)

    - implements: Source code/component realizes target requirement
      * Example: Module implements requirement (reserved for tooling)
      * Direction: implementation -> requirement
      * NOTE: This type is primarily for downstream tools that track code-to-requirement mapping

    - supersedes: Source replaces target (for deprecation/versioning)
      * Example: REQ-AUTH-002 supersedes REQ-AUTH-001 after security audit
      * Direction: replacement -> deprecated (new replaces old)
      * Use when archiving requirements: mark old as deprecated, link new via supersedes

    - consumesInterface: Source consumes interface provided by target
      * Example: System A consumesInterface API provided by System B
      * Direction: consumer -> provider
      * Use for cross-system dependency mapping

    - providesInterface: Source provides interface consumed by target
      * Example: System A providesInterface consumed by System B
      * Direction: provider -> consumer
      * Inverse of consumesInterface; use for contract ownership

    - conformsTo: Source conforms to standard or specification target
      * Example: Requirement conformsTo ISO 27001 control
      * Direction: conforming artifact -> standard/specification
      * Use with external locator for standards URIs

    - deprecates: Source deprecates target (lifecycle management)
      * Example: REQ-AUTH-002 deprecates REQ-AUTH-001
      * Direction: new artifact -> deprecated artifact
      * Stronger than supersedes; target should be removed

    - breaks: Source breaks backward compatibility with target
      * Example: API-V2 breaks API-V1 contract
      * Direction: breaking artifact -> broken artifact
      * Use for change management and migration planning

    FOR LLMs:
    - Use trace edges to answer "why does this exist?" (follow satisfies/refines up)
    - Use trace edges to answer "what depends on this?" (follow dependsOn/implements down)
    - When generating code, create implements edges to maintain traceability
    - When writing tests, create verifiedBy/covers edges to requirements
    - Use consumesInterface/providesInterface for cross-system contract mapping
    - Use conformsTo for compliance traceability to standards
    - Use deprecates/breaks for change management and API evolution
  -->
  <xs:simpleType name="TraceType">
    <xs:restriction base="xs:token">
      <xs:enumeration value="refines"/>
      <xs:enumeration value="satisfies"/>
      <xs:enumeration value="dependsOn"/>
      <xs:enumeration value="conflictsWith"/>
      <xs:enumeration value="threatens"/>
      <xs:enumeration value="mitigates"/>
      <xs:enumeration value="verifiedBy"/>
      <xs:enumeration value="covers"/>
      <!-- reserved for downstream tooling -->
      <xs:enumeration value="implements"/>
      <!-- lifecycle management -->
      <xs:enumeration value="supersedes"/>
      <!-- cross-project / contract semantics -->
      <xs:enumeration value="consumesInterface"/>
      <xs:enumeration value="providesInterface"/>
      <xs:enumeration value="conformsTo"/>
      <!-- change management -->
      <xs:enumeration value="deprecates"/>
      <xs:enumeration value="breaks"/>

    </xs:restriction>
  </xs:simpleType>

  <!--
    TestType: Classification of verification activities

    Different test types validate different aspects of the system and run at
    different phases of development.

    VALUES:
    - acceptance: Validates business requirements from user perspective
      * Typically derived from acceptance criteria (given/when/then)
      * Stakeholder-facing; often automated as end-to-end tests
      * Example: "User can complete checkout flow"

    - integration: Validates interactions between components/systems
      * Tests API contracts, database interactions, external service calls
      * Example: "Payment service correctly calls bank API"

    - unit: Validates individual functions/methods/classes in isolation
      * Fast, numerous, developer-facing
      * Example: "calculateTotal returns correct sum with discounts"

    - security: Validates security controls and identifies vulnerabilities
      * Penetration testing, vulnerability scanning, auth testing
      * Example: "SQL injection attempts are blocked"

    - performance: Validates speed, throughput, and resource usage
      * Load testing, stress testing, benchmarking
      * Example: "System handles 1000 concurrent users with <500ms response"

    - inspection: Manual review or audit (non-automated verification)
      * Code review, design review, compliance audit
      * Example: "Security architect reviews authentication design"

    FOR LLMs:
    - Generate acceptance tests from requirement acceptance criteria
    - Generate unit tests for individual functions in generated code
    - Generate integration tests for API endpoints and external calls
    - Map NFR requirements to performance tests
    - Map SR requirements to security tests
  -->
  <xs:simpleType name="TestType">
    <xs:restriction base="xs:token">
      <xs:enumeration value="acceptance"/>
      <xs:enumeration value="integration"/>
      <xs:enumeration value="unit"/>
      <xs:enumeration value="security"/>
      <xs:enumeration value="performance"/>
      <xs:enumeration value="inspection"/>
    </xs:restriction>
  </xs:simpleType>

  <!--
    ConfidenceType: Probability/certainty level for trace links and estimates

    Range: 0.0 to 1.0 (0% to 100% confidence)

    INTERPRETATION:
    - 1.0: Certain; formally verified or definitionally true
    - 0.8-0.99: High confidence; strong evidence or expert judgment
    - 0.5-0.79: Medium confidence; reasonable belief with some uncertainty
    - 0.2-0.49: Low confidence; tentative or speculative
    - 0.0-0.19: Very low confidence; placeholder or assumption needing validation

    FOR LLMs:
    - Use confidence on trace edges to indicate strength of relationship
    - Lower confidence links should be flagged for stakeholder review
    - When eliciting, ask about confidence when relationships are uncertain
    - When analyzing impact, weight changes by confidence of affected links
  -->
  <xs:simpleType name="ConfidenceType">
    <xs:restriction base="xs:decimal">
      <xs:minInclusive value="0.0"/>
      <xs:maxInclusive value="1.0"/>
    </xs:restriction>
  </xs:simpleType>

  <!--
    StateKindType: Classification of states in a state machine

    VALUES:
    - initial: The starting state; exactly one per state machine
    - normal: Regular intermediate state (default)
    - final: Terminal state; no outgoing transitions allowed

    FOR LLMs:
    - Every state machine must have exactly one initial state
    - Final states represent completed lifecycles
    - Normal states are the default; omit the attribute for normal states
  -->
  <xs:simpleType name="StateKindType">
    <xs:restriction base="xs:token">
      <xs:enumeration value="initial"/>
      <xs:enumeration value="normal"/>
      <xs:enumeration value="final"/>
    </xs:restriction>
  </xs:simpleType>

  <!-- =========================
       Reusable complex types

       Building blocks used by multiple sections of the schema.
       ========================= -->

  <!--
    TextBlockType: Rich text content container

    Allows mixed content (text with embedded elements) for descriptions,
    statements, rationales, and other narrative content.

    FOR LLMs:
    - Can contain plain text or simple markup
    - Use for any prose content: descriptions, rationales, notes
    - Keep content concise but complete
    - In statements, use normative language: "SHALL", "SHOULD", "MAY" (RFC 2119)
  -->
  <xs:complexType name="TextBlockType" mixed="true">
    <xs:sequence>
      <xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
    </xs:sequence>
  </xs:complexType>

  <!-- =========================
       Root Element

       The rqml element is the document root. It enforces:
       1. Required version and document identity
       2. Unique IDs across all elements (via xs:key)
       3. Referential integrity for trace edges (via xs:keyref)
       ========================= -->

  <!--
    rqml: Root element of an RQML document

    REQUIRED ATTRIBUTES:
    - version: Schema version (fixed at "2.1.0")
    - docId: Unique document identifier; keep stable across revisions
    - status: Document lifecycle state (draft/review/approved/deprecated)

    STRUCTURE:
    Contains sections in fixed order: meta, catalogs?, domain?, goals?,
    scenarios?, requirements, behavior?, interfaces?, verification?, trace?, governance?

    CONSTRAINTS:
    - All @id attributes must be unique within the document
    - All trace edge @from and @to must reference existing IDs

    FOR LLMs:
    - Always include xmlns="https://rqml.org/schema/2.1.0"
    - Start documents with status="draft" during elicitation
    - Use a meaningful docId that identifies the system/project
  -->
  <xs:element name="rqml" type="RqmlDocumentType">

    <!-- Ensure IDs are unique across the document -->
    <xs:key name="allIds">
      <xs:selector xpath=".//profile|.//term|.//actor|.//stakeholder|.//constraint|.//policy|.//decision|.//risk|.//entity|.//attr|.//rule|.//stateMachine|.//state|.//transition|.//goal|.//qgoal|.//obstacle|.//goalLink|.//scenario|.//misuseCase|.//edgeCase|.//reqPackage|.//req|.//criterion|.//api|.//endpoint|.//event|.//testSuite|.//testCase|.//edge|.//issue|.//approval"/>
      <xs:field xpath="@id"/>
    </xs:key>

    <!-- Trace edges: local locator @id values must point to declared ids.
         Cross-document (doc) and external locator URIs are not validated by schema.
         Keyrefs only fire when the element is present. -->
    <xs:keyref name="traceFromRef" refer="allIds">
      <xs:selector xpath=".//edge/from/locator/local"/>
      <xs:field xpath="@id"/>
    </xs:keyref>
    <xs:keyref name="traceToRef" refer="allIds">
      <xs:selector xpath=".//edge/to/locator/local"/>
      <xs:field xpath="@id"/>
    </xs:keyref>

    <!-- State machine initial state must reference a declared state -->
    <xs:keyref name="smInitialRef" refer="allIds">
      <xs:selector xpath=".//stateMachine"/>
      <xs:field xpath="@initial"/>
    </xs:keyref>

    <!-- Transition from/to must reference declared states -->
    <xs:keyref name="transitionFromRef" refer="allIds">
      <xs:selector xpath=".//transition"/>
      <xs:field xpath="@from"/>
    </xs:keyref>
    <xs:keyref name="transitionToRef" refer="allIds">
      <xs:selector xpath=".//transition"/>
      <xs:field xpath="@to"/>
    </xs:keyref>

  </xs:element>

  <!--
    RqmlDocumentType: Structure of the complete RQML document

    Defines the top-level sections in their required order.
    Only `meta` and `requirements` are mandatory; others are optional
    but recommended for complete specifications.
  -->
  <xs:complexType name="RqmlDocumentType">
    <xs:sequence>
      <xs:element name="meta" type="MetaType"/>
      <xs:element name="catalogs" type="CatalogsType" minOccurs="0"/>
      <xs:element name="domain" type="DomainType" minOccurs="0"/>
      <xs:element name="goals" type="GoalsType" minOccurs="0"/>
      <xs:element name="scenarios" type="ScenariosType" minOccurs="0"/>
      <xs:element name="requirements" type="RequirementsType"/>
      <xs:element name="behavior" type="BehaviorType" minOccurs="0"/>
      <xs:element name="interfaces" type="InterfacesType" minOccurs="0"/>
      <xs:element name="verification" type="VerificationType" minOccurs="0"/>
      <xs:element name="trace" type="TraceTypeContainer" minOccurs="0"/>
      <xs:element name="governance" type="GovernanceType" minOccurs="0"/>
    </xs:sequence>

    <xs:attribute name="version" type="xs:token" use="required" fixed="2.1.0"/>
    <xs:attribute name="docId" type="IdType" use="required"/>
    <xs:attribute name="status" type="StatusType" use="required"/>
  </xs:complexType>

  <!-- =========================
       Meta Section

       Document identity, ownership, and conventions. Required section that
       must appear first. Establishes provenance and change control context.

       FOR LLMs:
       - Always populate title and system
       - Use conventions to establish ID patterns and normative keywords
       - Track updates in dates/updated for change management
       - Use profiles for domain-specific customizations
       ========================= -->

  <!--
    MetaType: Document metadata container

    REQUIRED CHILDREN:
    - title: Human-readable document name
    - system: Name/code of the system being specified

    OPTIONAL CHILDREN:
    - summary: Overview of scope and purpose
    - authors: Who wrote/owns this document
    - dates: Creation, update, and release timing
    - conventions: Rules for IDs and normative language
    - profiles: Domain-specific customizations
  -->
  <xs:complexType name="MetaType">
    <xs:sequence>
      <xs:element name="title" type="xs:string"/>
      <xs:element name="system" type="xs:string"/>
      <xs:element name="summary" type="TextBlockType" minOccurs="0"/>
      <xs:element name="authors" type="AuthorsType" minOccurs="0"/>
      <xs:element name="dates" type="DatesType" minOccurs="0"/>
      <xs:element name="conventions" type="ConventionsType" minOccurs="0"/>
      <xs:element name="profiles" type="ProfilesType" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="AuthorsType">
    <xs:sequence>
      <xs:element name="author" type="AuthorType" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    AuthorType: Individual author/contributor information

    FOR LLMs: Capture at least name and role for accountability.
    Contact info helps with follow-up questions during elicitation.
  -->
  <xs:complexType name="AuthorType">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="role" type="xs:string" minOccurs="0"/>
      <xs:element name="org" type="xs:string" minOccurs="0"/>
      <xs:element name="contact" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    DatesType: Temporal metadata for change control

    - created: When the document was first created (xs:date format: YYYY-MM-DD)
    - updated: When the document was last modified
    - targetRelease: Version/sprint/date when requirements should be delivered
  -->
  <xs:complexType name="DatesType">
    <xs:sequence>
      <xs:element name="created" type="xs:date" minOccurs="0"/>
      <xs:element name="updated" type="xs:date" minOccurs="0"/>
      <xs:element name="targetRelease" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ConventionsType: Document-wide rules and standards

    - normativeKeywords: How to interpret MUST/SHALL/SHOULD/MAY (typically RFC 2119)
    - idConventions: Patterns for generating IDs (e.g., "REQ-<AREA>-NNN")

    FOR LLMs: Follow these conventions when adding new elements.
  -->
  <xs:complexType name="ConventionsType">
    <xs:sequence>
      <xs:element name="normativeKeywords" type="TextBlockType" minOccurs="0"/>
      <xs:element name="idConventions" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ProfilesType">
    <xs:sequence>
      <xs:element name="profile" type="ProfileType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ProfileType: Domain-specific customization or viewpoint

    Profiles allow tailoring the spec for different audiences or domains
    (e.g., safety-critical, regulatory, mobile). Similar to viewpoints in
    ISO/IEC/IEEE 42010 architecture descriptions.

    ATTRIBUTES:
    - id: Unique identifier for the profile
    - type: Category of profile (e.g., "safety", "compliance", "mobile")
  -->
  <xs:complexType name="ProfileType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="type" type="xs:token" use="required"/>
  </xs:complexType>

  <!-- =========================
       Catalogs Section

       Shared definitions and reusable reference lists. Centralizes vocabulary
       and facts to keep requirements concise and consistent.

       FOR LLMs:
       - Define terms in glossary BEFORE using them in requirements
       - Define actors and stakeholders to establish WHO the system serves
       - Capture constraints early - they limit the solution space
       - Log decisions to preserve rationale (like ADRs)
       - Document risks so requirements can address them
       ========================= -->

  <!--
    CatalogsType: Container for all catalog subsections

    Subsections can appear in any order and multiple times.
    All provide referenceable items for use throughout the document.
  -->
  <xs:complexType name="CatalogsType">
    <xs:choice minOccurs="0" maxOccurs="unbounded">
      <xs:element name="glossary" type="GlossaryType"/>
      <xs:element name="actors" type="ActorsType"/>
      <xs:element name="stakeholders" type="StakeholdersType"/>
      <xs:element name="constraints" type="ConstraintsType"/>
      <xs:element name="policies" type="PoliciesType"/>
      <xs:element name="decisions" type="DecisionsType"/>
      <xs:element name="risks" type="RisksType"/>
    </xs:choice>
  </xs:complexType>

  <!--
    GlossaryType: Domain vocabulary definitions

    Establishes shared understanding of terms to reduce ambiguity.
    IEEE 29148 emphasizes consistent terminology in requirements.

    FOR LLMs:
    - Add terms when stakeholders use domain-specific language
    - Reference terms by ID in requirements to enforce consistency
    - Include synonyms to handle variant terminology
  -->
  <xs:complexType name="GlossaryType">
    <xs:sequence>
      <xs:element name="term" type="TermType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    TermType: Individual glossary entry

    ATTRIBUTES:
    - id: Unique identifier (e.g., TERM-PCI, TERM-PAYMENT)

    CHILDREN:
    - name: The term as used in text
    - definition: Precise meaning in this context
    - synonyms: Alternative names for the same concept
  -->
  <xs:complexType name="TermType">
    <xs:sequence>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="definition" type="TextBlockType"/>
      <xs:element name="synonyms" type="SynonymsType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
  </xs:complexType>

  <xs:complexType name="SynonymsType">
    <xs:sequence>
      <xs:element name="synonym" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ActorsType: Users and external systems that interact with the system

    Actors from UML use case modeling - entities outside the system boundary
    that interact with it. Can be humans, systems, or devices.
  -->
  <xs:complexType name="ActorsType">
    <xs:sequence>
      <xs:element name="actor" type="ActorType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ActorType: Individual actor definition

    ATTRIBUTES:
    - id: Unique identifier (e.g., ACT-USER, ACT-ADMIN, ACT-PAYMENT-GATEWAY)
    - name: Human-readable actor name
    - type: Category of actor (e.g., "human", "system", "device", "timer")

    CHILDREN:
    - description: Role and characteristics of this actor

    FOR LLMs:
    - Reference actors in scenarios via actorRef
    - Use trace edges to link actors to their goals (type="satisfies" from goal to actor)
    - Use actor types to distinguish user personas from system integrations
  -->
  <xs:complexType name="ActorType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="type" type="xs:token" use="optional"/>
  </xs:complexType>

  <!--
    StakeholdersType: Parties with interest in the system

    Stakeholders may not directly use the system but have concerns that
    requirements must address (e.g., compliance officers, operations team).
    Aligns with BABOK stakeholder analysis.
  -->
  <xs:complexType name="StakeholdersType">
    <xs:sequence>
      <xs:element name="stakeholder" type="StakeholderType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    StakeholderType: Individual stakeholder definition

    ATTRIBUTES:
    - id: Unique identifier (e.g., STK-RISK, STK-OPS, STK-LEGAL)
    - name: Stakeholder name or role
    - org: Organization they belong to

    CHILDREN:
    - concerns: What this stakeholder cares about; requirements should address these

    FOR LLMs:
    - Use ownerRef to assign requirements to responsible stakeholders
    - Ensure each concern maps to at least one requirement
    - Different stakeholders may have conflicting concerns - flag these
  -->
  <xs:complexType name="StakeholderType">
    <xs:sequence>
      <xs:element name="concerns" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="org" type="xs:string" use="optional"/>
  </xs:complexType>

  <!--
    ConstraintsType: Non-negotiable limitations on the solution

    Constraints restrict what solutions are acceptable, unlike requirements
    which specify what the solution must do. They come from technical,
    business, regulatory, or organizational sources.
  -->
  <xs:complexType name="ConstraintsType">
    <xs:sequence>
      <xs:element name="constraint" type="ConstraintType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ConstraintType: Individual constraint definition

    ATTRIBUTES:
    - id: Unique identifier (e.g., CON-HTTPS, CON-K8S, CON-JAVA17)
    - severity: Impact level (e.g., "high", "medium", "low", "blocking")

    CHILDREN:
    - statement: What is constrained and how
    - source: Where this constraint comes from (policy, standard, etc.)

    FOR LLMs:
    - Constraints with severity="blocking" must be satisfied by any solution
    - When generating code, check constraints first to avoid invalid approaches
    - Reference constraints in requirement rationale to explain "why this way"

    EXAMPLES:
    - "All APIs must use TLS 1.2+" (source: Security Policy)
    - "Must deploy to AWS us-east-1" (source: Data Residency Policy)
    - "Must use Java 17 LTS" (source: Platform Standards)
  -->
  <xs:complexType name="ConstraintType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="source" type="xs:string" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="severity" type="xs:token" use="optional"/>
  </xs:complexType>

  <!--
    PoliciesType: Organizational and regulatory obligations

    Policies define what MUST be done due to external mandates (laws,
    regulations, standards) or internal rules. They differ from constraints
    in that they specify obligations rather than limitations.
  -->
  <xs:complexType name="PoliciesType">
    <xs:sequence>
      <xs:element name="policy" type="PolicyType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    PolicyType: Individual policy definition

    ATTRIBUTES:
    - id: Unique identifier (e.g., POL-GDPR-CONSENT, POL-PCI-STORAGE)
    - source: Authority mandating this policy (e.g., "GDPR Art. 7", "PCI-DSS 3.4")

    CHILDREN:
    - obligation: What must be done to comply
    - evidence: How compliance is demonstrated

    FOR LLMs:
    - Generate PR (Policy/Compliance) requirements from policies
    - Include evidence requirements in verification section
    - Policy violations can have legal/financial consequences - flag gaps
  -->
  <xs:complexType name="PolicyType">
    <xs:sequence>
      <xs:element name="obligation" type="TextBlockType"/>
      <xs:element name="evidence" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="source" type="xs:string" use="optional"/>
  </xs:complexType>

  <!--
    DecisionsType: Architecture and design decisions

    Records significant decisions and their rationale. Similar to Architecture
    Decision Records (ADRs). Preserves context for future maintainers.
  -->
  <xs:complexType name="DecisionsType">
    <xs:sequence>
      <xs:element name="decision" type="DecisionType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    DecisionType: Individual decision record

    ATTRIBUTES:
    - id: Unique identifier (e.g., DEC-IDEMPOTENCY, DEC-DATABASE)
    - status: Decision lifecycle (draft/review/approved/deprecated)

    CHILDREN:
    - context: Why this decision was needed (the problem)
    - decision: What was decided (the solution chosen)
    - alternatives: Other options considered and why rejected
    - consequences: Implications of this decision (good and bad)

    FOR LLMs:
    - When generating code, follow approved decisions
    - Deprecated decisions may explain legacy code
    - Use decision context to understand trade-offs
    - Reference decisions in requirement rationale
  -->
  <xs:complexType name="DecisionType">
    <xs:sequence>
      <xs:element name="context" type="TextBlockType"/>
      <xs:element name="decision" type="TextBlockType"/>
      <xs:element name="alternatives" type="TextBlockType" minOccurs="0"/>
      <xs:element name="consequences" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="status" type="StatusType" use="optional"/>
  </xs:complexType>

  <!--
    RisksType: Identified risks to the project or system

    Risks are potential problems that could prevent goals from being achieved.
    Aligned with ISO 31000 risk management principles.
  -->
  <xs:complexType name="RisksType">
    <xs:sequence>
      <xs:element name="risk" type="RiskType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    RiskType: Individual risk entry

    ATTRIBUTES:
    - id: Unique identifier (e.g., RISK-FRAUD, RISK-DOWNTIME, RISK-DATA-LOSS)
    - severity: Impact level (e.g., "critical", "high", "medium", "low")

    CHILDREN:
    - statement: Description of the risk and its potential impact
    - mitigation: How this risk is addressed (link to requirements/controls)

    FOR LLMs:
    - Create trace edges from risks to goals they threaten (type="threatens")
    - Create trace edges from requirements to risks they mitigate (type="mitigates")
    - Generate SR (Security) or NFR requirements to address high-severity risks
    - Unmitigated high-severity risks should be flagged
  -->
  <xs:complexType name="RiskType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="mitigation" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="severity" type="xs:token" use="optional"/>
  </xs:complexType>

  <!-- =========================
       Domain Section

       Captures shared understanding of the problem space: key concepts,
       data structures, and business logic. Provides vocabulary for requirements.

       Aligned with Domain-Driven Design (DDD) and Michael Jackson's Problem Frames.

       FOR LLMs:
       - Use entities as the basis for data models and class hierarchies
       - Use attributes to generate database schemas and API payloads
       - Use business rules to generate validation logic
       - Reference domain elements in requirements via appliesTo or trace edges
       ========================= -->

  <!--
    DomainType: Problem space model

    CHILDREN:
    - overview: High-level context, assumptions, and scope boundaries
    - entities: Key domain objects and their attributes
    - businessRules: Invariants and logic that govern the domain
  -->
  <xs:complexType name="DomainType">
    <xs:sequence>
      <xs:element name="overview" type="TextBlockType" minOccurs="0"/>
      <xs:element name="entities" type="EntitiesType" minOccurs="0"/>
      <xs:element name="businessRules" type="BusinessRulesType" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="EntitiesType">
    <xs:sequence>
      <xs:element name="entity" type="EntityType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    EntityType: Domain object definition

    Entities are the core concepts in the problem domain. They become classes,
    database tables, API resources, and form the ubiquitous language.

    ATTRIBUTES:
    - id: Unique identifier (e.g., ENT-PAYMENT, ENT-USER, ENT-ORDER)
    - name: Entity name (use PascalCase for code generation)

    CHILDREN:
    - description: Purpose and role of this entity
    - attr: Attributes (properties/fields) of the entity

    FOR LLMs:
    - Generate classes/types from entities
    - Generate database tables from entities
    - Generate API resource schemas from entities
    - Entity names become part of the ubiquitous language
  -->
  <xs:complexType name="EntityType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="attr" type="AttrType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
  </xs:complexType>

  <!--
    AttrType: Entity attribute (property/field)

    ATTRIBUTES:
    - id: Unique identifier (e.g., ATTR-PAYMENT-ID, ATTR-AMOUNT)
    - name: Attribute name (use camelCase for code generation)
    - type: Data type token (e.g., "uuid", "string", "decimal", "ISO8601-timestamp", "email")
    - required: Whether this attribute must have a value (boolean)

    CHILDREN:
    - description: Purpose and semantics of this attribute
    - constraints: Validation rules (e.g., "positive", "max 255 chars", "valid email format")

    FOR LLMs:
    - Generate class properties from attributes
    - Generate database columns from attributes
    - Generate validation code from constraints
    - Use type tokens consistently across the document

    COMMON TYPE TOKENS:
    - uuid: Universally unique identifier
    - string: Text value
    - decimal: Numeric value with precision
    - integer: Whole number
    - boolean: True/false
    - ISO8601-timestamp: Date-time in ISO 8601 format
    - email: Email address format
    - url: URL/URI format
    - enum:value1,value2,value3: Enumerated values
  -->
  <xs:complexType name="AttrType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="constraints" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="type" type="xs:token" use="required"/>
    <xs:attribute name="required" type="xs:boolean" use="optional"/>
  </xs:complexType>

  <!--
    BusinessRulesType: Domain logic and invariants

    Business rules are constraints and logic that govern how the domain behaves.
    They exist independent of any particular system implementation.
    Aligned with the Business Rules Manifesto.
  -->
  <xs:complexType name="BusinessRulesType">
    <xs:sequence>
      <xs:element name="rule" type="RuleType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    RuleType: Individual business rule

    ATTRIBUTES:
    - id: Unique identifier (e.g., BR-DECLINE, BR-DISCOUNT, BR-SHIPPING)

    CHILDREN:
    - statement: The rule expressed in domain language
    - examples: Concrete instances showing the rule in action

    FOR LLMs:
    - Generate validation logic from business rules
    - Generate test cases from examples
    - Business rules may become FR (functional) or DR (data) requirements
    - Rules often translate to if/then logic or constraints

    EXAMPLE:
    - Rule: "Orders over $100 qualify for free shipping"
    - Example: "$150 order -> free shipping; $50 order -> $5.99 shipping"
  -->
  <xs:complexType name="RuleType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="examples" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
  </xs:complexType>

  <!-- =========================
       Goals Section

       Captures WHY the system exists: business objectives, quality targets,
       and obstacles that threaten success. Goals drive requirements.

       Aligned with KAOS and i* goal-oriented requirements engineering.

       FOR LLMs:
       - Start elicitation by asking "what are you trying to achieve?"
       - Decompose high-level goals into sub-goals (refines relationship)
       - Derive requirements that satisfy goals
       - Identify obstacles/risks that threaten goals
       - Quality goals need measurable metrics
       ========================= -->

  <!--
    GoalsType: Goal model container

    CHILDREN:
    - goal: Business/functional objectives
    - qgoal: Quality/non-functional objectives
    - obstacle: Threats to goal achievement
    - goalLink: Relationships between goals, obstacles, and other elements
  -->
  <xs:complexType name="GoalsType">
    <xs:sequence>
      <xs:element name="goal" type="GoalType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="qgoal" type="QualityGoalType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="obstacle" type="ObstacleType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="goalLink" type="GoalLinkType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    GoalType: Business or functional objective

    Goals express what stakeholders want to achieve. They are intentional
    (describe desired state) rather than operational (describe how to achieve).

    ATTRIBUTES:
    - id: Unique identifier (e.g., GOAL-AVAIL, GOAL-REVENUE, GOAL-COMPLIANCE)
    - title: Short descriptive name
    - priority: Importance (must/should/may)
    - status: Lifecycle state
    - ownerRef: Reference to stakeholder who owns this goal

    CHILDREN:
    - statement: What should be achieved (use "Maintain...", "Achieve...", "Ensure...")
    - rationale: Why this goal matters (business justification)

    FOR LLMs:
    - Ask "why?" to discover goals behind requirements
    - High-level goals decompose into sub-goals (create goalLink with type="refines")
    - Requirements satisfy goals (create trace edge with type="satisfies")
    - Goals without requirements indicate gaps

    EXAMPLES:
    - "Achieve 99.9% availability during peak shopping periods"
    - "Maintain compliance with PCI-DSS for all card transactions"
    - "Ensure new users can complete checkout within 3 minutes"
  -->
  <xs:complexType name="GoalType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="rationale" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
    <xs:attribute name="priority" type="PriorityType" use="optional"/>
    <xs:attribute name="status" type="StatusType" use="optional"/>
    <xs:attribute name="ownerRef" type="IdType" use="optional"/>
  </xs:complexType>

  <!--
    QualityGoalType: Non-functional quality objective

    Quality goals specify HOW WELL the system should perform. They map to
    ISO/IEC 25010 quality attributes (performance, security, usability, etc.).

    ATTRIBUTES:
    - id: Unique identifier (e.g., QGOAL-LATENCY, QGOAL-SECURITY, QGOAL-USABILITY)
    - title: Short descriptive name
    - priority: Importance (must/should/may)
    - status: Lifecycle state

    CHILDREN:
    - statement: The quality objective
    - metric: Measurable criteria (CRITICAL for verifiability)

    FOR LLMs:
    - Quality goals become NFR (non-functional) requirements
    - Always ask for metrics - vague quality goals are untestable
    - Generate performance/security/etc. tests from quality goals
    - Quality goals often conflict - identify trade-offs

    EXAMPLES:
    - Goal: "Low latency checkout" | Metric: "p95 latency ≤ 500ms under 200 rps"
    - Goal: "High availability" | Metric: "99.9% uptime monthly"
    - Goal: "Accessible interface" | Metric: "WCAG 2.1 Level AA compliance"
  -->
  <xs:complexType name="QualityGoalType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="metric" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
    <xs:attribute name="priority" type="PriorityType" use="optional"/>
    <xs:attribute name="status" type="StatusType" use="optional"/>
  </xs:complexType>

  <!--
    ObstacleType: Threat to goal achievement

    Obstacles are conditions or events that could prevent goals from being met.
    They drive risk mitigation and defensive requirements.

    ATTRIBUTES:
    - id: Unique identifier (e.g., OBS-DB, OBS-FRAUD, OBS-VENDOR)
    - title: Short descriptive name
    - likelihood: Probability of occurrence (e.g., "high", "medium", "low")
    - severity: Impact if it occurs (e.g., "critical", "high", "medium", "low")

    CHILDREN:
    - statement: Description of the obstacle
    - mitigation: How to address it (may reference requirements)

    FOR LLMs:
    - Create goalLink with type="threatens" to connect obstacles to goals
    - Generate requirements that mitigate high-likelihood/high-severity obstacles
    - Link mitigations to requirements via trace edges (type="mitigates")
    - Unmitigated critical obstacles should be flagged
  -->
  <xs:complexType name="ObstacleType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="mitigation" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
    <xs:attribute name="likelihood" type="xs:token" use="optional"/>
    <xs:attribute name="severity" type="xs:token" use="optional"/>
  </xs:complexType>

  <!--
    GoalLinkType: Relationship between goals and obstacles

    Captures how goals relate to each other and to obstacles.
    Used for goal decomposition and threat modeling.

    ATTRIBUTES:
    - id: Unique identifier for this link
    - from: Source element ID
    - to: Target element ID
    - type: Relationship type (TraceType - typically refines, threatens, mitigates, conflictsWith)
    - confidence: Certainty of this relationship (0.0-1.0)

    COMMON PATTERNS:
    - Sub-goal refines parent-goal (decomposition)
    - Obstacle threatens goal (threat)
    - Goal conflictsWith goal (trade-off)
    - Requirement mitigates obstacle (addressed by requirement)
  -->
  <xs:complexType name="GoalLinkType">
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="from" type="IdType" use="required"/>
    <xs:attribute name="to" type="IdType" use="required"/>
    <xs:attribute name="type" type="TraceType" use="required"/>
    <xs:attribute name="confidence" type="ConfidenceType" use="optional"/>
  </xs:complexType>

  <!-- =========================
       Scenarios Section

       Narrative descriptions of system usage. Includes positive use cases,
       negative misuse cases, and boundary edge cases.

       Aligned with Cockburn use cases and Sindre/Opdahl misuse cases.

       FOR LLMs:
       - Use scenarios to discover requirements through "what happens when..."
       - Generate acceptance tests from scenario narratives
       - Misuse cases drive security requirements
       - Edge cases drive robustness requirements
       ========================= -->

  <!--
    ScenariosType: Scenario collection

    CHILDREN:
    - scenario: Normal/positive use cases
    - misuseCase: Abuse/attack scenarios
    - edgeCase: Boundary/exceptional scenarios
  -->
  <xs:complexType name="ScenariosType">
    <xs:sequence>
      <xs:element name="scenario" type="ScenarioType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="misuseCase" type="ScenarioType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="edgeCase" type="ScenarioType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ScenarioType: Individual scenario definition (used for scenario, misuseCase, edgeCase)

    ATTRIBUTES:
    - id: Unique identifier (e.g., SCN-CHECKOUT, SCN-FRAUD, SCN-TIMEOUT)
    - title: Short descriptive name
    - actorRef: Reference to the actor performing this scenario

    CHILDREN:
    - narrative: Step-by-step description of what happens

    FOR LLMs:

    For SCENARIOS (positive use cases):
    - Describe the happy path of user interaction
    - Include main flow and notable alternative flows
    - Derive FR (functional) requirements from scenario steps
    - Generate acceptance tests from scenarios

    For MISUSE CASES (abuse scenarios):
    - Describe how attackers or malicious users might abuse the system
    - Derive SR (security) requirements to prevent/detect abuse
    - Link to risks in catalogs
    - Generate security tests from misuse cases

    For EDGE CASES (boundary scenarios):
    - Describe unusual but valid conditions (empty inputs, max values, etc.)
    - Derive robustness requirements
    - Generate boundary tests from edge cases

    EXAMPLE NARRATIVE FORMAT:
    "1. User enters email and password
     2. System validates credentials against user store
     3. System generates session token
     4. System redirects to dashboard"
  -->
  <xs:complexType name="ScenarioType">
    <xs:sequence>
      <xs:element name="narrative" type="TextBlockType"/>
</xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
    <xs:attribute name="actorRef" type="IdType" use="optional"/>
  </xs:complexType>

  <!-- =========================
       Requirements Section (REQUIRED)

       The core normative content - statements of what the system MUST do.
       This is the primary driver for implementation.

       Aligned with IEEE 29148 requirements qualities: necessary, verifiable,
       unambiguous, consistent, complete, feasible, traceable.

       FOR LLMs:
       - This section drives code generation
       - Each requirement should map to implementable code
       - Use acceptance criteria for test generation
       - Type attribute determines implementation approach
       ========================= -->

  <!--
    RequirementsType: Requirements container

    CHILDREN:
    - reqPackage: Grouping container for related requirements
    - req: Individual requirement statements

    Requirements can be organized into packages or listed directly.
    Packages help manage ownership and scope.
  -->
  <xs:complexType name="RequirementsType">
    <xs:sequence>
      <xs:element name="reqPackage" type="ReqPackageType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="req" type="ReqTypeItem" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ReqPackageType: Logical grouping of requirements

    Packages organize requirements by feature area, component, or ownership.
    Similar to Volere requirement categories or agile epics.

    ATTRIBUTES:
    - id: Unique identifier (e.g., PKG-AUTH, PKG-PAYMENTS, PKG-REPORTING)
    - title: Package name
    - ownerRef: Reference to stakeholder responsible for this package

    CHILDREN:
    - description: Purpose and scope of this package
    - req: Requirements within this package

    FOR LLMs:
    - Use packages to organize by feature area or bounded context
    - Package ownership helps route implementation to the right team
    - When generating code, package names may map to modules/namespaces
  -->
  <xs:complexType name="ReqPackageType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="req" type="ReqTypeItem" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
    <xs:attribute name="ownerRef" type="IdType" use="optional"/>
  </xs:complexType>

  <!--
    ReqTypeItem: Individual requirement definition

    The fundamental unit of specification. Each requirement is a normative
    statement about what the system must do or how it must behave.

    ATTRIBUTES:
    - id: Unique identifier (e.g., REQ-AUTH-001, REQ-PAY-002)
    - type: Requirement category (ReqType: FR/NFR/IR/DR/SR/CR/PR/UXR/OR)
    - title: Short descriptive name
    - status: Lifecycle state (draft/review/approved/deprecated)
    - priority: Importance (must/should/may)
    - ownerRef: Reference to responsible stakeholder
    - appliesTo: Token indicating scope (e.g., entity ID, component name)

    CHILDREN:
    - statement: The normative requirement (use SHALL/SHOULD/MAY)
    - rationale: Why this requirement exists
    - notes: Implementation hints or clarifications
    - acceptance: BDD-style acceptance criteria

    FOR LLMs - REQUIREMENT STATEMENT GUIDELINES:
    - Use active voice: "The system SHALL..." not "It should be possible to..."
    - Be specific: "within 200ms" not "quickly"
    - Be testable: each statement should have clear pass/fail criteria
    - One requirement per statement: avoid "and" joining unrelated behaviors
    - Use normative keywords from RFC 2119:
      * SHALL/MUST: Absolute requirement
      * SHOULD: Recommended but not mandatory
      * MAY: Optional

    FOR LLMs - CODE GENERATION BY TYPE:
    - FR: Application logic, services, controllers, business rules
    - NFR: Architecture decisions, caching, async processing, optimization
    - IR: API handlers, protocol implementations, serialization
    - DR: Models, schemas, validators, data access code
    - SR: Auth middleware, encryption, audit logging, security filters
    - CR: Configuration, deployment scripts, dependency management
    - PR: Compliance features, audit trails, reporting
    - UXR: UI components, accessibility, internationalization
    - OR: Logging, monitoring, health checks, alerting

    EXAMPLE STATEMENTS BY TYPE:
    - FR: "The system SHALL allow users to reset their password via email link"
    - NFR: "The API SHALL respond within 200ms for 95th percentile requests"
    - IR: "The system SHALL accept payment requests in ISO 20022 format"
    - DR: "Email addresses SHALL be validated against RFC 5322 format"
    - SR: "Failed login attempts SHALL be logged with source IP and timestamp"
    - CR: "The system SHALL be deployable on Kubernetes 1.28+"
    - PR: "User data exports SHALL be provided within 30 days per GDPR Art. 20"
    - UXR: "Form fields SHALL display inline validation errors on blur"
    - OR: "The system SHALL emit metrics to Prometheus in OpenMetrics format"
  -->
  <xs:complexType name="ReqTypeItem">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="rationale" type="TextBlockType" minOccurs="0"/>
      <xs:element name="notes" type="TextBlockType" minOccurs="0"/>
      <xs:element name="acceptance" type="AcceptanceType" minOccurs="0"/>
</xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="type" type="ReqType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
    <xs:attribute name="status" type="StatusType" use="optional"/>
    <xs:attribute name="priority" type="PriorityType" use="optional"/>
    <xs:attribute name="ownerRef" type="IdType" use="optional"/>
    <xs:attribute name="appliesTo" type="xs:token" use="optional"/>
  </xs:complexType>

  <!--
    AcceptanceType: Container for acceptance criteria

    Acceptance criteria define when a requirement is satisfied.
    Based on BDD/Gherkin given-when-then format.
  -->
  <xs:complexType name="AcceptanceType">
    <xs:sequence>
      <xs:element name="criterion" type="CriterionType" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    CriterionType: Individual acceptance criterion

    Uses given-when-then structure from BDD (Behavior-Driven Development).
    Each criterion is a testable scenario for the requirement.

    ATTRIBUTES:
    - id: Optional unique identifier for the criterion

    CHILDREN:
    - given: Preconditions/context (optional - may be implicit)
    - when: Action/trigger (optional - may be implicit)
    - then: Expected outcome (required - must be verifiable)

    FOR LLMs:
    - Generate test cases directly from acceptance criteria
    - "given" becomes test setup/fixtures
    - "when" becomes test action
    - "then" becomes test assertions
    - Multiple criteria = multiple test cases

    EXAMPLES:
    Criterion 1:
      given: "A user with a valid session"
      when: "The user submits an order with items totaling $150"
      then: "Free shipping is applied and total reflects no shipping charge"

    Criterion 2:
      given: "A guest user without a session"
      when: "The user attempts to access /account"
      then: "The user is redirected to /login with return URL preserved"
  -->
  <xs:complexType name="CriterionType">
    <xs:sequence>
      <xs:element name="given" type="TextBlockType" minOccurs="0"/>
      <xs:element name="when" type="TextBlockType" minOccurs="0"/>
      <xs:element name="then" type="TextBlockType" minOccurs="1"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="optional"/>
  </xs:complexType>

  <!-- =========================
       Behavior Section

       State machines that formalize entity lifecycles derived from requirements.
       Models valid states and transitions to enable precise behavioral specs.

       Placed after requirements because state machines refine/formalize requirement
       statements into explicit lifecycle models. Transitions reference requirements.

       Aligned with UML state machine concepts (simplified flat model).

       FOR LLMs:
       - Use state machines to formalize entity lifecycles (Order, Payment, User, etc.)
       - Generate state enums, transition functions, and validation logic
       - Generate state transition tests (happy path, all transitions, invalid transitions)
       - Link transitions to requirements via trace edges for traceability
       - Check guards to generate conditional logic
       ========================= -->

  <!--
    BehaviorType: Container for state machines

    CHILDREN:
    - stateMachine: Individual state machine definitions
  -->
  <xs:complexType name="BehaviorType">
    <xs:sequence>
      <xs:element name="stateMachine" type="StateMachineType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    StateMachineType: Finite state machine definition

    Models the valid lifecycle of an entity or process. An entity is always
    in exactly one state; transitions move it between states based on events
    and guards.

    ATTRIBUTES:
    - id: Unique identifier (e.g., SM-ORDER, SM-PAYMENT, SM-USER-ACCOUNT)
    - name: Human-readable state machine name
    - entityRef: Optional reference to the domain entity this governs
    - initial: Required reference to the initial state ID

    CHILDREN:
    - description: Purpose and scope of this state machine
    - state: State definitions (at least one required)
    - transition: Transition definitions between states

    FOR LLMs:
    - Generate state enum/type from all state names
    - Generate transition validation function
    - Use entityRef to link to domain entity for the status field
    - Ensure initial state exists and is reachable
    - Verify all non-final states have at least one outgoing transition

    EXAMPLE ID PATTERNS:
    - SM-ORDER (order lifecycle)
    - SM-PAYMENT (payment processing)
    - SM-TICKET (support ticket workflow)
    - SM-DOC-REVIEW (document approval process)
  -->
  <xs:complexType name="StateMachineType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="state" type="StateType" minOccurs="1" maxOccurs="unbounded"/>
      <xs:element name="transition" type="TransitionType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="entityRef" type="IdType" use="optional"/>
    <xs:attribute name="initial" type="IdType" use="required"/>
  </xs:complexType>

  <!--
    StateType: Individual state in a state machine

    Represents a distinct condition or situation in an entity's lifecycle.
    States are mutually exclusive; an entity is in exactly one state at a time.

    ATTRIBUTES:
    - id: Unique identifier (e.g., ST-PENDING, ST-CONFIRMED, ST-CANCELLED)
    - name: Human-readable state name (use for enum values in code generation)
    - type: State kind: initial, normal, or final (default: normal)

    CHILDREN:
    - description: What this state represents and when an entity is in it
    - onEntry: Actions to perform when entering this state
    - onExit: Actions to perform when leaving this state
    - invariant: Conditions that must hold while in this state

    FOR LLMs:
    - Generate enum values from state names (use PascalCase or snake_case)
    - onEntry actions become side effects in transition handlers
    - onExit actions become cleanup logic before transitions
    - invariant becomes validation logic or assertions
    - States with type="final" should have no outgoing transitions

    EXAMPLE STATE NAMES:
    - Pending, Confirmed, Shipped, Delivered, Cancelled (order)
    - Draft, Review, Approved, Published, Archived (document)
    - Active, Suspended, Closed (account)
  -->
  <xs:complexType name="StateType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="onEntry" type="TextBlockType" minOccurs="0"/>
      <xs:element name="onExit" type="TextBlockType" minOccurs="0"/>
      <xs:element name="invariant" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="type" type="StateKindType" use="optional" default="normal"/>
  </xs:complexType>

  <!--
    TransitionType: State transition definition

    Defines a valid movement from one state to another, optionally triggered
    by an event and constrained by a guard condition.

    ATTRIBUTES:
    - id: Unique identifier (e.g., TR-CONFIRM, TR-SHIP, TR-CANCEL)
    - from: Source state ID (must exist in same state machine)
    - to: Target state ID (must exist in same state machine)
    - event: Optional event name that triggers this transition

    CHILDREN:
    - description: Human-readable explanation of this transition
    - trigger: What causes this transition (if not captured by event attribute)
    - guard: Condition that must be true for transition to fire
    - action: What happens during the transition (side effects)

    FOR LLMs:

    CODE GENERATION:
    - Generate transition table/map: { from, to, event, guard? }
    - Generate event handler functions from event names
    - Guard text becomes conditional logic (if/when)
    - Action text becomes side effect code
    - Use trace edges to link transitions to requirements for traceability

    TEST GENERATION:
    - Generate test for each transition (valid path)
    - Generate test for transition with guard=true and guard=false
    - Generate test for invalid transitions (wrong source state)
    - Generate test for missing event (should reject)

    PATTERNS:
    - event="confirm" -> onConfirm() handler
    - guard="payment authorized" -> if (order.paymentAuthorized)
    - action="send email" -> emailService.send(...)

    EXAMPLE:
    <transition id="TR-SHIP" from="ST-CONFIRMED" to="ST-SHIPPED" event="ship">
      <guard>All items picked and packed</guard>
      <action>Capture payment; generate tracking number</action>
    </transition>
    Then link via trace section:
      edge id="TR-SHIP-REQ" type="satisfies"
        from > locator > local id="TR-SHIP"
        to   > locator > local id="REQ-ORDER-SHIP"
  -->
  <xs:complexType name="TransitionType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="trigger" type="TextBlockType" minOccurs="0"/>
      <xs:element name="guard" type="TextBlockType" minOccurs="0"/>
      <xs:element name="action" type="TextBlockType" minOccurs="0"/>
</xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="from" type="IdType" use="required"/>
    <xs:attribute name="to" type="IdType" use="required"/>
    <xs:attribute name="event" type="xs:string" use="optional"/>
  </xs:complexType>

  <!-- =========================
       Interfaces Section

       System boundaries and contracts with external systems.
       Describes APIs, events, and other integration points.

       Aligned with ISO/IEC/IEEE 42010 interface specifications.

       FOR LLMs:
       - Generate API handlers from endpoint definitions
       - Generate event handlers from event definitions
       - Generate client SDKs from API specifications
       - Generate OpenAPI/AsyncAPI specs from interface definitions
       ========================= -->

  <!--
    InterfacesType: Interface specifications container

    CHILDREN:
    - api: Synchronous API definitions (REST, RPC, GraphQL)
    - event: Asynchronous event definitions (messages, webhooks)
  -->
  <xs:complexType name="InterfacesType">
    <xs:sequence>
      <xs:element name="api" type="ApiType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="event" type="EventType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    ApiType: API surface definition

    ATTRIBUTES:
    - id: Unique identifier (e.g., API-PAYMENTS, API-USERS, API-ADMIN)
    - name: Human-readable API name
    - protocol: Communication protocol (e.g., "https", "grpc", "graphql", "websocket")
    - auth: Authentication method (e.g., "oauth2", "api-key", "jwt", "mtls", "none")

    CHILDREN:
    - description: Purpose and scope of this API
    - endpoint: Individual endpoint definitions

    FOR LLMs:
    - Use protocol to determine implementation pattern
    - Use auth to generate authentication/authorization middleware
    - API names may map to controller classes or service modules
    - Generate OpenAPI specification from api + endpoints
  -->
  <xs:complexType name="ApiType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="endpoint" type="EndpointType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="protocol" type="xs:token" use="optional"/>
    <xs:attribute name="auth" type="xs:token" use="optional"/>
  </xs:complexType>

  <!--
    EndpointType: Individual API endpoint

    ATTRIBUTES:
    - id: Unique identifier (e.g., EP-CREATE-PAYMENT, EP-GET-USER)
    - method: HTTP method or operation type (e.g., "GET", "POST", "PUT", "DELETE", "PATCH")
    - path: URL path with parameters (e.g., "/payments", "/users/{id}", "/orders/{orderId}/items")

    CHILDREN:
    - summary: Brief description of what this endpoint does
    - request: Request body/parameters specification
    - response: Success response specification
    - errors: Error responses and conditions

    FOR LLMs:
    - Generate route handlers from method + path
    - Generate request DTOs/validators from request description
    - Generate response DTOs from response description
    - Generate error handling from errors description
    - Use domain entities as basis for request/response schemas

    PATH PARAMETER CONVENTIONS:
    - Use {paramName} for path parameters
    - Use snake_case or camelCase consistently
    - Example: /users/{userId}/orders/{orderId}

    COMMON PATTERNS:
    - GET /resources - List resources (paginated)
    - POST /resources - Create new resource
    - GET /resources/{id} - Get single resource
    - PUT /resources/{id} - Replace resource
    - PATCH /resources/{id} - Update resource partially
    - DELETE /resources/{id} - Remove resource
  -->
  <xs:complexType name="EndpointType">
    <xs:sequence>
      <xs:element name="summary" type="TextBlockType" minOccurs="0"/>
      <xs:element name="request" type="TextBlockType" minOccurs="0"/>
      <xs:element name="response" type="TextBlockType" minOccurs="0"/>
      <xs:element name="errors" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="method" type="xs:token" use="required"/>
    <xs:attribute name="path" type="xs:string" use="required"/>
  </xs:complexType>

  <!--
    EventType: Asynchronous event definition

    Events represent messages exchanged asynchronously between systems
    or components (message queues, event buses, webhooks, etc.).

    ATTRIBUTES:
    - id: Unique identifier (e.g., EVT-PAYMENT-CREATED, EVT-ORDER-SHIPPED)
    - name: Event name (use PascalCase for consistency)

    CHILDREN:
    - description: When this event is emitted and its purpose
    - payload: Data structure carried by the event

    FOR LLMs:
    - Generate event classes/types from event definitions
    - Generate event handlers/subscribers
    - Generate event publishers/emitters
    - Use domain entities as basis for payload schemas
    - Generate AsyncAPI specification from events

    EVENT NAMING CONVENTIONS:
    - Use past tense for things that happened: PaymentCreated, OrderShipped
    - Use present tense for commands: ProcessPayment, ShipOrder
    - Include domain context: PaymentService.PaymentCreated vs OrderService.PaymentReceived
  -->
  <xs:complexType name="EventType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
      <xs:element name="payload" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="name" type="xs:string" use="required"/>
  </xs:complexType>

  <!-- =========================
       Verification Section

       How requirements are tested and validated. Captures planned
       and executed verification activities.

       Aligned with IEEE 29148 verification requirements and V-model testing.

       FOR LLMs:
       - Generate test code from test case definitions
       - Map test cases to requirements via trace edges (type="verifiedBy")
       - Use acceptance criteria (given/when/then) for test implementation
       - Ensure each requirement has at least one verifiedBy trace edge
       ========================= -->

  <!--
    VerificationType: Verification container

    CHILDREN:
    - testSuite: Logical grouping of test cases
    - testCase: Individual verification items
  -->
  <xs:complexType name="VerificationType">
    <xs:sequence>
      <xs:element name="testSuite" type="TestSuiteType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="testCase" type="TestCaseType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    TestSuiteType: Logical grouping of test cases

    ATTRIBUTES:
    - id: Unique identifier (e.g., TS-PAYMENT, TS-AUTH, TS-PERFORMANCE)
    - title: Suite name

    CHILDREN:
    - description: Purpose and scope of this test suite

    FOR LLMs:
    - Generate test suite/describe blocks from test suites
    - Use trace edges to link test cases to suites for grouping
    - Suites may map to test files or test classes
  -->
  <xs:complexType name="TestSuiteType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
  </xs:complexType>

  <!--
    TestCaseType: Individual verification item

    ATTRIBUTES:
    - id: Unique identifier (e.g., TC-AUTH-001, TC-PERF-LOAD)
    - type: Test category (TestType: acceptance/integration/unit/security/performance/inspection)
    - title: Test name

    CHILDREN:
    - purpose: What this test verifies (the "why")
    - steps: How to execute the test (the "how")
    - expected: Expected outcome (the "what")

    FOR LLMs - TEST GENERATION BY TYPE:

    acceptance:
    - Generate from requirement acceptance criteria
    - Use end-to-end test frameworks (Cypress, Playwright, etc.)
    - Focus on user-facing behavior

    integration:
    - Test component interactions
    - Use API testing tools
    - Mock external dependencies appropriately

    unit:
    - Test individual functions/methods
    - Use unit test frameworks (Jest, pytest, JUnit, etc.)
    - Focus on logic correctness

    security:
    - Generate from SR requirements
    - Include auth bypass attempts, injection tests, etc.
    - Use security testing tools

    performance:
    - Generate from NFR requirements with metrics
    - Use load testing tools (k6, JMeter, etc.)
    - Include baseline and stress scenarios

    inspection:
    - Document manual review checklists
    - Include compliance verification points
    - May not generate automated code

    TEST CASE EXAMPLE:
    purpose: "Verify password reset flow works for valid users"
    steps: "1. Request reset for valid email
            2. Extract token from email
            3. Submit new password with token"
    expected: "Password is updated and user can login with new password"
  -->
  <xs:complexType name="TestCaseType">
    <xs:sequence>
      <xs:element name="purpose" type="TextBlockType" minOccurs="0"/>
      <xs:element name="steps" type="TextBlockType" minOccurs="0"/>
      <xs:element name="expected" type="TextBlockType" minOccurs="0"/>
</xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="type" type="TestType" use="required"/>
    <xs:attribute name="title" type="xs:string" use="required"/>
  </xs:complexType>

  <!-- =========================
       Trace Section

       Explicit relationships between all artifacts for impact analysis
       and coverage tracking. This is the traceability matrix in graph form.

       Aligned with IEEE 29148 traceability requirements.

       FOR LLMs:
       - Use traces to answer "what depends on this?" before making changes
       - Use traces to verify coverage (every goal has satisfying requirements)
       - Create traces when generating code (implements relationship)
       - Maintain trace integrity when modifying documents
       ========================= -->

  <!--
    TraceTypeContainer: Container for trace edges

    Trace edges form a directed graph connecting all artifacts.
    Use queries on this graph for impact analysis and coverage reports.
  -->
  <xs:complexType name="TraceTypeContainer">
    <xs:sequence>
      <xs:element name="edge" type="TraceEdgeType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!-- =========
       TRACE GRAPH
       =========

       Each trace edge has two structured endpoints (from/to), each containing
       a locator element. The locator is one of three types:
         - local:    reference by @id to an element in this document (keyref-validated)
         - doc:      reference by @uri/@docId/@id to an element in another RQML document
                     Supports @version and @git for immutable pinning
         - external: reference by @uri to any external artifact (Jira, Git, standards, etc.)
  -->

  <xs:complexType name="TraceEdgeType">
    <xs:sequence>
      <xs:element name="from" type="TraceEndpointType"/>
      <xs:element name="to" type="TraceEndpointType"/>
      <xs:element name="notes" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>

    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="type" type="TraceType" use="required"/>
    <xs:attribute name="confidence" type="ConfidenceType"/>

    <!-- Lifecycle metadata -->
    <xs:attribute name="status" type="StatusType"/>
    <xs:attribute name="createdBy" type="xs:string"/>
    <xs:attribute name="createdAt" type="xs:dateTime"/>

    <!-- Categorization -->
    <xs:attribute name="tags" type="xs:NMTOKENS"/>
  </xs:complexType>

  <xs:complexType name="TraceEndpointType">
    <xs:sequence>
      <xs:element name="locator" type="TraceLocatorType"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="TraceLocatorType">
    <xs:choice>
      <!-- Reference an artifact by id in this document -->
      <xs:element name="local" type="TraceLocalRefType"/>

      <!-- Reference an artifact by id in another RQML document -->
      <xs:element name="doc" type="TraceDocRefType"/>

      <!-- Reference any external artifact by URI -->
      <xs:element name="external" type="TraceExternalRefType"/>
    </xs:choice>
  </xs:complexType>

  <xs:complexType name="TraceLocalRefType">
    <xs:attribute name="id" type="IdType" use="required"/>
    <!-- Optional hints for tooling / renderers -->
    <xs:attribute name="kind" type="xs:token"/>
    <xs:attribute name="title" type="xs:string"/>
  </xs:complexType>

  <xs:complexType name="TraceDocRefType">
    <!-- Where to find the other RQML document -->
    <xs:attribute name="uri" type="xs:anyURI" use="required"/>
    <xs:attribute name="docId" type="IdType"/>
    <!-- Optional pinning for immutability -->
    <xs:attribute name="version" type="xs:token"/>
    <xs:attribute name="git" type="xs:token"/>

    <!-- What inside that document -->
    <xs:attribute name="id" type="IdType" use="required"/>

    <!-- Optional hints for tooling / renderers -->
    <xs:attribute name="kind" type="xs:token"/>
    <xs:attribute name="title" type="xs:string"/>
  </xs:complexType>

  <xs:complexType name="TraceExternalRefType">
    <xs:attribute name="uri" type="xs:anyURI" use="required"/>
    <!-- Optional hints for tooling / renderers -->
    <xs:attribute name="kind" type="xs:token"/>
    <xs:attribute name="title" type="xs:string"/>
  </xs:complexType>

  <!--
    TraceEdgeType: Individual traceability link (structured endpoint model)

    Each edge connects two endpoints via structured locators. Each endpoint
    contains a locator element that can be one of three types:

    LOCATOR TYPES:
    - local: Reference by @id to an element in THIS document (keyref-validated)
    - doc:   Reference by @uri + @id to an element in ANOTHER RQML document
             Supports @version and @git pinning for immutability
    - external: Reference by @uri to any external artifact (not validated)

    ATTRIBUTES:
    - id: Unique identifier for this edge
    - type: Relationship type (TraceType — 15 values, see TraceType comment)
    - confidence: Certainty of this relationship (0.0-1.0)
    - status: Lifecycle state (draft/review/approved/deprecated)
    - createdBy: Who created this trace (person, role, or tool)
    - createdAt: When this trace was created (ISO 8601 dateTime)
    - tags: Space-separated category tags for filtering (e.g., "safety security")

    CHILDREN:
    - from: Source endpoint (contains locator)
    - to: Target endpoint (contains locator)
    - notes: Explanation of why this relationship exists

    FOR LLMs - COMMON TRACE PATTERNS:

    Local traces (within same RQML document):
      <edge id="TR-1" type="satisfies">
        <from><locator><local id="REQ-001"/></locator></from>
        <to><locator><local id="GOAL-001"/></locator></to>
      </edge>

    Cross-document traces (between RQML documents):
      <edge id="TR-2" type="dependsOn">
        <from><locator><local id="REQ-PAY-001"/></locator></from>
        <to><locator><doc uri="auth-spec.rqml" docId="AUTH-001" id="REQ-AUTH-001" version="2.1.0"/></locator></to>
      </edge>

    External traces (to/from external systems):
      <edge id="TR-3" type="implements">
        <from><locator><external uri="file:src/auth/login.ts#L42-L87"/></locator></from>
        <to><locator><local id="REQ-AUTH-001"/></locator></to>
      </edge>

    EXTERNAL URI CONVENTIONS:
    - Jira:        jira:PROJ-1234
    - GitHub:      github:owner/repo/issues/42
    - Git commit:  git:a1b2c3d4e5f6
    - File:        file:src/auth/login.ts#L42-L87
    - Regulation:  urn:gdpr:article:17
    - Full URL:    https://jira.example.com/browse/PROJ-1234

    IMPACT ANALYSIS:
    To find what's affected by changing element X:
    1. Find all edges where from or to locators reference X
    2. Recursively follow edges to find transitive impacts
    3. Higher confidence edges indicate stronger impacts

    COVERAGE ANALYSIS:
    To verify all goals are addressed:
    1. For each goal, find edges where to references goal_id and type=satisfies
    2. Goals without satisfies edges are uncovered
    3. Flag uncovered goals for stakeholder attention

    LIFECYCLE MANAGEMENT:
    - status=draft: Auto-generated or tentative traces
    - status=approved: Confirmed traces for reliable impact analysis
    - status=deprecated: Historical traces kept for audit
    - Use createdBy/createdAt for accountability and staleness detection

    CATEGORIZATION:
    Use tags for filtering: safety, security, compliance, performance, accessibility
    Example: tags="safety compliance" for a trace relevant to both domains
  -->
  

  <!-- =========================
       Governance Section

       Change control, accountability, and approval workflows.
       Tracks issues to resolve and sign-offs obtained.

       Aligned with ISO/IEC/IEEE 12207 configuration management.

       FOR LLMs:
       - Check governance/issues for open questions before implementing
       - Approved documents are ready for implementation
       - Issues may block requirements or indicate uncertainty
       - Update governance when making document changes
       ========================= -->

  <!--
    GovernanceType: Governance container

    CHILDREN:
    - issue: Open questions, concerns, or deviations
    - approval: Sign-offs and authorizations
  -->
  <xs:complexType name="GovernanceType">
    <xs:sequence>
      <xs:element name="issue" type="IssueType" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="approval" type="ApprovalType" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <!--
    IssueType: Open question or concern

    Issues track things that need resolution: missing information,
    conflicting requirements, deferred decisions, or risks.

    ATTRIBUTES:
    - id: Unique identifier (e.g., ISS-PCI, ISS-SCOPE, ISS-RESOURCE)
    - status: Issue lifecycle (draft/review/approved/deprecated - where approved means resolved)
    - owner: Person or role responsible for resolution

    CHILDREN:
    - statement: What needs to be addressed
    - notes: Progress, context, or resolution details

    FOR LLMs:
    - Check issues before implementing - they may indicate blocking concerns
    - Issues with status="review" need stakeholder input
    - Resolved issues (status="approved") contain decisions to follow
    - Create issues when encountering ambiguity during elicitation
  -->
  <xs:complexType name="IssueType">
    <xs:sequence>
      <xs:element name="statement" type="TextBlockType"/>
      <xs:element name="notes" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="status" type="StatusType" use="optional"/>
    <xs:attribute name="owner" type="xs:string" use="optional"/>
  </xs:complexType>

  <!--
    ApprovalType: Sign-off record

    Approvals track who has reviewed and accepted the specification.
    Required for regulated environments and formal release processes.

    ATTRIBUTES:
    - id: Unique identifier (e.g., APR-SEC, APR-LEGAL, APR-PRODUCT)
    - role: The role required to approve (not a specific person)
    - status: Approval state (draft=pending, approved=obtained, deprecated=revoked)

    CHILDREN:
    - description: Scope of this approval (what is being approved)

    FOR LLMs:
    - Documents need approvals before implementation in regulated contexts
    - Check approval status before treating requirements as final
    - Different roles approve different aspects (security, legal, product, etc.)
  -->
  <xs:complexType name="ApprovalType">
    <xs:sequence>
      <xs:element name="description" type="TextBlockType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="IdType" use="required"/>
    <xs:attribute name="role" type="xs:string" use="required"/>
    <xs:attribute name="status" type="StatusType" use="optional"/>
  </xs:complexType>

</xs:schema>
