doc-ctr

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

doc-ctr

doc-ctr

Purpose

目的

Create Data Contracts (CTR) - Optional Layer 8 artifact in the SDD workflow that defines API contracts, data schemas, and interface specifications using dual-file format (markdown + YAML).
Layer: 8 (Optional)
Upstream: BRD (Layer 1), PRD (Layer 2), EARS (Layer 3), BDD (Layer 4), ADR (Layer 5), SYS (Layer 6), REQ (Layer 7)
Downstream Artifacts: SPEC (Layer 9), TSPEC (Layer 10), TASKS (Layer 11), Code (Layer 12)
创建数据契约(CTR)——SDD流程中的可选第8层工件,采用双文件格式(markdown + YAML)定义API契约、数据模式和接口规范。
层级: 8(可选)
上游工件: BRD(第1层)、PRD(第2层)、EARS(第3层)、BDD(第4层)、ADR(第5层)、SYS(第6层)、REQ(第7层)
下游工件: SPEC(第9层)、TSPEC(第10层)、TASKS(第11层)、代码(第12层)

Prerequisites

前置条件

Upstream Artifact Verification (CRITICAL)

上游工件验证(关键)

Before creating this document, you MUST:
  1. List existing upstream artifacts:
    bash
    ls docs/01_BRD/ docs/02_PRD/ docs/03_EARS/ docs/04_BDD/ docs/05_ADR/ docs/06_SYS/ docs/07_REQ/ 2>/dev/null
  2. Reference only existing documents in traceability tags
  3. Use
    null
    only when upstream artifact type genuinely doesn't exist
  4. NEVER use placeholders like
    BRD-XXX
    or
    TBD
  5. Do NOT create missing upstream artifacts - skip functionality instead
Before creating CTR, read:
  1. Shared Standards:
    .claude/skills/doc-flow/SHARED_CONTENT.md
  2. Upstream REQ: Read atomic requirements (especially Section 3: Interface Specifications, Section 4: Data Schemas)
  3. Template:
    ai_dev_flow/08_CTR/CTR-TEMPLATE.md
    and
    CTR-TEMPLATE.yaml
  4. Creation Rules:
    ai_dev_flow/08_CTR/CTR_CREATION_RULES.md
  5. Validation Rules:
    ai_dev_flow/08_CTR/CTR_VALIDATION_RULES.md
  6. Validation Script:
    ./ai_dev_flow/scripts/validate_ctr.sh
在创建本文档之前,您必须:
  1. 列出已有的上游工件:
    bash
    ls docs/01_BRD/ docs/02_PRD/ docs/03_EARS/ docs/04_BDD/ docs/05_ADR/ docs/06_SYS/ docs/07_REQ/ 2>/dev/null
  2. 仅在可追溯标签中引用已存在的文档
  3. 仅当上游工件类型确实不存在时才使用
    null
  4. 绝不要使用
    BRD-XXX
    TBD
    这类占位符
  5. 不要创建缺失的上游工件——而是跳过相关功能
在创建CTR之前,请阅读:
  1. 共享标准:
    .claude/skills/doc-flow/SHARED_CONTENT.md
  2. 上游REQ: 阅读原子需求(尤其是第3节:接口规范、第4节:数据模式)
  3. 模板:
    ai_dev_flow/08_CTR/CTR-TEMPLATE.md
    CTR-TEMPLATE.yaml
  4. 创建规则:
    ai_dev_flow/08_CTR/CTR_CREATION_RULES.md
  5. 验证规则:
    ai_dev_flow/08_CTR/CTR_VALIDATION_RULES.md
  6. 验证脚本:
    ./ai_dev_flow/scripts/validate_ctr.sh

Reserved ID Exemption (CTR-00_*)

保留ID豁免(CTR-00_*)

Scope: Documents with reserved ID
000
are FULLY EXEMPT from validation.
Pattern:
CTR-00_*.md
,
CTR-00_*.yaml
Document Types:
  • Index documents (
    CTR-00_index.md
    )
  • Traceability matrix templates (
    CTR-00_TRACEABILITY_MATRIX-TEMPLATE.md
    )
  • Glossaries, registries, checklists
Rationale: Reserved ID 000 documents are framework infrastructure (indexes, templates, reference materials), not project artifacts requiring traceability or quality gates.
Validation Behavior: Skip all checks when filename matches
CTR-00_*
pattern.
范围: 保留ID为
000
的文档完全豁免验证。
模式:
CTR-00_*.md
,
CTR-00_*.yaml
文档类型:
  • 索引文档(
    CTR-00_index.md
  • 可追溯性矩阵模板(
    CTR-00_TRACEABILITY_MATRIX-TEMPLATE.md
  • 术语表、注册表、检查清单
理由: 保留ID 000的文档属于框架基础设施(索引、模板、参考资料),而非需要可追溯性或质量门的项目工件。
验证行为: 当文件名匹配
CTR-00_*
模式时,跳过所有检查。

When to Use This Skill

何时使用此技能

Use
doc-ctr
when:
  • Have completed BRD through REQ (Layers 1-7)
  • Need to define API contracts or data schemas
  • Multiple teams/services need shared contracts
  • Building microservices or distributed systems
  • REQ Section 3 (Interface Specifications) needs formal contract
  • This layer is OPTIONAL (Layer 8) - skip if contracts are simple
在以下场景使用
doc-ctr
:
  • 已完成BRD到REQ(第1-7层)
  • 需要定义API契约或数据模式
  • 多个团队/服务需要共享契约
  • 构建微服务或分布式系统
  • REQ第3节(接口规范)需要正式契约
  • 此层级为可选(第8层)——如果契约简单可跳过

CTR-Specific Guidance

CTR专属指南

1. Mandatory Dual-File Format

1. 强制双文件格式

Two files required for each contract (mandatory dual-file format:
.md
file + companion
.yaml
file):
Markdown File (
.md
):
  • Document Control section
  • Contract overview
  • Business context
  • Usage examples
  • Traceability
YAML File (
.yaml
):
  • OpenAPI 3.0 or JSON Schema
  • Formal contract definition
  • Validation rules
  • Example payloads
Example:
ai_dev_flow/CTR/CTR-01_data_validation.md
ai_dev_flow/CTR/CTR-01_data_validation.yaml
每个契约需要两个文件(强制双文件格式:
.md
文件 + 配套
.yaml
文件):
Markdown文件
.md
):
  • 文档控制部分
  • 契约概述
  • 业务上下文
  • 使用示例
  • 可追溯性
YAML文件
.yaml
):
  • OpenAPI 3.0或JSON Schema
  • 正式契约定义
  • 验证规则
  • 示例负载
示例:
ai_dev_flow/CTR/CTR-01_data_validation.md
ai_dev_flow/CTR/CTR-01_data_validation.yaml

2. Document Control Fields (9 Required)

2. 文档控制字段(9个必填)

FieldRequiredDescription
CTR IDYesCTR-NN format
TitleYesContract name
StatusYesDraft/In Review/Active/Deprecated
VersionYesSemantic version (Major.Minor.Patch)
CreatedYesYYYY-MM-DD
AuthorYesDocument author
OwnerYesContract owner
Last UpdatedYesYYYY-MM-DD
SPEC-Ready ScoreYes✅ NN% (Target: ≥90%)
字段必填描述
CTR IDCTR-NN格式
标题契约名称
状态草稿/审核中/已激活/已弃用
版本语义化版本(主版本.次版本.修订版本)
创建日期YYYY-MM-DD
作者文档作者
所有者契约所有者
最后更新日期YYYY-MM-DD
SPEC就绪分数✅ NN%(目标:≥90%)

3. Required Sections (Markdown File)

3. 必填章节(Markdown文件)

Document Control (MANDATORY - First section before all numbered sections)
Core Sections:
  1. Contract Overview: Purpose, scope, version
  2. Business Context: Why this contract exists (link to REQ)
  3. Contract Definition: Reference to YAML file
  4. Usage Examples: Request/response examples
  5. Validation Rules: Schema validation, business rules
  6. Error Handling: Error codes and responses
  7. Traceability: Section 7 format with cumulative tags
文档控制(必填 - 所有编号章节之前的第一个章节)
核心章节:
  1. 契约概述: 目的、范围、版本
  2. 业务上下文: 契约存在的原因(链接到REQ)
  3. 契约定义: 引用YAML文件
  4. 使用示例: 请求/响应示例
  5. 验证规则: 模式验证、业务规则
  6. 错误处理: 错误代码和响应
  7. 可追溯性: 第7节格式,包含累积标签

4. Element ID Format (MANDATORY)

4. 元素ID格式(必填)

Pattern:
CTR.{DOC_NUM}.{ELEM_TYPE}.{SEQ}
(4 segments, dot-separated)
Element TypeCodeExample
Interface16CTR.02.16.01
Data Model17CTR.02.17.01
Contract Clause20CTR.02.20.01
REMOVED PATTERNS - Do NOT use legacy formats:
  • INT-XXX
    - Use
    CTR.NN.16.SS
    instead
  • MODEL-XXX
    - Use
    CTR.NN.17.SS
    instead
  • CLAUSE-XXX
    - Use
    CTR.NN.20.SS
    instead
  • IF-XXX
    - Use
    CTR.NN.16.SS
    instead
  • DM-XXX
    - Use
    CTR.NN.17.SS
    instead
  • CC-XXX
    - Use
    CTR.NN.20.SS
    instead
Reference: ID_NAMING_STANDARDS.md - Cross-Reference Link Format
模式:
CTR.{DOC_NUM}.{ELEM_TYPE}.{SEQ}
(4个段,点分隔)
元素类型代码示例
接口16CTR.02.16.01
数据模型17CTR.02.17.01
契约条款20CTR.02.20.01
已移除模式 - 不要使用旧格式:
  • INT-XXX
    - 改用
    CTR.NN.16.SS
  • MODEL-XXX
    - 改用
    CTR.NN.17.SS
  • CLAUSE-XXX
    - 改用
    CTR.NN.20.SS
  • IF-XXX
    - 改用
    CTR.NN.16.SS
  • DM-XXX
    - 改用
    CTR.NN.17.SS
  • CC-XXX
    - 改用
    CTR.NN.20.SS
参考: ID_NAMING_STANDARDS.md - 交叉引用链接格式

5. YAML Contract Format

5. YAML契约格式

OpenAPI 3.0 Format (for APIs):
yaml
openapi: 3.0.3
info:
  title: Data Validation API
  version: 1.0.0
  description: Contract for data validation

paths:
  /api/v1/data/validate:
    post:
      summary: Validate data record
      operationId: validateDataRecord
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DataRequest'
      responses:
        '200':
          description: Validation successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationResponse'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

components:
  schemas:
    DataRequest:
      type: object
      required:
        - record_type
        - record_id
        - data
        - account_id
      properties:
        record_type:
          type: string
          pattern: ^[A-Z]{1,10}$
          example: "METRIC"
        record_id:
          type: string
          format: uuid
          example: "abc123"
        data:
          type: object
          example: {}
        account_id:
          type: string
          format: uuid
          example: "123e4567-e89b-12d3-a456-426614174000"

    ValidationResponse:
      type: object
      required:
        - valid
        - order_id
      properties:
        valid:
          type: boolean
          example: true
        order_id:
          type: string
          format: uuid
          example: "987f6543-e21c-43d2-b654-426614174111"
        warnings:
          type: array
          items:
            type: string
          example: ["Price near market close"]

    ErrorResponse:
      type: object
      required:
        - error_code
        - message
      properties:
        error_code:
          type: string
          example: "INVALID_SYMBOL"
        message:
          type: string
          example: "Symbol 'XYZ' not found in approved list"
        details:
          type: object
          additionalProperties: true
JSON Schema Format (for data models):
yaml
$schema: "http://json-schema.org/draft-07/schema#"
name: DataProcessingConfig
description: Configuration schema for data processing

type: object
required:
  - max_batch_size
  - timeout_seconds
  - check_frequency

properties:
  max_batch_size:
    type: integer
    minimum: 1
    maximum: 10000
    description: Maximum records per batch
    example: 1000

  timeout_seconds:
    type: integer
    minimum: 1
    maximum: 300
    description: Processing timeout in seconds
    example: 60

  check_frequency:
    type: string
    enum: ["realtime", "1min", "5min", "15min"]
    description: How often to check processing status
    example: "1min"

  alert_threshold:
    type: number
    minimum: 0
    maximum: 1.0
    description: Alert when queue depth exceeds this fraction
    default: 0.80
    example: 0.80
OpenAPI 3.0格式(适用于API):
yaml
openapi: 3.0.3
info:
  title: Data Validation API
  version: 1.0.0
  description: Contract for data validation

paths:
  /api/v1/data/validate:
    post:
      summary: Validate data record
      operationId: validateDataRecord
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DataRequest'
      responses:
        '200':
          description: Validation successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationResponse'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

components:
  schemas:
    DataRequest:
      type: object
      required:
        - record_type
        - record_id
        - data
        - account_id
      properties:
        record_type:
          type: string
          pattern: ^[A-Z]{1,10}$
          example: "METRIC"
        record_id:
          type: string
          format: uuid
          example: "abc123"
        data:
          type: object
          example: {}
        account_id:
          type: string
          format: uuid
          example: "123e4567-e89b-12d3-a456-426614174000"

    ValidationResponse:
      type: object
      required:
        - valid
        - order_id
      properties:
        valid:
          type: boolean
          example: true
        order_id:
          type: string
          format: uuid
          example: "987f6543-e21c-43d2-b654-426614174111"
        warnings:
          type: array
          items:
            type: string
          example: ["Price near market close"]

    ErrorResponse:
      type: object
      required:
        - error_code
        - message
      properties:
        error_code:
          type: string
          example: "INVALID_SYMBOL"
        message:
          type: string
          example: "Symbol 'XYZ' not found in approved list"
        details:
          type: object
          additionalProperties: true
JSON Schema格式(适用于数据模型):
yaml
$schema: "http://json-schema.org/draft-07/schema#"
name: DataProcessingConfig
description: Configuration schema for data processing

type: object
required:
  - max_batch_size
  - timeout_seconds
  - check_frequency

properties:
  max_batch_size:
    type: integer
    minimum: 1
    maximum: 10000
    description: Maximum records per batch
    example: 1000

  timeout_seconds:
    type: integer
    minimum: 1
    maximum: 300
    description: Processing timeout in seconds
    example: 60

  check_frequency:
    type: string
    enum: ["realtime", "1min", "5min", "15min"]
    description: How often to check processing status
    example: "1min"

  alert_threshold:
    type: number
    minimum: 0
    maximum: 1.0
    description: Alert when queue depth exceeds this fraction
    default: 0.80
    example: 0.80

6. Usage Examples Section

6. 使用示例章节

Format:
markdown
undefined
格式:
markdown
undefined

Usage Examples

使用示例

Example 1: Successful Validation

示例1:验证成功

Request:
json
{
  "record_type": "METRIC",
  "record_id": "abc123",
  "data": {"value": 100},
  "account_id": "123e4567-e89b-12d3-a456-426614174000"
}
Response:
json
{
  "valid": true,
  "order_id": "987f6543-e21c-43d2-b654-426614174111",
  "warnings": []
}
请求:
json
{
  "record_type": "METRIC",
  "record_id": "abc123",
  "data": {"value": 100},
  "account_id": "123e4567-e89b-12d3-a456-426614174000"
}
响应:
json
{
  "valid": true,
  "order_id": "987f6543-e21c-43d2-b654-426614174111",
  "warnings": []
}

Example 2: Invalid Record Type

示例2:无效记录类型

Request:
json
{
  "record_type": "invalid",
  "record_id": "abc123",
  "data": {"value": 100},
  "account_id": "123e4567-e89b-12d3-a456-426614174000"
}
Response (400 Bad Request):
json
{
  "error_code": "INVALID_RECORD_TYPE",
  "message": "Record type 'invalid' not found in approved list",
  "details": {
    "record_type": "invalid",
    "approved_types": ["METRIC", "EVENT", "LOG"]
  }
}
undefined
请求:
json
{
  "record_type": "invalid",
  "record_id": "abc123",
  "data": {"value": 100},
  "account_id": "123e4567-e89b-12d3-a456-426614174000"
}
响应(400错误请求):
json
{
  "error_code": "INVALID_RECORD_TYPE",
  "message": "Record type 'invalid' not found in approved list",
  "details": {
    "record_type": "invalid",
    "approved_types": ["METRIC", "EVENT", "LOG"]
  }
}
undefined

7. Contract Versioning

7. 契约版本控制

Semantic Versioning: Major.Minor.Patch
Version Policy:
  • Major: Breaking changes (incompatible)
  • Minor: New features (backward compatible)
  • Patch: Bug fixes (backward compatible)
Example:
yaml
openapi: 3.0.3
info:
  title: Data Validation API
  version: 2.1.0  # Major.Minor.Patch
  description: |
    Version 2.1.0 (2025-01-15)
    - Added: optional 'warnings' field in response (minor)
    - Fixed: validation error for edge case data (patch)

    Breaking changes from v1.x:
    - Changed: account_id now requires UUID format (was string)
语义化版本: 主版本.次版本.修订版本
版本策略:
  • 主版本: 破坏性变更(不兼容)
  • 次版本: 新增功能(向后兼容)
  • 修订版本: 错误修复(向后兼容)
示例:
yaml
openapi: 3.0.3
info:
  title: Data Validation API
  version: 2.1.0  # Major.Minor.Patch
  description: |
    Version 2.1.0 (2025-01-15)
    - Added: optional 'warnings' field in response (minor)
    - Fixed: validation error for edge case data (patch)

    Breaking changes from v1.x:
    - Changed: account_id now requires UUID format (was string)

8. SPEC-Ready Scoring System

8. SPEC就绪评分系统

Purpose: Measures CTR maturity and readiness for progression to Technical Specifications (SPEC) phase.
Format in Document Control:
markdown
| **SPEC-Ready Score** | ✅ 95% (Target: ≥90%) |
Status and SPEC-Ready Score Mapping:
SPEC-Ready ScoreRequired Status
≥90%Active
70-89%In Review
<70%Draft
Scoring Criteria:
  • Schema Completeness (35%): All endpoints/models defined, JSON Schema/OpenAPI validation passes, examples provided
  • Error Handling (25%): All error codes documented, retry strategies specified, failure modes covered
  • Quality Attributes (20%): Performance targets, SLA requirements, idempotency specified
  • Traceability (10%): Upstream REQ/ADR linked, consumer/provider identified
  • Documentation (10%): Usage examples, versioning policy, deprecation strategy
Quality Gate: Score <90% blocks SPEC artifact creation.
目的: 衡量CTR的成熟度和进入技术规范(SPEC)阶段的就绪程度。
文档控制中的格式:
markdown
| **SPEC就绪分数** | ✅ 95% (Target: ≥90%) |
状态与SPEC就绪分数映射:
SPEC就绪分数必填状态
≥90%已激活
70-89%审核中
<70%草稿
评分标准:
  • 模式完整性(35%): 所有端点/模型已定义,JSON Schema/OpenAPI验证通过,提供示例
  • 错误处理(25%): 所有错误代码已文档化,指定重试策略,覆盖故障模式
  • 质量属性(20%): 指定性能目标、SLA要求、幂等性
  • 可追溯性(10%): 链接上游REQ/ADR,识别消费者/提供者
  • 文档(10%): 使用示例、版本控制策略、弃用策略
质量门: 分数<90%会阻止SPEC工件创建。

9. Directory Organization by Service Type

9. 按服务类型组织目录

Purpose: Organize contracts by service type for large projects (30+ contracts).
Structure:
CTR/
├── agents/              # Agent-to-agent communication
├── mcp/                 # MCP server contracts
├── infra/               # Infrastructure services
└── shared/              # Cross-cutting contracts
When to Use:
  • <10 contracts: Flat directory
  • 10-30 contracts: Optional subdirectories
  • 30+ contracts: Mandatory subdirectories
Recommendation: Start flat, migrate to subdirectories when 3+ contracts per service type.
目的: 为大型项目(30+个契约)按服务类型组织契约。
结构:
CTR/
├── agents/              # Agent间通信
├── mcp/                 # MCP服务器契约
├── infra/               # 基础设施服务
└── shared/              # 跨领域契约
使用时机:
  • <10个契约: 扁平目录
  • 10-30个契约: 可选子目录
  • 30+个契约: 强制子目录
建议: 从扁平目录开始,当每个服务类型有3+个契约时迁移到子目录。

Tag Format Convention (By Design)

标签格式约定(设计如此)

The SDD framework uses two distinct notation systems for cross-references:
NotationFormatArtifactsPurpose
DashTYPE-NNADR, SPEC, CTRTechnical artifacts - references to files/documents
DotTYPE.NN.TT.SSBRD, PRD, EARS, BDD, SYS, REQ, IMPL, TASKSHierarchical artifacts - references to elements inside documents
Key Distinction:
  • @adr: ADR-033
    → Points to the document
    ADR-033_risk_limit_enforcement.md
  • @brd: BRD.17.01.01
    → Points to element 01.01 inside document
    BRD-017.md
SDD框架使用两种不同的符号系统进行交叉引用:
符号格式工件目的
短横线TYPE-NNADR, SPEC, CTR技术工件 - 引用文件/文档
TYPE.NN.TT.SSBRD, PRD, EARS, BDD, SYS, REQ, IMPL, TASKS分层工件 - 引用文档内的元素
关键区别:
  • @adr: ADR-033
    → 指向文档
    ADR-033_risk_limit_enforcement.md
  • @brd: BRD.17.01.01
    → 指向文档
    BRD-017.md
    内的元素01.01

Unified Element ID Format (MANDATORY)

统一元素ID格式(必填)

For hierarchical requirements (BRD, PRD, EARS, BDD, SYS, REQ, IMPL):
  • Always use:
    TYPE.NN.TT.SS
    (dot separator, 4-segment unified format)
  • Never use:
    TYPE-NN:NNN
    (colon separator - DEPRECATED)
  • Never use:
    TYPE.NN.TT
    (3-segment format - DEPRECATED)
Examples:
  • @brd: BRD.17.01.01
  • @brd: BRD.017.001
    ❌ (old 3-segment format)
对于分层需求(BRD, PRD, EARS, BDD, SYS, REQ, IMPL):
  • 必须使用:
    TYPE.NN.TT.SS
    (点分隔,4段统一格式)
  • 禁止使用:
    TYPE-NN:NNN
    (冒号分隔 - 已弃用)
  • 禁止使用:
    TYPE.NN.TT
    (3段格式 - 已弃用)
示例:
  • @brd: BRD.17.01.01
  • @brd: BRD.017.001
    ❌(旧3段格式)

Cumulative Tagging Requirements

累积标签要求

Layer 8 (CTR): Must include tags from Layers 1-7 (BRD through REQ)
Tag Count: 7 tags
Element Type Codes for Cumulative Tags:
TagArtifactElement TypeCode
@brdBRDBusiness Requirement01
@prdPRDProduct Feature07
@earsEARSEARS Statement25
@bddBDDScenario14
@adrADRDocument reference(dash notation)
@sysSYSSystem Requirement26
@reqREQAtomic Requirement27
Format:
markdown
undefined
第8层(CTR): 必须包含第1-7层(BRD到REQ)的标签
标签数量: 7个标签
累积标签的元素类型代码:
标签工件元素类型代码
@brdBRD业务需求01
@prdPRD产品功能07
@earsEARSEARS声明25
@bddBDD场景14
@adrADR文档引用(短横线符号)
@sysSYS系统需求26
@reqREQ原子需求27
格式:
markdown
undefined

Traceability

可追溯性

Required Tags (Cumulative Tagging Hierarchy - Layer 8):
markdown
@brd: BRD.01.01.03
@prd: PRD.01.07.02
@ears: EARS.01.25.01
@bdd: BDD.01.14.01
@adr: ADR-033, ADR-045
@sys: SYS.01.26.01
@req: REQ.01.27.03
必填标签(累积标签层级 - 第8层):
markdown
@brd: BRD.01.01.03
@prd: PRD.01.07.02
@ears: EARS.01.25.01
@bdd: BDD.01.14.01
@adr: ADR-033, ADR-045
@sys: SYS.01.26.01
@req: REQ.01.27.03

Upstream/Downstream Artifacts

上游/下游工件

Upstream Sources:
  • BRD (Layer 1) - Business requirements
  • PRD (Layer 2) - Product features
  • EARS (Layer 3) - Formal requirements
  • BDD (Layer 4) - Test scenarios
  • ADR (Layer 5) - Architecture decisions
  • SYS (Layer 6) - System requirements
  • REQ (Layer 7) - Atomic requirements (PRIMARY SOURCE - especially Section 3)
Downstream Artifacts:
  • SPEC (Layer 9) - Technical specifications
  • TSPEC (Layer 10) - Test specifications
  • TASKS (Layer 11) - Task breakdown
  • Code (Layer 12) - Implementation code
Same-Type Document Relationships (conditional):
  • @related-ctr: CTR-NN
    - CTRs sharing API context
  • @depends-ctr: CTR-NN
    - CTR that must be completed first
上游来源:
  • BRD(第1层) - 业务需求
  • PRD(第2层) - 产品功能
  • EARS(第3层) - 正式需求
  • BDD(第4层) - 测试场景
  • ADR(第5层) - 架构决策
  • SYS(第6层) - 系统需求
  • REQ(第7层) - 原子需求(主要来源 - 尤其是第3节)
下游工件:
  • SPEC(第9层) - 技术规范
  • TSPEC(第10层) - 测试规范
  • TASKS(第11层) - 任务分解
  • 代码(第12层) - 实现代码
同类型文档关系(有条件):
  • @related-ctr: CTR-NN
    - 共享API上下文的CTR
  • @depends-ctr: CTR-NN
    - 必须先完成的CTR

Validation Checks

验证检查

Tier 1: Errors (Blocking)

第1层:错误(阻塞)

CheckDescription
CHECK 1Required Document Control Fields (9 fields)
CHECK 2Dual-File Format (both .md and .yaml exist)
CHECK 3SPEC-Ready Score format (✅ emoji + percentage + target)
CHECK 4YAML Schema Validation (OpenAPI/JSON Schema valid)
CHECK 5Cumulative Tagging (7-8 upstream tags)
CHECK 6Element ID Format (
CTR.NN.TT.SS
)
检查项描述
检查1必填文档控制字段(9个字段)
检查2双文件格式(.md和.yaml都存在)
检查3SPEC就绪分数格式(✅表情 + 百分比 + 目标)
检查4YAML模式验证(OpenAPI/JSON Schema有效)
检查5累积标签(7-8个上游标签)
检查6元素ID格式(
CTR.NN.TT.SS

Tier 2: Warnings (Recommended)

第2层:警告(推荐)

CheckDescription
CHECK 7Usage Examples (request/response pairs)
CHECK 8Error Handling (error codes documented)
CHECK 9Versioning Policy (semantic versioning)
CHECK 10Validation Rules (schema validation specified)
检查项描述
检查7使用示例(请求/响应对)
检查8错误处理(错误代码已文档化)
检查9版本控制策略(语义化版本)
检查10验证规则(指定模式验证)

Tier 3: Info

第3层:信息

CheckDescription
CHECK 11Directory Organization (subdirectories for 30+ contracts)
CHECK 12Consumer/Provider identified
检查项描述
检查11目录组织(30+个契约使用子目录)
检查12已识别消费者/提供者

Creation Process

创建流程

Step 1: Read Upstream Artifacts

步骤1:阅读上游工件

Focus on REQ Section 3 (Interface Specifications) and Section 4 (Data Schemas).
重点关注REQ第3节(接口规范)和第4节(数据模式)。

Step 2: Reserve ID Number

步骤2:保留ID编号

Check
ai_dev_flow/CTR/
for next available ID number.
ID Numbering Convention: Start with 2 digits and expand only as needed.
  • ✅ Correct: CTR-01, CTR-99, CTR-102
  • ❌ Incorrect: CTR-001, CTR-009 (extra leading zero not required)
检查
ai_dev_flow/CTR/
获取下一个可用的ID编号。
ID编号约定: 从2位数字开始,仅在需要时扩展。
  • ✅ 正确: CTR-01, CTR-99, CTR-102
  • ❌ 错误: CTR-001, CTR-009(不需要额外前导零)

Step 3: Create CTR Files (Dual Format)

步骤3:创建CTR文件(双格式)

Nested Folder Rule (MANDATORY): ALL CTR documents MUST use nested folders regardless of document size.
Location:
  • Standard:
    docs/08_CTR/CTR-NN_{slug}/CTR-NN_{slug}.md
    +
    .yaml
  • Service-based:
    docs/08_CTR/{service_type}/CTR-NN_{slug}/CTR-NN_{slug}.md
    +
    .yaml
On-Demand Folder Creation: Before saving, create the target directory:
bash
undefined
嵌套文件夹规则(必填): 所有CTR文档必须使用嵌套文件夹,无论文档大小。
位置:
  • 标准:
    docs/08_CTR/CTR-NN_{slug}/CTR-NN_{slug}.md
    +
    .yaml
  • 基于服务:
    docs/08_CTR/{service_type}/CTR-NN_{slug}/CTR-NN_{slug}.md
    +
    .yaml
按需创建文件夹: 保存前,创建目标目录:
bash
undefined

Create nested folder (ALWAYS required)

创建嵌套文件夹(始终需要)

mkdir -p docs/08_CTR/CTR-NN_{slug}/
mkdir -p docs/08_CTR/CTR-NN_{slug}/

OR for service-type subdirectory

或针对服务类型子目录

mkdir -p docs/08_CTR/{service_type}/CTR-NN_{slug}/

**Service Types** (when 10+ contracts):
- `agents/` - Agent-to-agent communication
- `mcp/` - MCP server contracts
- `infra/` - Infrastructure services
- `shared/` - Cross-cutting contracts

**Example**:
- Standard: `docs/08_CTR/CTR-01_data_validation/CTR-01_data_validation.md` + `.yaml`
- Service-based: `docs/08_CTR/agents/CTR-01_data_validation/CTR-01_data_validation.md` + `.yaml`

**CRITICAL**: Never create CTR files directly in `docs/08_CTR/` without a nested folder structure.
mkdir -p docs/08_CTR/{service_type}/CTR-NN_{slug}/

**服务类型**(10+个契约时):
- `agents/` - Agent间通信
- `mcp/` - MCP服务器契约
- `infra/` - 基础设施服务
- `shared/` - 跨领域契约

**示例**:
- 标准: `docs/08_CTR/CTR-01_data_validation/CTR-01_data_validation.md` + `.yaml`
- 基于服务: `docs/08_CTR/agents/CTR-01_data_validation/CTR-01_data_validation.md` + `.yaml`

**关键**: 永远不要直接在`docs/08_CTR/`中创建CTR文件,必须使用嵌套文件夹结构。

Step 4: Fill Document Control Section (Markdown)

步骤4:填写文档控制部分(Markdown)

Complete all 9 required fields including SPEC-Ready Score.
完成所有9个必填字段,包括SPEC就绪分数。

Step 5: Write Contract Overview (Markdown)

步骤5:编写契约概述(Markdown)

Summarize purpose, scope, and version.
总结目的、范围和版本。

Step 6: Define YAML Contract

步骤6:定义YAML契约

Choose format:
  • OpenAPI 3.0 for REST APIs
  • JSON Schema for data models
  • AsyncAPI for event-driven systems (if applicable)
选择格式:
  • OpenAPI 3.0 用于REST API
  • JSON Schema 用于数据模型
  • AsyncAPI 用于事件驱动系统(如适用)

Step 7: Add Usage Examples (Markdown)

步骤7:添加使用示例(Markdown)

Provide request/response examples with explanations.
提供带说明的请求/响应示例。

Step 8: Document Validation Rules (Markdown)

步骤8:文档验证规则(Markdown)

Explain schema validation and business rules.
解释模式验证和业务规则。

Step 9: Specify Error Handling (Markdown)

步骤9:指定错误处理(Markdown)

Document error codes and responses.
文档化错误代码和响应。

Step 10: Add Cumulative Tags

步骤10:添加累积标签

Include all 7-8 upstream tags (@brd through @req/impl).
包含所有7-8个上游标签(@brd到@req/impl)。

Step 11: Create/Update Traceability Matrix

步骤11:创建/更新可追溯性矩阵

MANDATORY: Update
ai_dev_flow/CTR/CTR-00_TRACEABILITY_MATRIX-TEMPLATE.md
必填: 更新
ai_dev_flow/CTR/CTR-00_TRACEABILITY_MATRIX-TEMPLATE.md

Step 12: Validate CTR

步骤12:验证CTR

bash
undefined
bash
undefined

YAML schema validation

YAML模式验证

yamllint ai_dev_flow/CTR/CTR-01_*.yaml
yamllint ai_dev_flow/CTR/CTR-01_*.yaml

OpenAPI validation

OpenAPI验证

openapi-spec-validator ai_dev_flow/CTR/CTR-01_*.yaml
openapi-spec-validator ai_dev_flow/CTR/CTR-01_*.yaml

Cumulative tagging

累积标签

python ai_dev_flow/scripts/validate_tags_against_docs.py --artifact CTR-01 --expected-layers brd,prd,ears,bdd,adr,sys,req,impl --strict
undefined
python ai_dev_flow/scripts/validate_tags_against_docs.py --artifact CTR-01 --expected-layers brd,prd,ears,bdd,adr,sys,req,impl --strict
undefined

Step 13: Commit Changes

步骤13:提交变更

Commit both files (.md and .yaml) and traceability matrix.
提交两个文件(.md和.yaml)和可追溯性矩阵。

Validation

验证

Automated Validation

自动化验证

bash
undefined
bash
undefined

Quality gates

质量门

scripts/validate_quality_gates.sh ai_dev_flow/CTR/CTR-01_*.md
scripts/validate_quality_gates.sh ai_dev_flow/CTR/CTR-01_*.md

YAML validation

YAML验证

yamllint ai_dev_flow/CTR/CTR-01_*.yaml
yamllint ai_dev_flow/CTR/CTR-01_*.yaml

OpenAPI validation (if using OpenAPI)

OpenAPI验证(如果使用OpenAPI)

openapi-spec-validator ai_dev_flow/CTR/CTR-01_*.yaml
openapi-spec-validator ai_dev_flow/CTR/CTR-01_*.yaml

CTR-specific validation (includes dual-file check)

CTR专属验证(包含双文件检查)

./ai_dev_flow/scripts/validate_ctr.sh CTR-01
./ai_dev_flow/scripts/validate_ctr.sh CTR-01

Cumulative tagging

累积标签

python ai_dev_flow/scripts/validate_tags_against_docs.py
--artifact CTR-01
--expected-layers brd,prd,ears,bdd,adr,sys,req,impl
--strict
undefined
python ai_dev_flow/scripts/validate_tags_against_docs.py
--artifact CTR-01
--expected-layers brd,prd,ears,bdd,adr,sys,req,impl
--strict
undefined

Manual Checklist

手动检查清单

  • Both files created (.md and .yaml)
  • Document Control complete (9 fields)
  • SPEC-Ready Score format correct (✅ NN% (Target: ≥90%))
  • Contract Overview clear
  • Business Context explains why (links to REQ)
  • YAML contract valid (OpenAPI/JSON Schema)
  • Usage Examples comprehensive
  • Error handling documented
  • Validation rules specified
  • Version number semantic (Major.Minor.Patch)
  • Cumulative tags: @brd through @req/impl (7-8 tags)
  • Element IDs use
    CTR.NN.TT.SS
    format
  • Traceability matrix updated
  • 已创建两个文件(.md和.yaml)
  • 文档控制已完成(9个字段)
  • SPEC就绪分数格式正确(✅ NN% (Target: ≥90%))
  • 契约概述清晰
  • 业务上下文解释了原因(链接到REQ)
  • YAML契约有效(OpenAPI/JSON Schema)
  • 使用示例全面
  • 错误处理已文档化
  • 验证规则已指定
  • 版本号为语义化版本(Major.Minor.Patch)
  • 累积标签: @brd到@req/impl(7-8个标签)
  • 元素ID使用
    CTR.NN.TT.SS
    格式
  • 可追溯性矩阵已更新

Diagram Standards

图表标准

All diagrams MUST use Mermaid syntax. Text-based diagrams (ASCII art, box drawings) are prohibited. See:
ai_dev_flow/DIAGRAM_STANDARDS.md
and
mermaid-gen
skill.
所有图表必须使用Mermaid语法。禁止使用基于文本的图表(ASCII艺术、框式绘图)。 参考:
ai_dev_flow/DIAGRAM_STANDARDS.md
mermaid-gen
技能。

Common Pitfalls

常见陷阱

  1. Single file only: Must create BOTH .md and .yaml files
  2. Invalid YAML: Must validate with yamllint and openapi-spec-validator
  3. Missing examples: Usage Examples section critical for adoption
  4. Vague validation: Schema validation must be precise and testable
  5. Missing cumulative tags: Layer 9 must include all 7-8 upstream tags
  6. Skipping when needed: Don't skip if multiple teams need shared contract
  7. Wrong element IDs: Use
    CTR.NN.TT.SS
    , not legacy
    INT-XXX
    ,
    MODEL-XXX
    ,
    CLAUSE-XXX
  8. Wrong cumulative tag codes: Use correct element type codes (EARS=25, BDD=14, SYS=26, REQ=27, IMPL=29)
  1. 仅单个文件: 必须同时创建.md和.yaml文件
  2. 无效YAML: 必须使用yamllint和openapi-spec-validator验证
  3. 缺少示例: 使用示例部分对采用至关重要
  4. 模糊的验证: 模式验证必须精确且可测试
  5. 缺少累积标签: 第9层必须包含所有7-8个上游标签
  6. 需要时跳过: 如果多个团队需要共享契约,不要跳过
  7. 错误的元素ID: 使用
    CTR.NN.TT.SS
    ,而非旧格式
    INT-XXX
    ,
    MODEL-XXX
    ,
    CLAUSE-XXX
  8. 错误的累积标签代码: 使用正确的元素类型代码(EARS=25, BDD=14, SYS=26, REQ=27, IMPL=29)

Post-Creation Validation (MANDATORY - NO CONFIRMATION)

创建后验证(必填 - 无需确认)

CRITICAL: Execute this validation loop IMMEDIATELY after document creation. Do NOT proceed to next document until validation passes.
关键: 文档创建后立即执行此验证循环。在验证通过前,不要继续下一个文档。

Automatic Validation Loop

自动验证循环

LOOP:
  1. Run: python ai_dev_flow/scripts/validate_cross_document.py --document {doc_path} --auto-fix
  2. IF errors fixed: GOTO LOOP (re-validate)
  3. IF warnings fixed: GOTO LOOP (re-validate)
  4. IF unfixable issues: Log for manual review, continue
  5. IF clean: Mark VALIDATED, proceed
LOOP:
  1. 运行: python ai_dev_flow/scripts/validate_cross_document.py --document {doc_path} --auto-fix
  2. 如果错误已修复: 回到LOOP(重新验证)
  3. 如果警告已修复: 回到LOOP(重新验证)
  4. 如果存在无法修复的问题: 记录以便手动审核,继续
  5. 如果无问题: 标记为已验证,继续

Validation Command

验证命令

bash
undefined
bash
undefined

Per-document validation (Phase 1)

单文档验证(第1阶段)

python ai_dev_flow/scripts/validate_cross_document.py --document docs/CTR/CTR-NN_slug.md --auto-fix
python ai_dev_flow/scripts/validate_cross_document.py --document docs/CTR/CTR-NN_slug.md --auto-fix

Layer validation (Phase 2) - run when all CTR documents complete

层级验证(第2阶段) - 所有CTR文档完成后运行

python ai_dev_flow/scripts/validate_cross_document.py --layer CTR --auto-fix
undefined
python ai_dev_flow/scripts/validate_cross_document.py --layer CTR --auto-fix
undefined

Layer-Specific Upstream Requirements

层级专属上游要求

This LayerRequired Upstream TagsCount
CTR (Layer 8)@brd, @prd, @ears, @bdd, @adr, @sys, @req7 tags
本层级必填上游标签数量
CTR(第8层)@brd, @prd, @ears, @bdd, @adr, @sys, @req7个标签

Auto-Fix Actions (No Confirmation Required)

自动修复操作(无需确认)

IssueFix Action
Missing upstream tagAdd with upstream document reference
Invalid tag formatCorrect to TYPE.NN.TT.SS (4-segment) or TYPE-NN format
Broken linkRecalculate path from current location
Missing traceability sectionInsert from template
问题修复操作
缺少上游标签添加上游文档引用
无效标签格式修正为TYPE.NN.TT.SS(4段)或TYPE-NN格式
链接损坏从当前位置重新计算路径
缺少可追溯性部分从模板插入

Validation Codes Reference

验证代码参考

CodeDescriptionSeverity
XDOC-001Referenced requirement ID not foundERROR
XDOC-002Missing cumulative tagERROR
XDOC-003Upstream document not foundERROR
XDOC-006Tag format invalidERROR
XDOC-007Gap in cumulative tag chainERROR
XDOC-009Missing traceability sectionERROR
代码描述严重程度
XDOC-001引用的需求ID未找到错误
XDOC-002缺少累积标签错误
XDOC-003上游文档未找到错误
XDOC-006标签格式无效错误
XDOC-007累积标签链存在缺口错误
XDOC-009缺少可追溯性部分错误

Quality Gate

质量门

Blocking: YES - Cannot proceed to next document until Phase 1 validation passes with 0 errors.

阻塞: 是 - 第1阶段验证必须无错误通过,才能继续下一个文档。

Next Skill

下一个技能

After creating CTR (or skipping this optional layer), use:
doc-spec
- Create Technical Specifications (Layer 9)
The SPEC will:
  • Reference CTR (if created) or REQ as upstream source
  • Include all 7-8 upstream tags
  • Use YAML format
  • Define implementation details
  • Achieve 100% implementation-readiness
创建CTR(或跳过此可选层级)后,使用:
doc-spec
- 创建技术规范(第9层)
SPEC将:
  • 引用CTR(如已创建)或REQ作为上游来源
  • 包含所有7-8个上游标签
  • 使用YAML格式
  • 定义实现细节
  • 达到100%实现就绪

Reference Documents

参考文档

For supplementary documentation related to CTR artifacts:
  • Format:
    CTR-REF-NNN_{slug}.md
  • Skill: Use
    doc-ref
    skill
  • Validation: Minimal (non-blocking)
  • Examples: API style guides, contract versioning policies
有关CTR工件的补充文档:
  • 格式:
    CTR-REF-NNN_{slug}.md
  • 技能: 使用
    doc-ref
    技能
  • 验证: 最小化(非阻塞)
  • 示例: API风格指南、契约版本控制策略

Related Resources

相关资源

  • Template:
    ai_dev_flow/08_CTR/CTR-TEMPLATE.md
    (primary authority)
  • Schema Template:
    ai_dev_flow/08_CTR/CTR-TEMPLATE.yaml
    (machine-readable)
  • CTR Creation Rules:
    ai_dev_flow/08_CTR/CTR_CREATION_RULES.md
  • CTR Validation Rules:
    ai_dev_flow/08_CTR/CTR_VALIDATION_RULES.md
  • CTR README:
    ai_dev_flow/08_CTR/README.md
  • OpenAPI Specification: https://spec.openapis.org/oas/v3.0.3
  • JSON Schema: https://json-schema.org/
  • Shared Standards:
    .claude/skills/doc-flow/SHARED_CONTENT.md
  • Naming Standards:
    .claude/skills/doc-naming/SKILL.md
    (ID and naming conventions)
Section Templates (for documents >25K tokens):
  • Index template:
    ai_dev_flow/08_CTR/CTR-SECTION-0-TEMPLATE.md
  • Content template:
    ai_dev_flow/08_CTR/CTR-SECTION-TEMPLATE.md
  • Reference:
    ai_dev_flow/ID_NAMING_STANDARDS.md
    (Section-Based File Splitting)
  • 模板:
    ai_dev_flow/08_CTR/CTR-TEMPLATE.md
    (主要权威来源)
  • 模式模板:
    ai_dev_flow/08_CTR/CTR-TEMPLATE.yaml
    (机器可读)
  • CTR创建规则:
    ai_dev_flow/08_CTR/CTR_CREATION_RULES.md
  • CTR验证规则:
    ai_dev_flow/08_CTR/CTR_VALIDATION_RULES.md
  • CTR README:
    ai_dev_flow/08_CTR/README.md
  • OpenAPI规范: https://spec.openapis.org/oas/v3.0.3
  • JSON Schema: https://json-schema.org/
  • 共享标准:
    .claude/skills/doc-flow/SHARED_CONTENT.md
  • 命名标准:
    .claude/skills/doc-naming/SKILL.md
    (ID和命名约定)
章节模板(适用于超过25K令牌的文档):
  • 索引模板:
    ai_dev_flow/08_CTR/CTR-SECTION-0-TEMPLATE.md
  • 内容模板:
    ai_dev_flow/08_CTR/CTR-SECTION-TEMPLATE.md
  • 参考:
    ai_dev_flow/ID_NAMING_STANDARDS.md
    (基于章节的文件拆分)

Quick Reference

快速参考

CTR Purpose: Define API contracts and data schemas
Layer: 8 (Optional)
Element ID Format:
CTR.NN.TT.SS
  • Interface = 16
  • Data Model = 17
  • Contract Clause = 20
Removed Patterns: INT-XXX, MODEL-XXX, CLAUSE-XXX, IF-XXX, DM-XXX, CC-XXX
Document Control Fields: 9 required
Tags Required: @brd through @req (7 tags)
Format: Dual-file (.md + .yaml)
SPEC-Ready Score: ≥90% required for "Active" status
YAML Standards:
  • OpenAPI 3.0 for REST APIs
  • JSON Schema for data models
  • AsyncAPI for event-driven (if applicable)
Key Sections:
  • Contract Overview
  • Business Context (link to REQ Section 3)
  • YAML contract definition
  • Usage Examples
  • Validation Rules
  • Error Handling
Directory Organization: Subdirectories recommended for 30+ contracts
Optional: Skip this layer if contracts are simple or embedded in REQ
Next: doc-spec

CTR目的: 定义API契约和数据模式
层级: 8(可选)
元素ID格式:
CTR.NN.TT.SS
  • 接口 = 16
  • 数据模型 = 17
  • 契约条款 = 20
已移除模式: INT-XXX, MODEL-XXX, CLAUSE-XXX, IF-XXX, DM-XXX, CC-XXX
文档控制字段: 9个必填
必填标签: @brd到@req(7个标签)
格式: 双文件(.md + .yaml)
SPEC就绪分数: "已激活"状态需要≥90%
YAML标准:
  • REST API使用OpenAPI 3.0
  • 数据模型使用JSON Schema
  • 事件驱动系统使用AsyncAPI(如适用)
关键章节:
  • 契约概述
  • 业务上下文(链接到REQ第3节)
  • YAML契约定义
  • 使用示例
  • 验证规则
  • 错误处理
目录组织: 30+个契约建议使用子目录
可选: 如果契约简单或已嵌入REQ,可跳过此层级
下一步: doc-spec

Version History

版本历史

VersionDateChangesAuthor
1.1.02026-02-08Updated layer assignment from 9 to 8 per LAYER_REGISTRY v1.6; updated downstream artifacts (SPEC Layer 9, TSPEC Layer 10, TASKS Layer 11); removed IMPL from upstreamSystem
1.0.02025-01-15Initial skill definitionSystem
版本日期变更作者
1.1.02026-02-08根据LAYER_REGISTRY v1.6将层级从9更新为8;更新下游工件(SPEC第9层、TSPEC第10层、TASKS第11层);从上游移除IMPL系统
1.0.02025-01-15初始技能定义系统