[
  {
    "path": ".gitignore",
    "content": "node_modules/\ndist/\n*.tsbuildinfo\n.DS_Store\n*.log\ncoverage/\n.env\n.manus-logs/\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Brief\n\nThank you for your interest in contributing to Brief! This document provides guidelines for contributing to the project.\n\n## Getting Started\n\n1. Fork the repository.\n2. Clone your fork: `git clone https://github.com/openperf/brief.git`\n3. Install dependencies: `pnpm install`\n4. Create a branch: `git checkout -b feature/your-feature`\n\n## Development\n\nThe project uses a pnpm workspace with the following structure:\n\n- `packages/brief-sdk/` — The core TypeScript SDK\n- `examples/` — Runnable example scripts\n- `docs/` — Design documents\n\n### Building\n\n```bash\npnpm build\n```\n\n### Testing\n\n```bash\ncd packages/brief-sdk\npnpm test\n```\n\n### Running Examples\n\n```bash\npnpm example:simple\npnpm example:cascade\npnpm example:fanout\n```\n\n## Pull Request Process\n\n1. Ensure all tests pass (`pnpm test`).\n2. Update documentation if you change the public API.\n3. Add tests for new features.\n4. Keep PRs focused — one feature or fix per PR.\n5. Write clear commit messages.\n\n## Code Style\n\n- Use TypeScript strict mode.\n- Prefer `const` over `let`.\n- Use JSDoc comments for public APIs.\n- Follow the existing code patterns in the project.\n\n## Reporting Issues\n\nWhen reporting issues, please include:\n\n- A clear description of the problem.\n- Steps to reproduce.\n- Expected vs. actual behavior.\n- Your environment (Node.js version, OS).\n\n## License\n\nBy contributing, you agree that your contributions will be licensed under the MIT License.\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2026 Brief Contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README-zh.md",
    "content": "<div align=\"center\">\n\n# Brief\n\n### 首个 Agent 显式委托开放协议\n\n**将混乱的多 Agent 交接变成结构化、可审计的任务简报。**\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.4+-3178C6.svg)](https://www.typescriptlang.org/)\n[![Tests](https://img.shields.io/badge/Tests-37%20passed-brightgreen.svg)](#测试)\n[![Protocol Version](https://img.shields.io/badge/Protocol-v1.2.0-orange.svg)](docs/design.md)\n\n[English](README.md) | [中文](README-zh.md)\n\n</div>\n\n---\n\n## 为什么需要 Brief\n\nAI Agent 生态已经有了**工具调用**（[MCP](https://modelcontextprotocol.io/)）、**Agent 发现与传输**（[A2A](https://github.com/google/A2A)）和 **Agent 能力描述**（[Agent Skills](https://github.com/anthropics/agent-skills)）的标准。但最关键的交互——**一个 Agent 如何正式地将任务委托给另一个 Agent**——至今没有标准。\n\nCognition 团队（Devin 的创造者）在其影响深远的文章 [*\"Don't Build Multi-Agents\"*](https://cognition.ai/blog/dont-build-multi-agents) 中精确地识别了这个问题，称之为**\"隐式甩锅\"（Implicit Handoff）**：Agent 在传递任务时缺乏结构化上下文，导致决策冲突、上下文丢失和脆弱的系统。他们的诊断是正确的，但我们认为答案不是放弃多 Agent 架构，而是**将委托本身形式化**。\n\n**Brief 是首个专门解决这一问题的开放协议。** 它引入了一种标准化、人类可读的 Agent 间任务委托格式——填补了 *Agent 如何通信*（A2A）和 *Agent 能做什么*（MCP/Skills）之间缺失的语义层。\n\n## 工作原理\n\n整个协议就是**两个 Markdown 文件**：\n\n```\nAgent A: 发送 brief-001.brief.md\n  \"这是我需要什么、为什么需要、以及期望你返回什么。\"\n\nAgent B: 发送 brief-001.response.md\n  \"这是我做了什么、以及我交付的成果。\"\n```\n\n就这么简单。没有新的 DSL，没有二进制格式，没有框架锁定。会写 Markdown 就能用 Brief。\n\n## 生态定位\n\nBrief 不是又一个框架。它是一个**语义层**，与现有标准协同工作，而非替代：\n\n```\n┌─────────────────────────────────────────────────┐\n│                   你的应用                        │\n├─────────────────────────────────────────────────┤\n│  Brief 协议       (.brief.md / .response.md)    │  ← 做什么\n├─────────────────────────────────────────────────┤\n│  A2A 协议         (传输与发现)                    │  ← 怎么找到和通信\n├─────────────────────────────────────────────────┤\n│  MCP 协议         (工具调用)                      │  ← 怎么使用工具\n├─────────────────────────────────────────────────┤\n│  Agent Skills     (SKILL.md)                    │  ← Agent 知道什么\n└─────────────────────────────────────────────────┘\n```\n\n## 为什么选择 Brief？\n\n| 特性 | Brief | 临时多 Agent 方案 | 单体 Agent |\n|------|-------|-----------------|-----------|\n| 上下文隔离 | **显式契约** | 共享内存（被污染） | 不适用 |\n| 可审计性 | **完整追踪日志** | 黑盒 | 单一日志 |\n| 级联委托 (A→B→C→D) | **内置深度控制** | 手动编排 | 不可能 |\n| 扇出 (A→B∥C) | **原生支持** | 复杂编排 | 不可能 |\n| 学习成本 | **会写 Markdown 就行** | 学习框架 API | 不适用 |\n| 生态兼容 | **与 MCP + A2A 协作** | 替代一切 | 不适用 |\n\n## 快速开始\n\n### 安装\n\n```bash\nnpm install brief-sdk\n# 或\npnpm add brief-sdk\n```\n\n### 创建 Brief（委托方）\n\n```typescript\nimport { Brief } from 'brief-sdk';\n\nconst brief = Brief.create({\n  delegator: 'agent-orchestrator',\n  delegatee: 'agent-code-reviewer',\n  body: `# 简报：审查 PR #42\n\n## 目标\n审查 OAuth 2.0 迁移代码的安全问题。\n\n## 关键约束\n- 重点关注 token 的处理和存储。\n- 检查 N+1 查询问题。\n\n## 期望交付物\n1. 审查摘要及发现。\n2. 批准或拒绝建议。`,\n});\n\n// brief.content 是一个合法的 .brief.md 字符串——用任何方式发送它\nconsole.log(brief.content);\n```\n\n### 接收并响应（被委托方）\n\n```typescript\nimport { Brief } from 'brief-sdk';\n\nconst incoming = Brief.parse(receivedMarkdown);\n\nconsole.log(incoming.delegator);  // \"agent-orchestrator\"\nconsole.log(incoming.isSubBrief); // false\n\n// 执行你的工作...\nconst results = await myAgent.review(incoming.body);\n\n// 创建结构化响应\nconst response = incoming.createResponse({\n  status: 'success',\n  body: `# 审查完成\n\n## 发现\n- 批准，有少量建议。\n- 在 auth/handler.ts 中发现未使用的导入。\n\n## 建议\n**批准** — 修复小问题后合并。`,\n});\n\n// response.content 是一个合法的 .response.md 字符串\n```\n\n### 级联委托 (A → B → C)\n\n```typescript\nconst parentBrief = Brief.parse(receivedMarkdown);\n\n// 创建子简报——parentId 和深度自动设置\nconst subBrief = parentBrief.createSubBrief({\n  delegator: 'agent-fullstack-dev',\n  delegatee: 'agent-docs-writer',\n  body: '# 为新端点编写 API 文档。',\n});\n\nconsole.log(subBrief.isSubBrief);  // true\nconsole.log(subBrief.parentId);    // parentBrief.id\n```\n\n### 追踪整条链路\n\n```typescript\nimport { Trace } from 'brief-sdk';\n\nconst trace = Trace.create();\n\ntrace.append({\n  agent: 'agent-orchestrator',\n  action: '委托了代码审查任务。',\n  briefId: 'brief-001',\n});\n\ntrace.append({\n  agent: 'agent-code-reviewer',\n  action: '审查完成。状态：成功。',\n  briefId: 'brief-001',\n});\n\n// 序列化为 trace.md\nconsole.log(trace.toString());\n```\n\n## 协议规范\n\nBrief 文档是一个标准的 Markdown 文件，带有 YAML frontmatter：\n\n### `.brief.md`（请求）\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-orchestrator\"\ndelegatee: \"agent-code-reviewer\"\ntimestamp: \"2026-02-06T03:55:00Z\"\n---\n\n# 简报：你的任务标题\n\n## 1. 目标\n需要做什么。\n\n## 2. 上下文\n为什么要做，以及相关背景。\n\n## 3. 约束\n规则和限制。\n\n## 4. 期望交付物\n需要返回什么。\n```\n\n### `.response.md`（响应）\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nstatus: \"success\"\ntimestamp: \"2026-02-06T04:30:00Z\"\n---\n\n# 响应：任务完成\n\n## 1. 摘要\n做了什么。\n\n## 2. 交付产物\n输出的链接和引用。\n```\n\n### 级联字段\n\n多级委托时，在 frontmatter 中添加以下可选字段：\n\n| 字段 | 类型 | 说明 |\n|------|------|------|\n| `parentId` | `string` | 将此简报链接到父简报 |\n| `maxDepth` | `number` | 允许的最大委托深度 |\n| `currentDepth` | `number` | 当前在链中的深度 |\n\n## 示例\n\n`examples/` 目录包含三个可运行的演示：\n\n```bash\n# 简单的 A → B 委托\npnpm example:simple\n\n# 级联 A → B → C 链\npnpm example:cascade\n\n# 扇出 A → (B ∥ C) 并扇入\npnpm example:fanout\n```\n\n## 测试\n\n```bash\ncd packages/brief-sdk\npnpm test\n```\n\n```\n ✓ __tests__/parser.test.ts    (9 tests)\n ✓ __tests__/brief.test.ts     (10 tests)\n ✓ __tests__/response.test.ts  (7 tests)\n ✓ __tests__/trace.test.ts     (11 tests)\n\n Test Files  4 passed (4)\n      Tests  37 passed (37)\n```\n\n## 项目结构\n\n```\nbrief/\n├── packages/brief-sdk/     # 核心 TypeScript SDK\n│   ├── src/\n│   │   ├── brief.ts         # Brief 类（创建、解析、子委托）\n│   │   ├── response.ts      # BriefResponse 类\n│   │   ├── trace.ts         # Trace 审计日志\n│   │   ├── parser.ts        # Markdown + YAML frontmatter 解析器\n│   │   ├── validator.ts     # Schema 校验\n│   │   ├── types.ts         # TypeScript 类型定义\n│   │   └── index.ts         # 公共 API 导出\n│   └── __tests__/           # 37 个单元测试\n├── examples/\n│   ├── 01-simple-delegation/  # A → B\n│   ├── 02-cascade-chain/      # A → B → C\n│   └── 03-fan-out/            # A → (B ∥ C)\n├── docs/                    # 设计文档与竞品分析\n│   ├── design.md              # 协议设计（英文）\n│   ├── design-zh.md           # 协议设计（中文）\n│   ├── competitive-analysis.md    # 市场分析（英文）\n│   └── competitive-analysis-zh.md # 市场分析（中文）\n└── README.md\n```\n\n## 贡献\n\n欢迎贡献！请参阅 [CONTRIBUTING.md](CONTRIBUTING.md) 了解指南。\n\n## 许可证\n\n[MIT](LICENSE)\n\n---\n\n<div align=\"center\">\n\n**Brief** — 因为 Agent 值得一份正式的简报，而不是含糊的甩锅。\n\n</div>\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n\n# Brief\n\n### The First Open Protocol for Explicit Agent Delegation\n\n**Turn chaotic multi-agent handoffs into structured, auditable task briefings.**\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.4+-3178C6.svg)](https://www.typescriptlang.org/)\n[![Tests](https://img.shields.io/badge/Tests-37%20passed-brightgreen.svg)](#testing)\n[![Protocol Version](https://img.shields.io/badge/Protocol-v1.2.0-orange.svg)](docs/design.md)\n\n[English](README.md) | [中文](README-zh.md)\n\n</div>\n\n---\n\n## Why Brief Exists\n\nThe AI agent ecosystem now has established standards for **tool invocation** ([MCP](https://modelcontextprotocol.io/)), **agent discovery and transport** ([A2A](https://github.com/google/A2A)), and **agent capabilities** ([Agent Skills](https://github.com/anthropics/agent-skills)). Yet the most critical interaction — **how one agent formally delegates a task to another** — remains unstandardized.\n\nThe Cognition team (creators of Devin) identified this exact gap in their influential post [*\"Don't Build Multi-Agents\"*](https://cognition.ai/blog/dont-build-multi-agents), calling it the **\"Implicit Handoff\"** problem: agents pass tasks without structured context, leading to decision conflicts, context loss, and fragile systems. Their diagnosis was precise. But rather than abandoning multi-agent architectures, we believe the answer is to **formalize the delegation itself**.\n\n**Brief is the first open protocol dedicated to solving this problem.** It introduces a standardized, human-readable format for inter-agent task delegation — filling the missing semantic layer between *how agents communicate* (A2A) and *what agents can do* (MCP/Skills).\n\n## How It Works\n\nThe entire protocol is **two Markdown files**:\n\n```\nAgent A: sends brief-001.brief.md\n  \"Here's exactly what I need, why, and what I expect back.\"\n\nAgent B: sends brief-001.response.md\n  \"Here's exactly what I did and what I'm delivering.\"\n```\n\nThat's it. No new DSL, no binary format, no framework lock-in. If you can write Markdown, you can use Brief.\n\n## Ecosystem Position\n\nBrief is not another framework. It is a **semantic layer** designed to complement — never replace — existing standards:\n\n```\n┌─────────────────────────────────────────────────┐\n│                  Your Application                │\n├─────────────────────────────────────────────────┤\n│  Brief Protocol    (.brief.md / .response.md)   │  ← What to do\n├─────────────────────────────────────────────────┤\n│  A2A Protocol      (Transport & Discovery)      │  ← How to find & talk\n├─────────────────────────────────────────────────┤\n│  MCP Protocol      (Tool Invocation)            │  ← How to use tools\n├─────────────────────────────────────────────────┤\n│  Agent Skills      (SKILL.md)                   │  ← What agents know\n└─────────────────────────────────────────────────┘\n```\n\n## Why Brief?\n\n| Feature | Brief | Ad-hoc Multi-Agent | Single Monolithic Agent |\n|---------|-------|-------------------|------------------------|\n| Context isolation | **Explicit contract** | Shared memory (polluted) | N/A |\n| Auditability | **Full trace log** | Black box | Single log |\n| Cascading (A→B→C→D) | **Built-in depth control** | Manual wiring | Not possible |\n| Fan-out (A→B∥C) | **Native support** | Complex orchestration | Not possible |\n| Learning curve | **Write Markdown** | Learn framework API | N/A |\n| Ecosystem fit | **Complements MCP + A2A** | Replaces everything | N/A |\n\n## Quick Start\n\n### Install\n\n```bash\nnpm install brief-sdk\n# or\npnpm add brief-sdk\n```\n\n### Create a Brief (Delegator Side)\n\n```typescript\nimport { Brief } from 'brief-sdk';\n\nconst brief = Brief.create({\n  delegator: 'agent-orchestrator',\n  delegatee: 'agent-code-reviewer',\n  body: `# Briefing: Review PR #42\n\n## Objective\nReview the OAuth 2.0 migration code for security issues.\n\n## Key Constraints\n- Focus on token handling and storage.\n- Check for N+1 queries.\n\n## Expected Deliverables\n1. Review summary with findings.\n2. Approve or reject recommendation.`,\n});\n\n// brief.content is a valid .brief.md string — send it however you want\nconsole.log(brief.content);\n```\n\n### Receive and Respond (Delegatee Side)\n\n```typescript\nimport { Brief } from 'brief-sdk';\n\nconst incoming = Brief.parse(receivedMarkdown);\n\nconsole.log(incoming.delegator);  // \"agent-orchestrator\"\nconsole.log(incoming.isSubBrief); // false\n\n// Do your work...\nconst results = await myAgent.review(incoming.body);\n\n// Create a structured response\nconst response = incoming.createResponse({\n  status: 'success',\n  body: `# Review Complete\n\n## Findings\n- Approved with minor suggestions.\n- Found unused import in auth/handler.ts.\n\n## Recommendation\n**Approve** — merge after addressing minor issues.`,\n});\n\n// response.content is a valid .response.md string\n```\n\n### Cascading Delegation (A → B → C)\n\n```typescript\nconst parentBrief = Brief.parse(receivedMarkdown);\n\n// Create a sub-brief — parentId and depth are set automatically\nconst subBrief = parentBrief.createSubBrief({\n  delegator: 'agent-fullstack-dev',\n  delegatee: 'agent-docs-writer',\n  body: '# Write API docs for the new endpoints.',\n});\n\nconsole.log(subBrief.isSubBrief);  // true\nconsole.log(subBrief.parentId);    // parentBrief.id\n```\n\n### Trace the Entire Chain\n\n```typescript\nimport { Trace } from 'brief-sdk';\n\nconst trace = Trace.create();\n\ntrace.append({\n  agent: 'agent-orchestrator',\n  action: 'Delegated code review.',\n  briefId: 'brief-001',\n});\n\ntrace.append({\n  agent: 'agent-code-reviewer',\n  action: 'Completed review. Status: success.',\n  briefId: 'brief-001',\n});\n\n// Serialize to trace.md\nconsole.log(trace.toString());\n```\n\n## Protocol Specification\n\nA Brief document is a standard Markdown file with YAML frontmatter:\n\n### `.brief.md` (The Request)\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-orchestrator\"\ndelegatee: \"agent-code-reviewer\"\ntimestamp: \"2026-02-06T03:55:00Z\"\n---\n\n# Briefing: Your Task Title\n\n## 1. Objective\nWhat needs to be done.\n\n## 2. Context\nWhy it needs to be done and relevant background.\n\n## 3. Constraints\nRules and limitations.\n\n## 4. Expected Deliverables\nWhat to return.\n```\n\n### `.response.md` (The Result)\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nstatus: \"success\"\ntimestamp: \"2026-02-06T04:30:00Z\"\n---\n\n# Response: Task Complete\n\n## 1. Summary\nWhat was done.\n\n## 2. Delivered Artifacts\nLinks and references to outputs.\n```\n\n### Cascading Fields\n\nFor multi-level delegation, add these optional fields to the frontmatter:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `parentId` | `string` | Links this brief to a parent brief |\n| `maxDepth` | `number` | Maximum allowed delegation depth |\n| `currentDepth` | `number` | Current depth in the chain |\n\n## Examples\n\nThe `examples/` directory contains three runnable demos:\n\n```bash\n# Simple A → B delegation\npnpm example:simple\n\n# Cascading A → B → C chain\npnpm example:cascade\n\n# Fan-out A → (B ∥ C) with fan-in\npnpm example:fanout\n```\n\n## Testing\n\n```bash\ncd packages/brief-sdk\npnpm test\n```\n\n```\n ✓ __tests__/parser.test.ts    (9 tests)\n ✓ __tests__/brief.test.ts     (10 tests)\n ✓ __tests__/response.test.ts  (7 tests)\n ✓ __tests__/trace.test.ts     (11 tests)\n\n Test Files  4 passed (4)\n      Tests  37 passed (37)\n```\n\n## Project Structure\n\n```\nbrief/\n├── packages/brief-sdk/     # Core TypeScript SDK\n│   ├── src/\n│   │   ├── brief.ts         # Brief class (create, parse, sub-delegate)\n│   │   ├── response.ts      # BriefResponse class\n│   │   ├── trace.ts         # Trace audit log\n│   │   ├── parser.ts        # Markdown + YAML frontmatter parser\n│   │   ├── validator.ts     # Schema validation\n│   │   ├── types.ts         # TypeScript type definitions\n│   │   └── index.ts         # Public API exports\n│   └── __tests__/           # 37 unit tests\n├── examples/\n│   ├── 01-simple-delegation/  # A → B\n│   ├── 02-cascade-chain/      # A → B → C\n│   └── 03-fan-out/            # A → (B ∥ C)\n├── docs/                    # Design documents & competitive analysis\n│   ├── design.md              # Protocol design (EN)\n│   ├── design-zh.md           # Protocol design (ZH)\n│   ├── competitive-analysis.md    # Market analysis (EN)\n│   └── competitive-analysis-zh.md # Market analysis (ZH)\n└── README.md\n```\n\n## Contributing\n\nWe welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.\n\n## License\n\n[MIT](LICENSE)\n\n---\n\n<div align=\"center\">\n\n**Brief** — Because agents deserve proper briefings, not vague handoffs.\n\n</div>\n"
  },
  {
    "path": "docs/competitive-analysis-zh.md",
    "content": "# Brief Protocol：竞品分析与市场定位\n\n**作者**：Manus AI\n**日期**：2026年2月6日\n**版本**：1.0\n\n---\n\n## 摘要\n\n本报告评估了 **Brief Protocol**（一个用于显式 Agent 委托的开源框架）在快速演进的 Agent 通信协议、多 Agent 框架和新兴学术研究生态中的竞争格局。分析涵盖截至 2026 年 2 月的最新发展，并识别了 Brief 在一个既拥挤又在关键领域严重不足的市场中的独特定位：**标准化、可审计的 Agent 间任务委托**。\n\n核心发现是：尽管 Agent 协议生态已显著成熟——MCP 主导工具调用、A2A 整合了 Agent 间传输、众多编排框架争夺开发者心智——但**没有任何现有方案为 Agent 间委托的内容提供轻量级的格式标准**。Brief Protocol 恰好填补了这一空白。\n\n---\n\n## 1. 2026 年协议全景\n\nAgent 协议生态已经结晶为四个明确的层次，The Register 在 2026 年 1 月的综述中进行了全面梳理 [1]。理解这些层次对于准确定位 Brief 至关重要。\n\n### 1.1 Agent-to-Tool 协议\n\n**模型上下文协议（MCP）** 由 Anthropic 于 2024 年底开发，已成为 Agent 工具调用的事实标准。所有主要 AI 提供商——包括 OpenAI 和 Google——均已采用 MCP [1]。**通用工具调用协议（UTCP）** 提供了更简单的替代方案，但仍属小众。\n\n**与 Brief 的关系**：MCP 定义了 *Agent 如何使用工具*。Brief 定义了 *Agent 如何将任务委托给其他 Agent*。两者互补而非竞争。\n\n### 1.2 Agent-to-Agent 协议\n\n**Agent-to-Agent（A2A）** 协议由 Google 开发并贡献给 Linux Foundation，已成为 Agent 发现和通信的事实标准。2025 年夏季发生了一个重大变化：**IBM 的 Agent 通信协议（ACP）**——最初为 BeeAI 平台构建——被合并到 Linux Foundation 旗下的 A2A 中 [1]。这一整合消除了此前被视为竞争标准的 ACP。\n\n**Agent 网络协议（ANP）** 采用点对点方式，旨在构建\"Agent 互联网\"[2]。Ecma International 于 2026 年 1 月推出的**自然语言交互协议（NLIP）** 尚不成熟 [1]。\n\n**与 Brief 的关系**：A2A 定义了*传输和发现*层——Agent 如何找到彼此并交换消息。Brief 定义了当目的是任务委托时这些消息的*语义内容*。Brief 设计为在 A2A *之上*运行。\n\n### 1.3 协议全景总结\n\n| 层次 | 协议 | 维护者 | 状态 | 与 Brief 的关系 |\n|------|------|--------|------|----------------|\n| Agent-to-Tool | MCP | Anthropic | 事实标准 | 互补（工具执行） |\n| Agent-to-Agent | A2A（+ACP） | Linux Foundation | 事实标准 | Brief 的传输层 |\n| Agent-to-Agent | ANP | 社区 | 成长中 | 替代传输层 |\n| Agent-to-User | A2UI / AG-UI | Google / CopilotKit | 早期 | 正交 |\n| 领域特定 | UCP / AP2 | Google | 早期 | 验证领域特定方法 |\n| **委托** | **Brief** | **开源** | **v1.0.0** | **填补空白** |\n\n---\n\n## 2. 编排框架格局\n\n### 2.1 主要框架\n\n**CrewAI** 仍是最流行的 Python 多 Agent 框架之一，使用角色扮演隐喻 [3]。**微软的 Agent Framework（MAF）** 统一了 Semantic Kernel 和 AutoGen，提供企业级编排和正式的\"Handoff\"编排模式 [4]。**Spring AI** 最近发布了关于子代理编排的重要系列文章，其中 Part 4 专门讨论通过\"Task tool\"将任务委托给专业子代理 [5]。\n\n### 2.2 IDE 级多 Agent 支持\n\n2026 年 2 月 5 日，**VS Code 1.109** 发布了全面的多 Agent 开发支持 [6]，可以并行运行 Claude、Codex 和 Copilot Agent，支持并行子代理执行。**Claude Code** 也通过 **Agent Teams** 功能正式化了其多 Agent 能力——通过共享任务列表、Agent 间消息传递和集中管理来协调多个 Claude Code 实例 [7]。\n\n### 2.3 框架对比\n\n| 框架 | 委托模型 | 标准化格式 | 跨框架 | 审计追踪 |\n|------|---------|-----------|--------|---------|\n| CrewAI | 角色任务 | 否（内部） | 否 | 部分 |\n| MAF/AutoGen | Handoff 编排 | 否（内部） | 否 | 部分 |\n| Spring AI | Task tool 子代理 | 否（内部） | 否 | 部分 |\n| Claude Code Teams | tmux 会话 | 否（专有） | 否 | 内部 |\n| VS Code Multi-Agent | 会话管理 | Agent Skills (.md) | 部分 | 会话日志 |\n| **Brief Protocol** | **显式委托** | **是（.brief.md）** | **是** | **完整（trace.md）** |\n\n关键区别一目了然：每个现有框架都将委托实现为*内部机制*——与其自身的运行时、API 和数据结构紧密耦合。**Brief 是唯一提供标准化、框架无关的委托内容格式的方案。**\n\n---\n\n## 3. 学术研究：Agent Contracts\n\n与 Brief Protocol 在智识上最接近的工作是 2026 年 1 月发表在 arXiv 上的 **\"Agent Contracts\"** 论文（arXiv:2601.08815）[8]。该论文引入了一个形式化框架，将\"合同\"隐喻从任务分配扩展到资源约束执行，统一了输入/输出规范、多维资源约束、时间边界和成功标准。实验结果令人印象深刻：90% 的 token 减少、525 倍更低的方差、零守恒违规 [8]。\n\n### Brief vs. Agent Contracts\n\n| 维度 | Brief Protocol | Agent Contracts |\n|------|---------------|-----------------|\n| **核心关注** | 上下文传递与任务规范 | 资源治理与预算控制 |\n| **格式** | Markdown + YAML（人类可读） | 形式化数学框架 |\n| **实现** | 开源 SDK + 可执行示例 | 学术论文，无公开 SDK |\n| **目标用户** | 实践中的 Agent 开发者 | 学术研究者 |\n| **复杂度** | 极简（2 文件 + 1 追踪日志） | 高（形式化证明、守恒定律） |\n\n两种方法是**互补而非竞争**的。Agent Contracts 的资源约束可以作为 Brief frontmatter 中的可选字段被整合。\n\n---\n\n## 4. Cognition 论题：验证 Brief 的存在理由\n\nBrief Protocol 的智识基础建立在 Cognition 的标志性博客文章\"Don't Build Multi-Agents\"（2025 年 6 月 12 日）之上 [9]，作者 Walden Yan 提出了两个影响深远的原则：\n\n> **原则 1**：共享上下文，共享完整的 Agent 追踪记录，而不仅仅是单条消息。\n\n> **原则 2**：行动携带隐式决策，冲突的决策导致坏结果。\n\nCognition 的诊断精准：多 Agent 系统失败是因为\"决策过于分散，上下文无法在 Agent 之间充分共享\"。至关重要的是，Yan 指出：**\"目前，我没有看到任何人在专注解决这个困难的跨 Agent 上下文传递问题。\"** [9]\n\nBrief Protocol 正是对这个问题的直接、专注的解决方案。`.brief.md` 格式通过要求显式上下文共享来执行原则 1。结构化的 frontmatter 和正文部分通过使隐式决策变为显式来执行原则 2。`trace.md` 机制提供了 Cognition 所倡导的\"完整 Agent 追踪记录\"。\n\n然而，Brief 在处方上与 Cognition 分道扬镳。Cognition 建议默认使用单线程 Agent，而 Brief 认为问题不在于多 Agent 架构本身，而在于*缺乏标准化的委托格式*。\n\n---\n\n## 5. 独特价值主张\n\n**第一，Brief 填补了真实的协议空白。** 生态系统有工具调用标准（MCP）、Agent 发现和传输标准（A2A）、Agent 能力标准（Agent Skills），甚至有 Agent-to-User 交互标准（A2UI/AG-UI）。但没有标准定义委托消息的*内容*。\n\n**第二，Brief 极致简单。** 在所有协议都要求 JSON-RPC、gRPC 或复杂客户端-服务器架构的环境中，Brief 使用 Markdown——开发者生态中最通用的格式。\n\n**第三，Brief 框架无关。** 一个 `.brief.md` 文件可以被任何框架中的任何 Agent 创建、读取和处理。\n\n**第四，Brief 提供内置可审计性。** `trace.md` 机制在多级委托链中创建完整的时间线审计追踪。\n\n**第五，Brief 直接回应了业界对多 Agent 系统最突出的批评。** 通过将\"显式委托\"实现为具体协议，Brief 将 Cognition 的理论诊断转化为实际解决方案。\n\n---\n\n## 6. 结论\n\nBrief Protocol 在一个恰当的时机进入市场。Agent 生态正在快速成熟，工具调用和 Agent 通信已有清晰标准，但委托内容标准明显缺失。业界最具影响力的声音已经识别了 Brief 要解决的确切问题，但尚无人交付实际方案。\n\nBrief Protocol 的极致简单、框架无关性和对行业核心批评的直接回应，使其独特地定位为 Agent 间任务委托的标准。\n\n---\n\n## 参考文献\n\n[1] Mann, T. (2026-01-30). \"Deciphering the alphabet soup of agentic AI protocols.\" *The Register*. https://www.theregister.com/2026/01/30/agnetic_ai_protocols_mcp_utcp_a2a_etc/\n\n[2] \"MCP, A2A, ACP & ANP: How AI Agents Communicate in Enterprise Workflows.\" *LinkedIn*. https://www.linkedin.com/pulse/mcp-a2a-acp-anp-how-ai-agents-communicate-enterprise-workflows-b98jc\n\n[3] \"How to Build Multi-Agent Systems: Complete 2026 Guide.\" *Dev.to*. https://dev.to/eira-wexford/how-to-build-multi-agent-systems-complete-2026-guide-1io6\n\n[4] \"Handoff - Microsoft Agent Framework.\" *Microsoft Learn*. https://learn.microsoft.com/en-us/agent-framework/user-guide/workflows/orchestrations/handoff\n\n[5] Tzolov, C. (2026-01-27). \"Spring AI Agentic Patterns (Part 4): Subagent Orchestration.\" *Spring Blog*. https://spring.io/blog/2026/01/27/spring-ai-agentic-patterns-4-task-subagents\n\n[6] VS Code Team. (2026-02-05). \"Your Home for Multi-Agent Development.\" *VS Code Blog*. https://code.visualstudio.com/blogs/2026/02/05/multi-agent-development\n\n[7] \"Orchestrate teams of Claude Code sessions.\" *Claude Code Docs*. https://code.claude.com/docs/en/agent-teams\n\n[8] Ye, Q. et al. (2026). \"Agent Contracts: A Formal Framework for Resource-Bounded Autonomous AI Systems.\" *arXiv:2601.08815*. https://arxiv.org/abs/2601.08815\n\n[9] Yan, W. (2025-06-12). \"Don't Build Multi-Agents.\" *Cognition Blog*. https://cognition.ai/blog/dont-build-multi-agents\n"
  },
  {
    "path": "docs/competitive-analysis.md",
    "content": "# Brief Protocol: Competitive Analysis & Market Positioning\n\n**Author**: Manus AI\n**Date**: February 6, 2026\n**Version**: 1.0\n\n---\n\n## Executive Summary\n\nThis report evaluates the competitive landscape surrounding **Brief Protocol** — an open-source framework for explicit agent delegation — against the rapidly evolving ecosystem of agent communication protocols, multi-agent frameworks, and emerging academic research. The analysis covers developments through February 2026 and identifies Brief's unique positioning in a market that is simultaneously crowded and fundamentally underserved in one critical area: **standardized, auditable task delegation between agents**.\n\nThe central finding is that while the agent protocol ecosystem has matured significantly — with MCP dominating tool-calling, A2A consolidating agent-to-agent transport, and numerous orchestration frameworks competing for developer mindshare — **no existing solution provides a lightweight, format-level standard for the content of inter-agent delegation**. Brief Protocol occupies this precise gap.\n\n---\n\n## 1. The Protocol Landscape in 2026\n\nThe agent protocol ecosystem has crystallized into four distinct layers, as comprehensively surveyed by The Register in January 2026 [1]. Understanding these layers is essential to positioning Brief correctly.\n\n### 1.1 Agent-to-Tool Protocols\n\nThe **Model Context Protocol (MCP)**, originally developed by Anthropic in late 2024, has achieved de facto standard status for agent-to-tool communication. All major AI providers — including OpenAI and Google — have adopted MCP, which uses a client-server architecture to expose tools and data sources via stdio, HTTP, or server-sent events [1]. The **Universal Tool Calling Protocol (UTCP)** offers a simpler alternative by letting models call tools through their native endpoints, but remains niche.\n\n**Relevance to Brief**: MCP defines *how agents use tools*. Brief defines *how agents delegate tasks to each other*. These are complementary, not competing concerns. A delegatee agent might use MCP internally to execute the task described in a `.brief.md`.\n\n### 1.2 Agent-to-Agent Protocols\n\nThe **Agent-to-Agent (A2A)** protocol, originally developed by Google and contributed to the Linux Foundation, has become the de facto standard for agent discovery and communication. A significant development occurred in summer 2025 when **IBM's Agent Communication Protocol (ACP)** — originally built for the BeeAI platform — was merged into A2A under the Linux Foundation umbrella [1]. This consolidation eliminated what was previously seen as a competing standard.\n\nTwo additional protocols operate in this space. The **Agent Network Protocol (ANP)** takes a peer-to-peer approach aimed at building an \"internet of agents,\" with a focus on decentralized identity and large-scale agent ecosystems [2]. The **Natural Language Interaction Protocol (NLIP)**, introduced by Ecma International in January 2026, enables natural language exchange between agents but remains immature [1].\n\n**Relevance to Brief**: A2A defines the *transport and discovery* layer — how agents find each other and exchange messages. Brief defines the *semantic content* of those messages when the purpose is task delegation. Brief is designed to be carried *over* A2A, not to replace it.\n\n### 1.3 Agent-to-User Protocols\n\nGoogle's **A2UI** protocol enables agents to dynamically generate user interfaces, while CopilotKit's **AG-UI** protocol standardizes secure communication between agents and frontend clients [1]. These are orthogonal to Brief's concerns.\n\n### 1.4 Domain-Specific Protocols\n\nGoogle's **Universal Commerce Protocol (UCP)** and **Agent Payments Protocol (AP2)** target e-commerce and payment scenarios specifically [1]. These demonstrate that domain-specific protocols are a growing trend, which validates Brief's approach of being a domain-specific protocol for *delegation*.\n\nThe following table summarizes the protocol landscape:\n\n| Layer | Protocol | Maintainer | Status | Relationship to Brief |\n|-------|----------|-----------|--------|----------------------|\n| Agent-to-Tool | MCP | Anthropic | De facto standard | Complementary (tool execution) |\n| Agent-to-Tool | UTCP | Community | Niche | Complementary |\n| Agent-to-Agent | A2A (+ACP) | Linux Foundation | De facto standard | Transport layer for Brief |\n| Agent-to-Agent | ANP | Community | Growing | Alternative transport |\n| Agent-to-Agent | NLIP | Ecma International | Early stage | Potential complement |\n| Agent-to-User | A2UI | Google | Preview | Orthogonal |\n| Agent-to-User | AG-UI | CopilotKit | Growing | Orthogonal |\n| Domain-Specific | UCP/AP2 | Google | Early stage | Validates domain-specific approach |\n| **Delegation** | **Brief** | **Open Source** | **v1.0.0** | **Fills the gap** |\n\n---\n\n## 2. The Orchestration Framework Landscape\n\nBeyond protocols, a rich ecosystem of multi-agent orchestration frameworks has emerged. These are higher-level tools that manage agent workflows, and they represent both potential integration partners and indirect competitors.\n\n### 2.1 Major Frameworks\n\n**CrewAI** remains one of the most popular Python-based multi-agent frameworks, using a role-playing metaphor where agents are assigned personas and collaborate on tasks [3]. **Microsoft's Agent Framework (MAF)** — which unifies Semantic Kernel and AutoGen — provides enterprise-grade orchestration with formal \"Handoff\" orchestration patterns that allow agents to transfer control based on context [4]. **LangGraph** from LangChain uses a graph-based state machine approach for complex agent workflows.\n\n**Spring AI** recently published a significant series on agentic patterns, with Part 4 specifically covering \"Subagent Orchestration\" — a pattern where a main agent delegates tasks to specialized subagents through a \"Task tool\" [5]. This is architecturally similar to Brief's delegation concept but is tightly coupled to the Spring AI framework.\n\n### 2.2 IDE-Level Multi-Agent Support\n\nA major development occurred on February 5, 2026, when **VS Code 1.109** launched with comprehensive multi-agent development support [6]. This release enables running Claude, Codex, and Copilot agents side by side, with parallel subagent execution and a unified Agent Sessions view. VS Code now supports **Agent Skills** (Anthropic's open standard for extending AI agents) as a generally available feature, and **MCP Apps** for rich UI rendering in agent interactions.\n\n**Claude Code** has also formalized its multi-agent capabilities through **Agent Teams** — a feature that coordinates multiple Claude Code instances with shared task lists, inter-agent messaging, and centralized management [7]. Each teammate operates in its own context window and communicates through automatic message delivery.\n\n### 2.3 Framework Comparison\n\n| Framework | Language | Delegation Model | Standardized Format | Cross-Framework | Audit Trail |\n|-----------|----------|-----------------|---------------------|----------------|-------------|\n| CrewAI | Python | Role-based tasks | No (internal) | No | Partial |\n| MAF/AutoGen | .NET/Python | Handoff orchestration | No (internal) | No | Partial |\n| LangGraph | Python | Graph state transitions | No (internal) | No | Partial |\n| Spring AI | Java | Task tool subagents | No (internal) | No | Partial |\n| Claude Code Teams | TypeScript | tmux-based sessions | No (proprietary) | No | Internal |\n| VS Code Multi-Agent | TypeScript | Session-based | Agent Skills (.md) | Partial | Session logs |\n| **Brief Protocol** | **TypeScript** | **Explicit delegation** | **Yes (.brief.md)** | **Yes** | **Full (trace.md)** |\n\nThe critical distinction is clear: every existing framework implements delegation as an *internal mechanism* — tightly coupled to its own runtime, APIs, and data structures. **Brief is the only solution that provides a standardized, framework-agnostic format for delegation content.**\n\n---\n\n## 3. Academic Research: Agent Contracts\n\nThe most intellectually proximate work to Brief Protocol is the **\"Agent Contracts\"** paper published on arXiv in January 2026 (arXiv:2601.08815) [8]. This paper introduces a formal framework that extends the contract metaphor from task allocation to resource-bounded execution.\n\nAgent Contracts unify input/output specifications, multi-dimensional resource constraints (tokens, time, cost), temporal boundaries, and success criteria into a coherent governance mechanism. The paper establishes \"conservation laws\" ensuring that delegated budgets respect parent constraints, and demonstrates impressive empirical results: 90% token reduction, 525x lower variance, and zero conservation violations in multi-agent delegation [8].\n\n### 3.1 Brief vs. Agent Contracts\n\nWhile both Brief and Agent Contracts address the delegation problem, they approach it from fundamentally different angles:\n\n| Dimension | Brief Protocol | Agent Contracts |\n|-----------|---------------|-----------------|\n| **Primary Focus** | Context passing & task specification | Resource governance & budget control |\n| **Format** | Markdown + YAML (human-readable) | Formal mathematical framework |\n| **Implementation** | Open-source SDK with executable examples | Academic paper, no public SDK |\n| **Target Audience** | Practicing agent developers | Academic researchers |\n| **Complexity** | Minimal (2 files + 1 trace log) | High (formal proofs, conservation laws) |\n| **Ecosystem Integration** | Designed for MCP/A2A/Agent Skills | Standalone theoretical framework |\n| **Cascading Support** | Built-in parentId/maxDepth | Conservation laws for budget delegation |\n\nThe two approaches are **complementary rather than competing**. Agent Contracts could potentially be integrated into Brief's frontmatter as optional resource constraint fields, combining Brief's practical simplicity with Agent Contracts' formal resource governance.\n\n---\n\n## 4. The Cognition Thesis: Validating Brief's Raison d'Être\n\nThe intellectual foundation of Brief Protocol rests on Cognition's influential blog post \"Don't Build Multi-Agents\" (June 12, 2025) [9], authored by Walden Yan. This post articulated two principles that have shaped the industry's thinking about multi-agent systems:\n\n> **Principle 1**: Share context, and share full agent traces, not just individual messages.\n\n> **Principle 2**: Actions carry implicit decisions, and conflicting decisions carry bad results.\n\nCognition's diagnosis was precise: multi-agent systems fail because \"the decision-making ends up being too dispersed and context isn't able to be shared thoroughly enough between the agents.\" Crucially, Yan noted: **\"At the moment, I don't see anyone putting a dedicated effort to solving this difficult cross-agent context-passing problem.\"** [9]\n\nBrief Protocol is a direct, dedicated effort to solve exactly this problem. The `.brief.md` format enforces Principle 1 by requiring explicit context sharing. The structured frontmatter and body sections enforce Principle 2 by making implicit decisions explicit. The `trace.md` mechanism provides the \"full agent traces\" that Cognition advocates.\n\nHowever, Brief diverges from Cognition's prescription. Where Cognition recommends defaulting to single-threaded agents, Brief argues that the problem is not multi-agent architectures themselves but rather the *lack of a standardized delegation format*. With proper explicit delegation, multi-agent systems can be both reliable and powerful.\n\n---\n\n## 5. Unique Value Proposition\n\nBased on this comprehensive analysis, Brief Protocol's unique positioning can be articulated across five dimensions:\n\n**First, Brief fills a genuine protocol gap.** The ecosystem has standards for tool-calling (MCP), agent discovery and transport (A2A), agent capabilities (Agent Skills), and even agent-to-user interaction (A2UI/AG-UI). But there is no standard for the *content* of a delegation message — what information must be included when one agent asks another to perform a task. Brief provides this missing semantic layer.\n\n**Second, Brief is radically simple.** In a landscape where protocols require JSON-RPC, gRPC, or complex client-server architectures, Brief uses Markdown — the most universally understood format in the developer ecosystem. The entire protocol is two Markdown files and one trace log. This simplicity is not a limitation but a deliberate design choice that lowers the barrier to adoption.\n\n**Third, Brief is framework-agnostic.** Unlike CrewAI's internal task objects, AutoGen's message formats, or Claude Code's proprietary session management, a `.brief.md` file can be created, read, and processed by any agent in any framework. This universality is essential for a protocol that aims to standardize inter-agent delegation across the ecosystem.\n\n**Fourth, Brief provides built-in auditability.** The `trace.md` mechanism creates a complete, chronological audit trail across multi-level delegation chains. This is not an afterthought but a core protocol feature, addressing enterprise requirements for transparency and compliance.\n\n**Fifth, Brief directly responds to the industry's most prominent critique of multi-agent systems.** By implementing \"Explicit Delegation\" as a concrete protocol, Brief transforms Cognition's theoretical diagnosis into a practical solution.\n\n---\n\n## 6. Risks and Mitigation\n\nSeveral risks should be acknowledged as Brief moves toward open-source release:\n\nThe **adoption risk** is significant. Protocols succeed through network effects, and Brief must achieve critical mass to become a standard. Mitigation strategies include publishing compelling examples, integrating with popular frameworks (CrewAI, LangGraph), and contributing Brief support to A2A implementations.\n\nThe **consolidation risk** exists if A2A or MCP expand their scope to include delegation semantics. However, both protocols have shown a pattern of staying focused on their core concerns (transport/discovery and tool-calling respectively), making scope creep unlikely in the near term.\n\nThe **complexity creep risk** is inherent in any protocol. As users request more features (priority levels, SLA definitions, resource constraints), Brief must resist the temptation to become a heavy framework. The principle of \"progressive disclosure\" — simple by default, powerful when needed — must be rigorously maintained.\n\n---\n\n## 7. Conclusion\n\nBrief Protocol enters the market at an opportune moment. The agent ecosystem is maturing rapidly, with clear standards emerging for tool-calling and agent communication, but a conspicuous absence of standards for delegation content. The industry's most influential voices have identified the exact problem Brief solves, yet no one has shipped a practical solution.\n\nThe competitive landscape validates Brief's approach: it is not competing with MCP, A2A, or any orchestration framework. It is providing the missing piece that makes all of them work better together. As the agent ecosystem continues to grow — with VS Code now supporting multi-agent development natively and enterprise adoption accelerating — the need for standardized, auditable delegation will only increase.\n\nBrief Protocol's combination of radical simplicity, framework agnosticism, and direct response to the industry's core critique positions it uniquely to become the standard for how agents delegate tasks to each other.\n\n---\n\n## References\n\n[1] Mann, T. (2026, January 30). \"Deciphering the alphabet soup of agentic AI protocols.\" *The Register*. https://www.theregister.com/2026/01/30/agnetic_ai_protocols_mcp_utcp_a2a_etc/\n\n[2] \"MCP, A2A, ACP & ANP: How AI Agents Communicate in Enterprise Workflows.\" *LinkedIn*. https://www.linkedin.com/pulse/mcp-a2a-acp-anp-how-ai-agents-communicate-enterprise-workflows-b98jc\n\n[3] \"How to Build Multi-Agent Systems: Complete 2026 Guide.\" *Dev.to*. https://dev.to/eira-wexford/how-to-build-multi-agent-systems-complete-2026-guide-1io6\n\n[4] \"Handoff - Microsoft Agent Framework.\" *Microsoft Learn*. https://learn.microsoft.com/en-us/agent-framework/user-guide/workflows/orchestrations/handoff\n\n[5] Tzolov, C. (2026, January 27). \"Spring AI Agentic Patterns (Part 4): Subagent Orchestration.\" *Spring Blog*. https://spring.io/blog/2026/01/27/spring-ai-agentic-patterns-4-task-subagents\n\n[6] VS Code Team. (2026, February 5). \"Your Home for Multi-Agent Development.\" *Visual Studio Code Blog*. https://code.visualstudio.com/blogs/2026/02/05/multi-agent-development\n\n[7] \"Orchestrate teams of Claude Code sessions.\" *Claude Code Docs*. https://code.claude.com/docs/en/agent-teams\n\n[8] Ye, Q. et al. (2026). \"Agent Contracts: A Formal Framework for Resource-Bounded Autonomous AI Systems.\" *arXiv:2601.08815*. https://arxiv.org/abs/2601.08815\n\n[9] Yan, W. (2025, June 12). \"Don't Build Multi-Agents.\" *Cognition Blog*. https://cognition.ai/blog/dont-build-multi-agents\n"
  },
  {
    "path": "docs/design-zh.md",
    "content": "# Brief：一个用于显式 Agent 委托的协议\n\n**作者**：Manus AI\n**版本**：1.2\n**日期**：2026年02月06日\n\n## 1. 引言：为何需要显式委托\n\n关于多智能体（Multi-Agent）AI 系统的讨论目前正处于一个十字路口。一方面，像 CrewAI 和 AutoGen 这样的框架倡导协作式 Agent 集成的力量。另一方面，一些有影响力的声音，特别是 Devin 的创建者 Cognition 团队，提出了重大关切，认为大多数多智能体架构因其**隐式交接（Implicit Handoffs）**而存在根本性缺陷 [1]。\n\n> **隐式交接**指的是一个 Agent 在没有清晰定义、结构化和完整的上下文的情况下，将任务传递给另一个 Agent。这在程序上等同于一个经理告诉员工“处理一下这个”，却没有提供必要的背景、目标和约束。这种模糊性会导致一系列问题，包括决策冲突、上下文丢失以及系统变得脆弱和不可预测。\n\n**Brief** 是一个基于相反原则构建的全新协议和轻量级 SDK：**显式委托（Explicit Delegation）**。\n\n我们认同对问题的诊断，但提出了一个更精细的解决方案。我们不应放弃多智能体系统的潜力，而应使其委托过程规范化。Brief 引入了一个标准化的、可审计的协议，将混乱的“隐式交接”转变为正式的“显式委托”。它为 Agent 之间下达任务提供了结构，就像一份写得很好的 JIRA 工单、一份正式的需求建议书（RFP）或一次军事任务简报。\n\n这种方法让开发者能够两全其美：既能利用专门 Agent 的专注能力，又能实现多智能体系统的可扩展协调，同时避免了相关的混乱。它专为那些正努力解决“上下文污染”和 Agent 协作失控挑战的高级 Agent 开发者和企业架构师而设计。\n\n## 2. 核心原则与创新\n\n为了真正做到创新并解决实际痛点，Brief 建立在三个核心原则之上：\n\n1.  **简单至上**：协议必须比编写临时脚本更容易使用。如果创建一个 `Brief` 比直接进行 API 调用更难，那么它就失败了。这意味着最少的必填字段和人性化的格式。\n2.  **不透明与无状态执行**：接收方 Agent 是一个黑盒。它必须*仅*基于 `Brief` 中提供的上下文进行操作。它不能访问委托方的内部状态、内存或完整的历史记录。这强制执行了清晰的决策边界，并防止了上下文污染。\n3.  **拥抱而非取代**：Brief 不是另一个包罗万象的框架。它是一个轻量级的语义层，旨在与现有的标准（如 A2A 和 MCP）*协同工作*，而不是取代它们。\n\n## 3. Brief 协议：一个双文档系统\n\nBrief 由两个简单的 Markdown 文档组成：`.brief.md`（请求）和 `.response.md`（结果）。\n\n### 3.1. 请求：`[id].brief.md`\n\n该文档是正式的“任务订单”。它遵循 `SKILL.md` 的范式，即使用 YAML frontmatter 来存储元数据，使用 Markdown body 来提供人类可读的指令。\n\n**`brief-a4b1c8.brief.md` 示例：**\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-openclaw-prod\"\ndelegatee: \"capability:code-refactoring\"\ntimestamp: \"2026-02-06T03:55:00Z\"\n---\n\n# 任务简报：重构认证模块以使用 SSO\n\n## 1. 目标\n\n重构主要的用户认证模块，将认证委托给我们新的内部 SSO 服务。\n\n## 2. 背景与历史\n\n*用户最初报告登录缓慢。内部分析确认，在密码验证期间，遗留的 `users` 表存在数据库瓶颈。架构决策已定，迁移到集中的 SSO 服务以提高性能和安全性。*\n\n## 3. 关键约束\n\n- **向后兼容**：现有的 v1 API 端点（`/auth/login`）必须保持功能。\n- **代码标准**：所有新代码必须遵守项目的“strict-ts” linting 规则。\n\n## 4. 所需工件\n\n- **当前模块源代码**: `file:///home/ubuntu/project/src/auth`\n- **SSO 服务文档**: `https://internal.docs/sso/v2/api`\n\n## 5. 预期交付物\n\n1.  **重构后的代码**：新的认证模块的完整、经过测试的源代码。\n2.  **Pull Request**：一个包含更改的 GitHub Pull Request，准备好供审查。\n```\n\n### 3.2. 响应：`[id].response.md`\n\n为了完成闭环，接收方 Agent 会发回一个响应文档。这确保了整个委托过程是一个自包含、可审计的记录。\n\n**`brief-a4b1c8.response.md` 示例：**\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nstatus: \"success\"\ntimestamp: \"2026-02-06T04:30:00Z\"\n---\n\n# 响应：重构完成\n\n## 1. 摘要\n\n认证模块已成功重构以使用 SSO 服务。所有测试均已通过。\n\n## 2. 交付的工件\n\n- **Pull Request**: https://github.com/example/project/pull/123\n\n## 3. 备注\n\n- 在 `src/auth/compat.ts` 中添加了一个兼容层以支持 v1 API。\n- 请确保在生产环境中设置 `SSO_CLIENT_SECRET` 环境变量。\n```\n\n## 4. 级联追踪：`trace.md`\n\n为了处理真正的多级、级联委托（A → B → C），`trace` 不再是 `Brief` 本身的一部分。相反，它是一个独立的、仅追加的日志，随任务一起传递，提供了一个完整的、按时间顺序排列的审计追踪。\n\n**`trace.md` 示例：**\n\n```markdown\n- **Agent**: `agent-root` @ `2026-02-06T03:50:00Z`\n  - **Action**: 收到用户请求：“修复登录缓慢问题。”\n- **Agent**: `agent-openclaw-prod` @ `2026-02-06T03:55:00Z`\n  - **Action**: 委托重构任务。创建 `brief-a4b1c8.brief.md`。\n- **Agent**: `agent-opencode-v4` @ `2026-02-06T04:05:00Z`\n  - **Action**: 接受 `brief-a4b1c8`。任务复杂，委托文档更新。创建 `brief-c9d2e7.brief.md`。\n- **Agent**: `agent-docs-writer` @ `2026-02-06T04:15:00Z`\n  - **Action**: 接受 `brief-c9d2e7`。完成文档更新。以 `brief-c9d2e7.response.md` 响应。\n- **Agent**: `agent-opencode-v4` @ `2026-02-06T04:30:00Z`\n  - **Action**: 收到 `brief-c9d2e7` 的响应。完成重构。以 `brief-a4b1c8.response.md` 响应。\n```\n\n这种分离至关重要：`Brief` 是*做什么*，而 `trace` 是*谁*和*何时*。它使 `Brief` 保持干净，并专注于手头的任务。\n\n## 5. 生态系统集成与流程\n\nBrief 被设计为一个语义层，位于现有的传输和发现协议之上。它不重复造轮子。\n\n![Brief 协议执行流程](images/brief_flow.png)\n\n1.  **发现 (A2A)**: Agent A (委托方) 需要一个 `code-refactoring` 能力。它使用 A2A 协议查询一个 Agent 目录，并发现 Agent B，后者的 `AgentCard` 列出了此能力并支持 `brief-protocol-v1.2`。\n\n2.  **委托 (Brief over A2A)**: Agent A 创建一个 `.brief.md` 文档。然后它使用 A2A 的 `SendMessage` 操作将此文档发送给 Agent B。`Brief` 的内容是 A2A 消息的有效载荷。\n\n3.  **执行 (不透明)**: Agent B 收到 `Brief`。它使用自己的内部逻辑和工具执行任务。如果它需要调用特定的工具（例如，代码检查器），它可能会使用 **MCP (Model-Context-Protocol)** 与该工具进行交互。\n\n4.  **级联委托 (Brief over A2A, 再次)**: 如果 Agent B 决定需要委托一个子任务（例如，更新文档），它自己就变成了委托方。它创建一个*新的* `.brief.md` 并将其发送给 Agent C，同时将其操作附加到 `trace.md` 文件中。\n\n5.  **响应 (Brief over A2A)**: 一旦 Agent B 完成原始任务，它会创建一个 `.response.md` 文档并将其发送回 Agent A，同样使用 A2A 协议。\n\n这种分层方法是 Brief 简单而强大的关键。它提供了缺失的“做什么”（`Brief` 格式），而不会干扰已建立的“怎么做”（A2A 用于传输，MCP 用于工具）。\n\n## 6. SDK 设计 (`brief-sdk` for TypeScript)\n\nSDK 的主要作用是使创建、解析和验证这些 Markdown 文档变得轻而易举。\n\n```typescript\nimport { Brief, BriefResponse, BriefFactory } from 'brief-sdk';\n\n// --- 委托方 ---\n\n// 1. 创建一个 Brief\nconst brief = BriefFactory.create({\n  delegator: 'agent-openclaw-prod',\n  delegatee: 'capability:code-refactoring',\n  body: '# 任务简报：重构认证\\n\\n## 1. 目标...'\n});\n\n// brief.content 现在是一个完整格式的 .brief.md 字符串\n// 2. 通过 A2A 客户端（或任何传输方式）发送\na2aClient.sendMessage(brief.delegatee, brief.content);\n\n// --- 接收方 ---\n\n// 3. 接收并解析 Brief\nconst receivedContent = a2aMessage.parts[0].text;\nconst incomingBrief = Brief.parse(receivedContent);\n\n// 4. 执行任务（你的 Agent 的核心逻辑）\nconst results = await myAgent.doWork(incomingBrief);\n\n// 5. 创建一个响应\nconst response = incomingBrief.createResponse({\n  status: 'success',\n  body: `# 响应：重构完成\\n\\n- **Pull Request**: ${results.prUrl}`\n});\n\n// 6. 发回响应\na2aClient.sendMessage(response.delegator, response.content);\n```\n\n请注意，`ContextCompiler` 已经消失了。它是一个有用的实用工具，但不是协议的核心部分。它可以在以后作为 SDK 中的一个可选辅助函数提供。\n\n## 7. 结论：简单、真实、创新\n\n这个修订后的 Brief 设计是：\n\n-   **简单**：它只是两个 Markdown 文件和一个可选的追踪日志。任何会写 Markdown 的人都可以使用它。\n-   **创新**：它引入了 `.brief.md` / `.response.md` 模式和解耦的 `trace.md`，以实现真正的、可审计的级联委托。\n-   **真实**：它通过强制执行一个干净、明确的契约，解决了 Agent 混乱交接的真正痛点，并且它与现有标准集成而不是与之竞争。\n\n这是一个能够“一鸣惊人”的设计，不是因为它更复杂，而是因为它从根本上更简单，更专注于实际的开发者体验。\n\n---\n\n## 参考文献\n\n[1] Cognition. (2025, June 12). *Don’t Build Multi-Agents*. [https://cognition.ai/blog/dont-build-multi-agents](https://cognition.ai/blog/dont-build-multi-agents)\n\n## 8. 高级主题：级联委托与扇出\n\n虽然简单的 A→B 委托是最常见的用例，但 Brief 被设计用于处理复杂的多级委托链（A→B→C）和扇出/扇入模式（A 委托给 B 和 C，然后等待两者都响应）。\n\n### 8.1. 启用级联：`parentId` 字段\n\n为了在父 `Brief` 和子 `Brief` 之间建立链接，我们在 frontmatter 中引入了一个可选的 `parentId` 字段。\n\n- 没有 `parentId` 的 `Brief` 是**根简报**。\n- *带有* `parentId` 的 `Brief` 是**子简报**。\n\n当 Agent B 在执行 `brief-a4b1c8` 时决定将一个子任务委托给 Agent C，它会创建一个新的简报（`brief-c9d2e7`）并设置 `parentId`：\n\n```yaml\n# 在 brief-c9d2e7.brief.md 中\n---\nid: \"brief-c9d2e7\"\nparentId: \"brief-a4b1c8\" # <-- 这将其链接到父任务\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-opencode-v4\"\ndelegatee: \"agent-docs-writer\"\ntimestamp: \"2026-02-06T04:05:00Z\"\n---\n# 任务简报：为 SSO 重构更新开发者文档\n...\n```\n\n这个简单的机制允许构建一个完整的任务树，这对于追踪和调试至关重要。\n\n### 8.2. 级联世界中的 `trace.md`\n\n`trace.md` 文件是在多个层级之间保持连贯审计追踪的关键。规则很简单：\n\n1.  **向下传递**：当一个 Agent 创建一个子简报时，它必须将当前 `trace.md` 的副本连同新的 `.brief.md` 一起传递给子 Agent。\n2.  **追加，不要替换**：子 Agent 将其自己的操作追加到它收到的 `trace.md` 中。\n3.  **向上传回**：当子 Agent 发送其 `.response.md` 时，它也必须返回更新后的 `trace.md`。\n4.  **合并**：父 Agent 负责将来自子任务的追踪合并回其主追踪中。对于简单的 A→B→C 链，这是一个简单的追加。对于扇出场景，父 Agent 必须处理并行的追踪分支。\n\n### 8.3. 扇出和扇入模式\n\nBrief 支持一个 Agent 并行地将任务委托给多个其他 Agent，并等待它们全部完成的场景。\n\n想象一下，Agent A 需要获取股票价格（`brief-002` 给 Agent B）和新闻情感分析（`brief-003` 给 Agent C）来做出决策。\n\n1.  Agent A 创建两个独立的简报，两者都具有相同的 `parentId`（例如，根用户请求的 ID）。\n2.  Agent A 将 `brief-002` 发送给 B，将 `brief-003` 发送给 C。\n3.  Agent A 现在等待，直到它收到了 `brief-002` 和 `brief-003` 的 `.response.md` 文件。\n4.  一旦两个响应都收到，Agent A 就可以综合结果并完成其原始任务。\n\nSDK 可以提供辅助工具来管理这种扇出/扇入逻辑，例如 `waitForAll(briefIds)` 函数。\n\n### 8.4. 深度限制：防止无限递归\n\n为了防止失控的成本或无限的委托循环，可以在根简报的 frontmatter 中设置一个 `maxDepth`。每个委托级别都会增加一个 `currentDepth` 计数器。如果 `currentDepth` 超过 `maxDepth`，则禁止该 Agent 创建更多的子简报。\n\n这些高级功能被设计为**渐进式披露**。对于简单的任务，你只需要考虑两个 Markdown 文件。对于复杂的编排，`parentId` 和 `trace.md` 提供了必要的能力和控制。\n"
  },
  {
    "path": "docs/design.md",
    "content": "# Brief: A Protocol for Explicit Agent Delegation\n\n**Date**: 2026-02-06\n\n## 1. Introduction: The Case for Explicit Delegation\n\nThe discourse surrounding multi-agent AI systems is currently at a crossroads. On one side, frameworks like CrewAI and AutoGen champion the power of collaborative agent ensembles. On the other, influential voices, notably the Cognition team behind Devin, have raised significant concerns, arguing that most multi-agent architectures are fundamentally flawed due to **implicit handoffs** [1].\n\n> An **implicit handoff** occurs when one agent passes a task to another without a clearly defined, structured, and complete context. It is the programmatic equivalent of a manager telling an employee, \"Just handle this,\" without providing the necessary background, goals, and constraints. This ambiguity leads to a cascade of problems, including decision conflicts, context loss, and fragile, unpredictable systems.\n\n**Brief** is a new protocol and lightweight SDK built on the opposite principle: **Explicit Delegation**.\n\nWe concur with the diagnosis of the problem but propose a more nuanced solution. Rather than abandoning the potential of multi-agent systems, we should formalize the process of inter-agent delegation. Brief introduces a standardized, auditable protocol that transforms the chaotic \"implicit handoff\" into a formal \"explicit delegation.\" It provides the structure for one agent to issue a task to another, much like a well-written JIRA ticket, a formal Request for Proposal (RFP), or a military briefing.\n\nThis approach allows developers to harness the best of both worlds: the focused power of specialized agents and the scalable coordination of a multi-agent system, all without the associated chaos. It is designed for advanced agent developers and enterprise architects who are grappling with the challenges of \"context pollution\" and uncontrollable agent collaboration.\n\n## 2. Core Principles & Innovations\n\nTo be truly innovative and solve real pain points, Brief is built on three core principles:\n\n1.  **Simplicity First**: The protocol must be simpler to use than writing an ad-hoc script. If creating a `Brief` is harder than making a direct API call, it has failed. This means minimal required fields and a human-friendly format.\n2.  **Opaque & Stateless Execution**: The delegatee agent is a black box. It MUST operate *only* on the context provided in the `Brief`. It cannot access the delegator's internal state, memory, or full history. This enforces a strong decision boundary and prevents context pollution.\n3.  **Embrace, Don't Replace**: Brief is not another all-encompassing framework. It is a lightweight semantic layer designed to work *with* existing standards like A2A and MCP, not replace them.\n\n## 3. The Brief Protocol: A Two-Document System\n\nBrief consists of two simple Markdown documents: the `.brief.md` (the request) and the `.response.md` (the result).\n\n### 3.1. The Request: `[id].brief.md`\n\nThis document is the formal \"task order.\" It follows the `SKILL.md` paradigm of YAML frontmatter for metadata and a Markdown body for human-readable instructions.\n\n**Example `brief-a4b1c8.brief.md`:**\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-openclaw-prod\"\ndelegatee: \"capability:code-refactoring\"\ntimestamp: \"2026-02-06T03:55:00Z\"\n---\n\n# Briefing: Refactor Authentication Module to SSO\n\n## 1. Objective\n\nRefactor the primary user authentication module to delegate authentication to our new internal SSO service.\n\n## 2. Context & History\n\n*User initially reported slow login times. Internal analysis confirmed a database bottleneck in the legacy `users` table during password verification. The architectural decision was made to migrate to the centralized SSO service to improve performance and security.*\n\n## 3. Key Constraints\n\n- **Backward Compatibility**: The existing v1 API endpoints (`/auth/login`) MUST remain functional.\n- **Code Standards**: All new code MUST adhere to the project's 'strict-ts' linting rules.\n\n## 4. Required Artifacts\n\n- **Current Module Source**: `file:///home/ubuntu/project/src/auth`\n- **SSO Service Documentation**: `https://internal.docs/sso/v2/api`\n\n## 5. Expected Deliverables\n\n1.  **Refactored Code**: The complete, tested source code for the new authentication module.\n2.  **Pull Request**: A GitHub Pull Request containing the changes, ready for review.\n```\n\n### 3.2. The Response: `[id].response.md`\n\nTo complete the loop, the delegatee agent sends back a response document. This ensures the entire delegation is a self-contained, auditable record.\n\n**Example `brief-a4b1c8.response.md`:**\n\n```markdown\n---\nid: \"brief-a4b1c8\"\nstatus: \"success\"\ntimestamp: \"2026-02-06T04:30:00Z\"\n---\n\n# Response: Refactoring Complete\n\n## 1. Summary\n\nThe authentication module has been successfully refactored to use the SSO service. All tests passed.\n\n## 2. Delivered Artifacts\n\n- **Pull Request**: https://github.com/example/project/pull/123\n\n## 3. Notes\n\n- A compatibility layer was added to `src/auth/compat.ts` to support the v1 API.\n- Please ensure the `SSO_CLIENT_SECRET` environment variable is set in production.\n```\n\n## 4. The Cascading Trace: `trace.md`\n\nTo handle true multi-level, cascading delegation (A → B → C), the `trace` is not part of the `Brief` itself. Instead, it's a separate, append-only log that travels with the task, providing a complete, chronological audit trail.\n\n**Example `trace.md`:**\n\n```markdown\n- **Agent**: `agent-root` @ `2026-02-06T03:50:00Z`\n  - **Action**: Received user request: \"Fix the slow login.\"\n- **Agent**: `agent-openclaw-prod` @ `2026-02-06T03:55:00Z`\n  - **Action**: Delegating refactoring task. Created `brief-a4b1c8.brief.md`.\n- **Agent**: `agent-opencode-v4` @ `2026-02-06T04:05:00Z`\n  - **Action**: Accepted `brief-a4b1c8`. Task is complex, delegating documentation update. Created `brief-c9d2e7.brief.md`.\n- **Agent**: `agent-docs-writer` @ `2026-02-06T04:15:00Z`\n  - **Action**: Accepted `brief-c9d2e7`. Completed documentation update. Responded with `brief-c9d2e7.response.md`.\n- **Agent**: `agent-opencode-v4` @ `2026-02-06T04:30:00Z`\n  - **Action**: Received response for `brief-c9d2e7`. Completed refactoring. Responded with `brief-a4b1c8.response.md`.\n```\n\nThis separation is critical: the `Brief` is the *what*, and the `trace` is the *who* and *when*. It keeps the `Brief` clean and focused on the task at hand.\n\n## 5. Ecosystem Integration & Flow\n\nBrief is designed to be a semantic layer that sits on top of existing transport and discovery protocols. It does not reinvent the wheel.\n\n![Brief Protocol Execution Flow](images/brief_flow.png)\n\n1.  **Discovery (A2A)**: Agent A (Delegator) needs a `code-refactoring` capability. It uses the A2A protocol to query an Agent Directory and discovers Agent B, whose `AgentCard` lists this capability and support for the `brief-protocol-v1.2`.\n\n2.  **Delegation (Brief over A2A)**: Agent A creates a `.brief.md` document. It then uses the A2A `SendMessage` operation to send this document to Agent B. The `Brief` content is the payload of the A2A message.\n\n3.  **Execution (Opaque)**: Agent B receives the `Brief`. It executes the task using its own internal logic and tools. If it needs to call a specific tool (e.g., a code linter), it might use the **MCP (Model-Context-Protocol)** to interact with that tool.\n\n4.  **Cascading Delegation (Brief over A2A, again)**: If Agent B decides it needs to delegate a sub-task (e.g., updating documentation), it becomes a delegator itself. It creates a *new* `.brief.md` and sends it to Agent C, appending its action to the `trace.md` file.\n\n5.  **Response (Brief over A2A)**: Once Agent B completes the original task, it creates a `.response.md` document and sends it back to Agent A, again using the A2A protocol.\n\nThis layered approach is the key to Brief's simplicity and power. It provides the missing \"what\" (the `Brief` format) without interfering with the established \"how\" (A2A for transport, MCP for tools).\n\n## 6. SDK Design (`brief-sdk` for TypeScript)\n\nThe SDK's primary role is to make creating, parsing, and validating these Markdown documents trivial.\n\n```typescript\nimport { Brief, BriefResponse, BriefFactory } from 'brief-sdk';\n\n// --- Delegator Side ---\n\n// 1. Create a Brief\nconst brief = BriefFactory.create({\n  delegator: 'agent-openclaw-prod',\n  delegatee: 'capability:code-refactoring',\n  body: '# Briefing: Refactor Auth\\n\\n## 1. Objective...'\n});\n\n// brief.content is now a fully formatted .brief.md string\n// 2. Send it via A2A client (or any transport)\na2aClient.sendMessage(brief.delegatee, brief.content);\n\n// --- Delegatee Side ---\n\n// 3. Receive and parse the Brief\nconst receivedContent = a2aMessage.parts[0].text;\nconst incomingBrief = Brief.parse(receivedContent);\n\n// 4. Execute the task (your agent's core logic)\nconst results = await myAgent.doWork(incomingBrief);\n\n// 5. Create a response\nconst response = incomingBrief.createResponse({\n  status: 'success',\n  body: `# Response: Refactoring Complete\\n\\n- **Pull Request**: ${results.prUrl}`\n});\n\n// 6. Send the response back\na2aClient.sendMessage(response.delegator, response.content);\n```\n\nNotice the `ContextCompiler` is gone. It's a useful utility, but not a core part of the protocol. It can be provided as an optional helper function in the SDK later.\n\n## 7. Conclusion: Simple, Real, and Innovative\n\nThis revised design for Brief is:\n\n-   **Simple**: It's just two Markdown files and an optional trace log. Anyone who can write Markdown can use it.\n-   **Innovative**: It introduces the `.brief.md` / `.response.md` pattern and the decoupled `trace.md` for true, auditable cascading delegation.\n-   **Real**: It solves the genuine pain point of chaotic agent handoffs by enforcing a clean, explicit contract, and it integrates with existing standards instead of competing with them.\n\nThis is a design that can \"one-up\" the competition not by being more complex, but by being radically simpler and more focused on the actual developer experience.\n\n---\n\n## References\n\n[1] Cognition. (2025, June 12). *Don’t Build Multi-Agents*. [https://cognition.ai/blog/dont-build-multi-agents](https://cognition.ai/blog/dont-build-multi-agents)\n\n## 8. Advanced Topic: Cascading Delegation & Fan-Out\n\nWhile the simple A→B delegation is the most common use case, Brief is designed to handle complex, multi-level delegation chains (A→B→C) and fan-out/fan-in patterns (A delegates to B and C, then waits for both to respond).\n\n### 8.1. Enabling Cascading: The `parentId` Field\n\nTo create a link between a parent `Brief` and a child `Brief`, we introduce an optional `parentId` field in the frontmatter.\n\n- A `Brief` with no `parentId` is a **root brief**.\n- A `Brief` *with* a `parentId` is a **sub-brief**.\n\nWhen Agent B, while executing `brief-a4b1c8`, decides to delegate a sub-task to Agent C, it creates a new brief (`brief-c9d2e7`) and sets the `parentId`:\n\n```yaml\n# In brief-c9d2e7.brief.md\n---\nid: \"brief-c9d2e7\"\nparentId: \"brief-a4b1c8\" # <-- This links it to the parent task\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-opencode-v4\"\ndelegatee: \"agent-docs-writer\"\ntimestamp: \"2026-02-06T04:05:00Z\"\n---\n# Briefing: Update Developer Docs for SSO Refactor\n...\n```\n\nThis simple mechanism allows for the construction of a complete task tree, which is essential for tracing and debugging.\n\n### 8.2. The `trace.md` in a Cascading World\n\nThe `trace.md` file is the key to maintaining a coherent audit trail across multiple levels. The rules are simple:\n\n1.  **Pass it Down**: When an agent creates a sub-brief, it MUST pass a copy of its current `trace.md` along with the new `.brief.md` to the sub-agent.\n2.  **Append, Don't Replace**: The sub-agent appends its own actions to the `trace.md` it received.\n3.  **Return it Up**: When the sub-agent sends its `.response.md`, it MUST also return the updated `trace.md`.\n4.  **Merge**: The parent agent is responsible for merging the trace from the sub-task back into its main trace. For simple A→B→C chains, this is a simple append. For fan-out scenarios, the parent must handle parallel trace branches.\n\n### 8.3. Fan-Out and Fan-In Pattern\n\nBrief supports scenarios where one agent delegates tasks to multiple other agents in parallel and waits for all of them to complete.\n\nImagine Agent A needs to get a stock price (`brief-002` to Agent B) and a news sentiment analysis (`brief-003` to Agent C) to make a decision.\n\n1.  Agent A creates two separate briefs, both with the same `parentId` (e.g., the ID of the root user request).\n2.  Agent A sends `brief-002` to B and `brief-003` to C.\n3.  Agent A now waits until it has received both `.response.md` files for `brief-002` and `brief-003`.\n4.  Once both responses are received, Agent A can synthesize the results and complete its original task.\n\nThe SDK can provide helper utilities to manage this fan-out/fan-in logic, such as a `waitForAll(briefIds)` function.\n\n### 8.4. Depth Limiting: Preventing Infinite Recursion\n\nTo prevent runaway costs or infinite delegation loops, a `maxDepth` can be set in the root brief's frontmatter. Each level of delegation increments a `currentDepth` counter. If `currentDepth` exceeds `maxDepth`, the agent is forbidden from creating further sub-briefs.\n\nThese advanced features are designed to be **progressively disclosed**. For simple tasks, you only need to think about two Markdown files. For complex orchestrations, the `parentId` and `trace.md` provide the necessary power and control.\n"
  },
  {
    "path": "examples/01-simple-delegation/index.ts",
    "content": "/**\n * Example 01 — Simple Delegation (A → B)\n *\n * This example demonstrates the most basic Brief workflow:\n * Agent A creates a brief, Agent B receives it, executes the task,\n * and sends back a response.\n *\n * Run: pnpm example:simple\n */\n\nimport { Brief, BriefResponse, Trace } from '../../packages/brief-sdk/src/index.js';\n\n// ═══════════════════════════════════════════════════════════════════════\n// Simulate: Agent A (Orchestrator) creates a delegation brief\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('╔══════════════════════════════════════════════════════════╗');\nconsole.log('║   Brief Protocol — Example 01: Simple Delegation       ║');\nconsole.log('╚══════════════════════════════════════════════════════════╝\\n');\n\n// Step 1: Agent A creates a brief\nconsole.log('📋 [Agent A] Creating a delegation brief...\\n');\n\nconst brief = Brief.create({\n  delegator: 'agent-orchestrator',\n  delegatee: 'agent-code-reviewer',\n  body: `# Briefing: Review Pull Request #42\n\n## 1. Objective\n\nReview the code changes in Pull Request #42 for the authentication module.\n\n## 2. Context\n\nThe team has refactored the login flow to use OAuth 2.0 instead of\nsession-based authentication. This PR contains approximately 500 lines\nof changes across 12 files.\n\n## 3. Key Constraints\n\n- **Security Focus**: Pay special attention to token handling and storage.\n- **Performance**: Ensure no N+1 queries are introduced.\n\n## 4. Expected Deliverables\n\n1. A review summary with findings.\n2. Approval or rejection recommendation.`,\n});\n\nconsole.log('   Generated .brief.md:\\n');\nconsole.log('   ' + brief.content.split('\\n').join('\\n   '));\nconsole.log(`\\n   Brief ID: ${brief.id}`);\nconsole.log(`   Delegator: ${brief.delegator}`);\nconsole.log(`   Delegatee: ${brief.delegatee}`);\n\n// Start a trace\nconst trace = Trace.create();\ntrace.append({\n  agent: 'agent-orchestrator',\n  action: `Created delegation brief for code review.`,\n  briefId: brief.id,\n});\n\n// ═══════════════════════════════════════════════════════════════════════\n// Simulate: Sending the brief over the wire (e.g., via A2A protocol)\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('\\n📡 [Transport] Sending brief to agent-code-reviewer via A2A...\\n');\n\nconst wireContent = brief.content; // This is what gets sent\n\n// ═══════════════════════════════════════════════════════════════════════\n// Simulate: Agent B (Code Reviewer) receives and processes the brief\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('📥 [Agent B] Received brief. Parsing...\\n');\n\nconst receivedBrief = Brief.parse(wireContent);\n\nconsole.log(`   Parsed Brief ID: ${receivedBrief.id}`);\nconsole.log(`   From: ${receivedBrief.delegator}`);\nconsole.log(`   Is sub-brief: ${receivedBrief.isSubBrief}`);\n\ntrace.append({\n  agent: 'agent-code-reviewer',\n  action: `Accepted brief ${receivedBrief.id}. Starting code review.`,\n  briefId: receivedBrief.id,\n});\n\n// Simulate doing the actual work...\nconsole.log('\\n⚙️  [Agent B] Performing code review...\\n');\n\n// Step 2: Agent B creates a response\nconsole.log('📝 [Agent B] Creating response...\\n');\n\nconst response = receivedBrief.createResponse({\n  status: 'success',\n  body: `# Review Complete: PR #42\n\n## 1. Summary\n\nThe OAuth 2.0 migration looks solid overall. Code quality is high,\nand the token handling follows best practices.\n\n## 2. Findings\n\n- **Approved** with minor suggestions.\n- Found 2 minor issues: unused import in \\`auth/handler.ts\\` and\n  a missing error boundary in \\`auth/callback.tsx\\`.\n\n## 3. Recommendation\n\n**Approve** — merge after addressing the minor issues above.`,\n});\n\ntrace.append({\n  agent: 'agent-code-reviewer',\n  action: `Completed review. Responded with status: ${response.status}.`,\n  briefId: receivedBrief.id,\n});\n\nconsole.log('   Generated .response.md:\\n');\nconsole.log('   ' + response.content.split('\\n').join('\\n   '));\n\n// ═══════════════════════════════════════════════════════════════════════\n// Simulate: Agent A receives the response\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('\\n📥 [Agent A] Received response.\\n');\n\nconst receivedResponse = BriefResponse.parse(response.content);\n\nconsole.log(`   Status: ${receivedResponse.status}`);\nconsole.log(`   Success: ${receivedResponse.isSuccess}`);\n\ntrace.append({\n  agent: 'agent-orchestrator',\n  action: `Received response for ${receivedResponse.id}. Status: ${receivedResponse.status}.`,\n  briefId: receivedResponse.id,\n});\n\n// ═══════════════════════════════════════════════════════════════════════\n// Print the full trace\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('\\n📊 Full Trace (trace.md):\\n');\nconsole.log(trace.toString());\nconsole.log('\\n✅ Done!');\n"
  },
  {
    "path": "examples/02-cascade-chain/index.ts",
    "content": "/**\n * Example 02 — Cascading Delegation (A → B → C)\n *\n * This example demonstrates multi-level cascading delegation:\n * Agent A delegates to Agent B, who then sub-delegates part of\n * the work to Agent C. The trace follows the entire chain.\n *\n * Run: pnpm example:cascade\n */\n\nimport { Brief, BriefResponse, Trace } from '../../packages/brief-sdk/src/index.js';\n\nconsole.log('╔══════════════════════════════════════════════════════════╗');\nconsole.log('║   Brief Protocol — Example 02: Cascading Delegation    ║');\nconsole.log('╚══════════════════════════════════════════════════════════╝\\n');\n\n// ═══════════════════════════════════════════════════════════════════════\n// Level 0: Agent A creates the root brief with a depth limit\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🔵 [Agent A — Orchestrator] Creating root brief...\\n');\n\nconst rootBrief = Brief.create({\n  delegator: 'agent-orchestrator',\n  delegatee: 'agent-fullstack-dev',\n  maxDepth: 3,\n  body: `# Briefing: Build User Profile Page\n\n## 1. Objective\n\nBuild a complete user profile page with avatar upload, bio editing,\nand activity history.\n\n## 2. Context\n\nWe are building a SaaS dashboard. The profile page is the last\nremaining feature before the v1.0 launch.\n\n## 3. Expected Deliverables\n\n1. Frontend React component for the profile page.\n2. Backend API endpoints for profile CRUD operations.\n3. Updated API documentation.`,\n});\n\nconsole.log(`   Root Brief: ${rootBrief.id}`);\nconsole.log(`   Max Depth: ${rootBrief.meta.maxDepth}`);\nconsole.log(`   Current Depth: ${rootBrief.meta.currentDepth}`);\nconsole.log(`   Can Delegate: ${rootBrief.canDelegate}\\n`);\n\n// Initialize the trace\nconst trace = Trace.create();\ntrace.append({\n  agent: 'agent-orchestrator',\n  action: 'Created root brief for building user profile page.',\n  briefId: rootBrief.id,\n});\n\n// ═══════════════════════════════════════════════════════════════════════\n// Level 1: Agent B receives the brief and sub-delegates docs to Agent C\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🟢 [Agent B — Fullstack Dev] Received brief. Analyzing...\\n');\n\nconst receivedByB = Brief.parse(rootBrief.content);\n\ntrace.append({\n  agent: 'agent-fullstack-dev',\n  action: `Accepted brief ${receivedByB.id}. Will handle frontend and backend, delegating docs.`,\n  briefId: receivedByB.id,\n});\n\n// Agent B decides to sub-delegate the documentation task\nconsole.log('   Agent B can delegate further:', receivedByB.canDelegate);\nconsole.log('   Creating sub-brief for documentation...\\n');\n\nconst docsBrief = receivedByB.createSubBrief({\n  delegator: 'agent-fullstack-dev',\n  delegatee: 'agent-docs-writer',\n  body: `# Briefing: Write API Documentation for Profile Endpoints\n\n## 1. Objective\n\nWrite comprehensive API documentation for the new user profile endpoints.\n\n## 2. Endpoints to Document\n\n- \\`GET /api/v1/profile/:id\\` — Fetch user profile\n- \\`PUT /api/v1/profile/:id\\` — Update user profile\n- \\`POST /api/v1/profile/:id/avatar\\` — Upload avatar\n\n## 3. Expected Deliverables\n\n1. OpenAPI 3.0 specification file.\n2. Human-readable Markdown documentation.`,\n});\n\nconsole.log(`   Sub-Brief: ${docsBrief.id}`);\nconsole.log(`   Parent ID: ${docsBrief.parentId}`);\nconsole.log(`   Current Depth: ${docsBrief.meta.currentDepth}`);\nconsole.log(`   Is Sub-Brief: ${docsBrief.isSubBrief}\\n`);\n\ntrace.append({\n  agent: 'agent-fullstack-dev',\n  action: `Delegated documentation task. Created sub-brief.`,\n  briefId: docsBrief.id,\n});\n\n// Pass a copy of the trace to Agent C\nconst traceForC = trace.clone();\n\n// ═══════════════════════════════════════════════════════════════════════\n// Level 2: Agent C receives the sub-brief and completes the docs\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🟡 [Agent C — Docs Writer] Received sub-brief. Working...\\n');\n\nconst receivedByC = Brief.parse(docsBrief.content);\n\ntraceForC.append({\n  agent: 'agent-docs-writer',\n  action: `Accepted sub-brief ${receivedByC.id}. Writing API documentation.`,\n  briefId: receivedByC.id,\n});\n\n// Agent C does the work and responds\nconst docsResponse = receivedByC.createResponse({\n  status: 'success',\n  body: `# Response: API Documentation Complete\n\n## 1. Summary\n\nAll three profile endpoints have been documented with request/response\nschemas, example payloads, and error codes.\n\n## 2. Delivered Artifacts\n\n- OpenAPI spec: \\`docs/openapi/profile.yaml\\`\n- Markdown docs: \\`docs/api/profile.md\\``,\n});\n\ntraceForC.append({\n  agent: 'agent-docs-writer',\n  action: `Completed documentation. Status: ${docsResponse.status}.`,\n  briefId: receivedByC.id,\n});\n\nconsole.log(`   Response Status: ${docsResponse.status}`);\nconsole.log(`   Response sent back to Agent B.\\n`);\n\n// ═══════════════════════════════════════════════════════════════════════\n// Back to Level 1: Agent B merges results and responds to Agent A\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🟢 [Agent B — Fullstack Dev] Received docs response. Merging...\\n');\n\n// Merge the trace from Agent C back into the main trace\ntrace.merge(traceForC);\n\nconst parsedDocsResponse = BriefResponse.parse(docsResponse.content);\nconsole.log(`   Docs sub-task status: ${parsedDocsResponse.status}`);\n\ntrace.append({\n  agent: 'agent-fullstack-dev',\n  action: `Received docs response. All sub-tasks complete. Building final response.`,\n  briefId: receivedByB.id,\n});\n\n// Agent B creates the final response for Agent A\nconst finalResponse = receivedByB.createResponse({\n  status: 'success',\n  body: `# Response: User Profile Page Complete\n\n## 1. Summary\n\nThe user profile page has been fully implemented:\n- Frontend React component with avatar upload and bio editing.\n- Backend API with three new endpoints.\n- API documentation (delegated to agent-docs-writer, completed successfully).\n\n## 2. Delivered Artifacts\n\n- Frontend: \\`src/pages/Profile.tsx\\`\n- Backend: \\`src/api/routes/profile.ts\\`\n- API Docs: \\`docs/api/profile.md\\`\n- OpenAPI: \\`docs/openapi/profile.yaml\\``,\n});\n\ntrace.append({\n  agent: 'agent-fullstack-dev',\n  action: `Responded to root brief. Status: ${finalResponse.status}.`,\n  briefId: receivedByB.id,\n});\n\n// ═══════════════════════════════════════════════════════════════════════\n// Back to Level 0: Agent A receives the final response\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🔵 [Agent A — Orchestrator] Received final response.\\n');\n\nconst finalParsed = BriefResponse.parse(finalResponse.content);\nconsole.log(`   Final Status: ${finalParsed.status}`);\nconsole.log(`   Success: ${finalParsed.isSuccess}`);\n\ntrace.append({\n  agent: 'agent-orchestrator',\n  action: `Received final response. Task complete.`,\n  briefId: rootBrief.id,\n});\n\n// ═══════════════════════════════════════════════════════════════════════\n// Print the complete trace\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('\\n📊 Full Cascade Trace (trace.md):\\n');\nconsole.log(trace.toString());\nconsole.log('\\n✅ Done! The entire A → B → C cascade completed successfully.');\n"
  },
  {
    "path": "examples/03-fan-out/index.ts",
    "content": "/**\n * Example 03 — Fan-Out / Fan-In (A → B ∥ C)\n *\n * This example demonstrates the fan-out pattern:\n * Agent A delegates two independent sub-tasks to Agent B and Agent C\n * in parallel, then waits for both to complete before synthesizing\n * the final result.\n *\n * Run: pnpm example:fanout\n */\n\nimport { Brief, BriefResponse, Trace } from '../../packages/brief-sdk/src/index.js';\n\nconsole.log('╔══════════════════════════════════════════════════════════╗');\nconsole.log('║   Brief Protocol — Example 03: Fan-Out / Fan-In        ║');\nconsole.log('╚══════════════════════════════════════════════════════════╝\\n');\n\n// ═══════════════════════════════════════════════════════════════════════\n// Agent A: Create the root brief and fan-out to two sub-agents\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🔵 [Agent A — Investment Advisor] Analyzing stock NVDA...\\n');\n\nconst rootBrief = Brief.create({\n  delegator: 'agent-investment-advisor',\n  delegatee: 'self',\n  maxDepth: 2,\n  body: `# Briefing: Analyze NVDA for Investment Decision\n\n## 1. Objective\n\nProvide a comprehensive buy/hold/sell recommendation for NVIDIA (NVDA).\n\n## 2. Required Analysis\n\n1. Technical price analysis (delegate to market-data agent).\n2. News sentiment analysis (delegate to news-analyst agent).\n3. Synthesize both into a final recommendation.`,\n});\n\nconst trace = Trace.create();\ntrace.append({\n  agent: 'agent-investment-advisor',\n  action: 'Received user request: Analyze NVDA. Fanning out to specialists.',\n  briefId: rootBrief.id,\n});\n\n// ── Fan-Out: Create two parallel sub-briefs ───────────────────────────\n\nconsole.log('   📤 Fanning out to 2 specialist agents...\\n');\n\n// Sub-brief 1: Market Data Analysis\nconst marketBrief = rootBrief.createSubBrief({\n  delegator: 'agent-investment-advisor',\n  delegatee: 'agent-market-data',\n  body: `# Briefing: NVDA Technical Price Analysis\n\n## 1. Objective\n\nProvide a technical analysis of NVIDIA (NVDA) stock price.\n\n## 2. Required Data\n\n- Current price and 52-week range.\n- 50-day and 200-day moving averages.\n- RSI and MACD indicators.\n\n## 3. Expected Deliverables\n\nA structured summary with buy/sell signals from technical indicators.`,\n});\n\n// Sub-brief 2: News Sentiment Analysis\nconst newsBrief = rootBrief.createSubBrief({\n  delegator: 'agent-investment-advisor',\n  delegatee: 'agent-news-analyst',\n  body: `# Briefing: NVDA News Sentiment Analysis\n\n## 1. Objective\n\nAnalyze recent news sentiment for NVIDIA (NVDA).\n\n## 2. Scope\n\n- Last 7 days of news articles.\n- Focus on earnings, product launches, and regulatory news.\n\n## 3. Expected Deliverables\n\nA sentiment score (bullish/neutral/bearish) with supporting evidence.`,\n});\n\nconsole.log(`   Sub-Brief 1 (Market): ${marketBrief.id} → agent-market-data`);\nconsole.log(`   Sub-Brief 2 (News):   ${newsBrief.id} → agent-news-analyst`);\nconsole.log(`   Both have parentId:   ${rootBrief.id}\\n`);\n\ntrace.append({\n  agent: 'agent-investment-advisor',\n  action: `Fan-out: created market analysis sub-brief.`,\n  briefId: marketBrief.id,\n});\n\ntrace.append({\n  agent: 'agent-investment-advisor',\n  action: `Fan-out: created news sentiment sub-brief.`,\n  briefId: newsBrief.id,\n});\n\n// ═══════════════════════════════════════════════════════════════════════\n// Simulate parallel execution of both sub-agents\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('⚡ [Parallel Execution] Both agents working simultaneously...\\n');\n\n// ── Agent B: Market Data ──────────────────────────────────────────────\n\nconst traceForB = trace.clone();\n\nconsole.log('🟢 [Agent B — Market Data] Analyzing NVDA price...');\n\nconst receivedByB = Brief.parse(marketBrief.content);\ntraceForB.append({\n  agent: 'agent-market-data',\n  action: `Accepted brief. Running technical analysis on NVDA.`,\n  briefId: receivedByB.id,\n});\n\nconst marketResponse = receivedByB.createResponse({\n  status: 'success',\n  body: `# NVDA Technical Analysis\n\n## Summary\n\n| Indicator | Value | Signal |\n|-----------|-------|--------|\n| Price | $142.50 | — |\n| 50-day MA | $135.20 | Bullish (price above) |\n| 200-day MA | $118.40 | Bullish (price above) |\n| RSI (14) | 62.3 | Neutral |\n| MACD | +2.15 | Bullish crossover |\n\n## Technical Verdict: **Moderately Bullish**`,\n});\n\ntraceForB.append({\n  agent: 'agent-market-data',\n  action: `Completed technical analysis. Verdict: Moderately Bullish.`,\n  briefId: receivedByB.id,\n});\n\nconsole.log('   ✅ Market analysis complete: Moderately Bullish\\n');\n\n// ── Agent C: News Sentiment ───────────────────────────────────────────\n\nconst traceForC = trace.clone();\n\nconsole.log('🟡 [Agent C — News Analyst] Analyzing NVDA news...');\n\nconst receivedByC = Brief.parse(newsBrief.content);\ntraceForC.append({\n  agent: 'agent-news-analyst',\n  action: `Accepted brief. Scanning last 7 days of NVDA news.`,\n  briefId: receivedByC.id,\n});\n\nconst newsResponse = receivedByC.createResponse({\n  status: 'success',\n  body: `# NVDA News Sentiment Analysis\n\n## Summary\n\nAnalyzed 47 articles from the past 7 days.\n\n| Category | Count | Sentiment |\n|----------|-------|-----------|\n| Earnings | 12 | Bullish |\n| AI/Product | 18 | Very Bullish |\n| Regulatory | 8 | Neutral |\n| Competition | 9 | Slightly Bearish |\n\n## Sentiment Verdict: **Bullish** (score: 7.2/10)`,\n});\n\ntraceForC.append({\n  agent: 'agent-news-analyst',\n  action: `Completed sentiment analysis. Verdict: Bullish (7.2/10).`,\n  briefId: receivedByC.id,\n});\n\nconsole.log('   ✅ News analysis complete: Bullish (7.2/10)\\n');\n\n// ═══════════════════════════════════════════════════════════════════════\n// Fan-In: Agent A collects both responses and synthesizes\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('🔵 [Agent A — Investment Advisor] Fan-in: collecting results...\\n');\n\n// Merge traces from both parallel branches\ntrace.merge(traceForB);\ntrace.merge(traceForC);\n\nconst parsedMarket = BriefResponse.parse(marketResponse.content);\nconst parsedNews = BriefResponse.parse(newsResponse.content);\n\nconsole.log(`   Market sub-task: ${parsedMarket.status}`);\nconsole.log(`   News sub-task:   ${parsedNews.status}`);\n\n// Both succeeded — synthesize the final recommendation\ntrace.append({\n  agent: 'agent-investment-advisor',\n  action: `Fan-in complete. Both sub-tasks succeeded. Synthesizing recommendation.`,\n  briefId: rootBrief.id,\n});\n\nconst finalResponse = rootBrief.createResponse({\n  status: 'success',\n  body: `# NVDA Investment Recommendation\n\n## 1. Synthesis\n\n| Source | Verdict |\n|--------|---------|\n| Technical Analysis | Moderately Bullish |\n| News Sentiment | Bullish (7.2/10) |\n\n## 2. Final Recommendation\n\n**BUY** — Both technical indicators and news sentiment are aligned\nin a bullish direction. The stock is trading above both major moving\naverages with a bullish MACD crossover, and recent news around AI\nproducts is overwhelmingly positive.\n\n## 3. Risk Factors\n\n- RSI approaching overbought territory (62.3).\n- Some competitive pressure noted in news analysis.`,\n});\n\ntrace.append({\n  agent: 'agent-investment-advisor',\n  action: `Final recommendation: BUY. Task complete.`,\n  briefId: rootBrief.id,\n});\n\nconsole.log(`\\n   🎯 Final Recommendation: BUY`);\n\n// ═══════════════════════════════════════════════════════════════════════\n// Print the complete trace\n// ═══════════════════════════════════════════════════════════════════════\n\nconsole.log('\\n📊 Full Fan-Out/Fan-In Trace (trace.md):\\n');\nconsole.log(trace.toString());\nconsole.log('\\n✅ Done! Fan-out to 2 agents, fan-in, and synthesis completed.');\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"brief-protocol\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"description\": \"A protocol for explicit agent delegation — turning chaotic multi-agent handoffs into structured, auditable task briefings.\",\n  \"keywords\": [\n    \"agent\",\n    \"multi-agent\",\n    \"delegation\",\n    \"protocol\",\n    \"ai\",\n    \"llm\",\n    \"mcp\",\n    \"a2a\",\n    \"orchestration\"\n  ],\n  \"author\": \"OpenPerf\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/openperf/brief.git\"\n  },\n  \"homepage\": \"https://github.com/openperf/brief\",\n  \"scripts\": {\n    \"build\": \"pnpm -r build\",\n    \"test\": \"pnpm -r test\",\n    \"example:simple\": \"npx tsx examples/01-simple-delegation/index.ts\",\n    \"example:cascade\": \"npx tsx examples/02-cascade-chain/index.ts\",\n    \"example:fanout\": \"npx tsx examples/03-fan-out/index.ts\"\n  },\n  \"devDependencies\": {\n    \"tsx\": \"^4.7.0\",\n    \"typescript\": \"^5.4.0\"\n  }\n}\n"
  },
  {
    "path": "packages/brief-sdk/__tests__/brief.test.ts",
    "content": "import { describe, it, expect } from 'vitest';\nimport { Brief } from '../src/brief.js';\n\nconst SAMPLE_BRIEF_MD = `---\nid: \"brief-test01\"\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-a\"\ndelegatee: \"agent-b\"\ntimestamp: \"2026-02-06T10:00:00Z\"\ncurrentDepth: 0\n---\n\n# Briefing: Test Task\n\n## 1. Objective\n\nDo something useful for testing.\n\n## 2. Expected Deliverables\n\n1. A test result.`;\n\ndescribe('Brief.parse', () => {\n  it('should parse a valid .brief.md string', () => {\n    const brief = Brief.parse(SAMPLE_BRIEF_MD);\n    expect(brief.id).toBe('brief-test01');\n    expect(brief.delegator).toBe('agent-a');\n    expect(brief.delegatee).toBe('agent-b');\n    expect(brief.meta.protocolVersion).toBe('1.2.0');\n    expect(brief.body).toContain('# Briefing: Test Task');\n    expect(brief.isSubBrief).toBe(false);\n  });\n\n  it('should throw on missing required fields', () => {\n    const invalid = `---\nid: \"test\"\n---\n\nBody.`;\n\n    expect(() => Brief.parse(invalid)).toThrow('Invalid Brief document');\n  });\n\n  it('should parse a sub-brief with parentId', () => {\n    const subBriefMd = `---\nid: \"brief-sub01\"\nprotocolVersion: \"1.2.0\"\ndelegator: \"agent-b\"\ndelegatee: \"agent-c\"\ntimestamp: \"2026-02-06T10:05:00Z\"\nparentId: \"brief-test01\"\ncurrentDepth: 1\nmaxDepth: 3\n---\n\n# Sub-task briefing`;\n\n    const brief = Brief.parse(subBriefMd);\n    expect(brief.isSubBrief).toBe(true);\n    expect(brief.parentId).toBe('brief-test01');\n    expect(brief.meta.currentDepth).toBe(1);\n    expect(brief.canDelegate).toBe(true);\n  });\n});\n\ndescribe('Brief.create', () => {\n  it('should create a brief with auto-generated id', () => {\n    const brief = Brief.create({\n      delegator: 'agent-x',\n      delegatee: 'agent-y',\n      body: '# Task\\n\\nDo it.',\n    });\n\n    expect(brief.id).toMatch(/^brief-[0-9a-f]{6}$/);\n    expect(brief.delegator).toBe('agent-x');\n    expect(brief.delegatee).toBe('agent-y');\n    expect(brief.meta.protocolVersion).toBe('1.2.0');\n    expect(brief.meta.currentDepth).toBe(0);\n    expect(brief.content).toContain('---');\n    expect(brief.content).toContain('# Task');\n  });\n\n  it('should create a brief with custom id', () => {\n    const brief = Brief.create({\n      id: 'my-custom-id',\n      delegator: 'a',\n      delegatee: 'b',\n      body: 'Body.',\n    });\n\n    expect(brief.id).toBe('my-custom-id');\n  });\n\n  it('should produce content that can be round-tripped via parse', () => {\n    const original = Brief.create({\n      delegator: 'agent-1',\n      delegatee: 'agent-2',\n      body: '# Round Trip\\n\\nTest content.',\n      maxDepth: 5,\n    });\n\n    const parsed = Brief.parse(original.content);\n    expect(parsed.id).toBe(original.id);\n    expect(parsed.delegator).toBe('agent-1');\n    expect(parsed.delegatee).toBe('agent-2');\n    expect(parsed.meta.maxDepth).toBe(5);\n    expect(parsed.body).toContain('# Round Trip');\n  });\n});\n\ndescribe('Brief.createSubBrief', () => {\n  it('should create a sub-brief linked to the parent', () => {\n    const parent = Brief.create({\n      delegator: 'agent-a',\n      delegatee: 'agent-b',\n      body: '# Parent Task',\n      maxDepth: 3,\n    });\n\n    const child = parent.createSubBrief({\n      delegator: 'agent-b',\n      delegatee: 'agent-c',\n      body: '# Child Task',\n    });\n\n    expect(child.isSubBrief).toBe(true);\n    expect(child.parentId).toBe(parent.id);\n    expect(child.meta.currentDepth).toBe(1);\n    expect(child.meta.maxDepth).toBe(3);\n  });\n\n  it('should throw when max depth is reached', () => {\n    const atLimit = Brief.create({\n      delegator: 'a',\n      delegatee: 'b',\n      body: 'Task',\n      maxDepth: 1,\n      currentDepth: 1,\n    });\n\n    expect(atLimit.canDelegate).toBe(false);\n    expect(() =>\n      atLimit.createSubBrief({\n        delegator: 'b',\n        delegatee: 'c',\n        body: 'Sub-task',\n      }),\n    ).toThrow('maximum delegation depth');\n  });\n\n  it('should allow unlimited depth when maxDepth is not set', () => {\n    const noLimit = Brief.create({\n      delegator: 'a',\n      delegatee: 'b',\n      body: 'Task',\n    });\n\n    expect(noLimit.canDelegate).toBe(true);\n\n    const child = noLimit.createSubBrief({\n      delegator: 'b',\n      delegatee: 'c',\n      body: 'Sub-task',\n    });\n\n    expect(child.isSubBrief).toBe(true);\n  });\n});\n\ndescribe('Brief.createResponse', () => {\n  it('should create a response linked to the brief id', () => {\n    const brief = Brief.parse(SAMPLE_BRIEF_MD);\n    const response = brief.createResponse({\n      status: 'success',\n      body: '# Done\\n\\nAll good.',\n    });\n\n    expect(response.id).toBe('brief-test01');\n    expect(response.status).toBe('success');\n    expect(response.isSuccess).toBe(true);\n    expect(response.body).toContain('# Done');\n  });\n});\n"
  },
  {
    "path": "packages/brief-sdk/__tests__/parser.test.ts",
    "content": "import { describe, it, expect } from 'vitest';\nimport { parseDocument, serializeDocument } from '../src/parser.js';\n\ndescribe('parseDocument', () => {\n  it('should parse a valid document with frontmatter and body', () => {\n    const content = `---\nid: \"brief-001\"\nstatus: \"success\"\n---\n\n# Hello World\n\nSome body content.`;\n\n    const result = parseDocument<{ id: string; status: string }>(content);\n    expect(result.meta.id).toBe('brief-001');\n    expect(result.meta.status).toBe('success');\n    expect(result.body).toContain('# Hello World');\n    expect(result.body).toContain('Some body content.');\n  });\n\n  it('should handle frontmatter with various YAML types', () => {\n    const content = `---\nname: \"test\"\ncount: 42\nenabled: true\n---\n\nBody text.`;\n\n    const result = parseDocument<{ name: string; count: number; enabled: boolean }>(content);\n    expect(result.meta.name).toBe('test');\n    expect(result.meta.count).toBe(42);\n    expect(result.meta.enabled).toBe(true);\n  });\n\n  it('should throw on missing frontmatter delimiters', () => {\n    expect(() => parseDocument('No frontmatter here')).toThrow(\n      'missing YAML frontmatter delimiters',\n    );\n  });\n\n  it('should throw on invalid YAML', () => {\n    const content = `---\n: invalid: yaml: [\n---\n\nBody.`;\n\n    expect(() => parseDocument(content)).toThrow('Invalid YAML frontmatter');\n  });\n\n  it('should throw on scalar YAML frontmatter', () => {\n    const content = `---\njust a string\n---\n\nBody.`;\n\n    expect(() => parseDocument(content)).toThrow('must be a mapping');\n  });\n\n  it('should handle empty body', () => {\n    const content = `---\nid: \"test\"\n---\n`;\n\n    const result = parseDocument<{ id: string }>(content);\n    expect(result.meta.id).toBe('test');\n    expect(result.body).toBe('');\n  });\n});\n\ndescribe('serializeDocument', () => {\n  it('should produce a valid frontmatter + body document', () => {\n    const result = serializeDocument({ id: 'brief-001', status: 'success' }, '# Hello');\n    expect(result).toContain('---');\n    expect(result).toContain('id: brief-001');\n    expect(result).toContain('status: success');\n    expect(result).toContain('# Hello');\n  });\n\n  it('should strip undefined values from frontmatter', () => {\n    const result = serializeDocument({ id: 'test', extra: undefined }, 'Body');\n    expect(result).not.toContain('extra');\n  });\n\n  it('should produce a round-trippable document', () => {\n    const meta = { id: 'brief-rt', version: '1.0.0' };\n    const body = '# Round Trip Test\\n\\nThis should survive.';\n    const serialized = serializeDocument(meta, body);\n    const parsed = parseDocument<typeof meta>(serialized);\n    expect(parsed.meta.id).toBe('brief-rt');\n    expect(parsed.meta.version).toBe('1.0.0');\n    expect(parsed.body).toContain('# Round Trip Test');\n  });\n});\n"
  },
  {
    "path": "packages/brief-sdk/__tests__/response.test.ts",
    "content": "import { describe, it, expect } from 'vitest';\nimport { BriefResponse } from '../src/response.js';\n\nconst SAMPLE_RESPONSE_MD = `---\nid: \"brief-resp01\"\nstatus: \"success\"\ntimestamp: \"2026-02-06T10:30:00Z\"\n---\n\n# Response: Task Complete\n\n## 1. Summary\n\nEverything went well.\n\n## 2. Delivered Artifacts\n\n- Report: \\`output/report.pdf\\``;\n\ndescribe('BriefResponse.parse', () => {\n  it('should parse a valid .response.md string', () => {\n    const response = BriefResponse.parse(SAMPLE_RESPONSE_MD);\n    expect(response.id).toBe('brief-resp01');\n    expect(response.status).toBe('success');\n    expect(response.isSuccess).toBe(true);\n    expect(response.body).toContain('# Response: Task Complete');\n  });\n\n  it('should correctly identify non-success statuses', () => {\n    const failureMd = `---\nid: \"brief-fail\"\nstatus: \"failure\"\ntimestamp: \"2026-02-06T11:00:00Z\"\n---\n\n# Response: Failed\n\nSomething went wrong.`;\n\n    const response = BriefResponse.parse(failureMd);\n    expect(response.status).toBe('failure');\n    expect(response.isSuccess).toBe(false);\n  });\n\n  it('should throw on invalid status', () => {\n    const invalidMd = `---\nid: \"test\"\nstatus: \"unknown\"\ntimestamp: \"2026-02-06T11:00:00Z\"\n---\n\nBody.`;\n\n    expect(() => BriefResponse.parse(invalidMd)).toThrow('Invalid Response document');\n  });\n\n  it('should throw on missing fields', () => {\n    const missingMd = `---\nid: \"test\"\n---\n\nBody.`;\n\n    expect(() => BriefResponse.parse(missingMd)).toThrow('Invalid Response document');\n  });\n});\n\ndescribe('BriefResponse.create', () => {\n  it('should create a response with auto-generated timestamp', () => {\n    const response = BriefResponse.create({\n      id: 'brief-abc',\n      status: 'success',\n      body: '# Done',\n    });\n\n    expect(response.id).toBe('brief-abc');\n    expect(response.status).toBe('success');\n    expect(response.meta.timestamp).toBeTruthy();\n    expect(response.content).toContain('---');\n    expect(response.content).toContain('# Done');\n  });\n\n  it('should produce content that can be round-tripped via parse', () => {\n    const original = BriefResponse.create({\n      id: 'brief-rt',\n      status: 'partial',\n      body: '# Partial Result\\n\\n50% done.',\n    });\n\n    const parsed = BriefResponse.parse(original.content);\n    expect(parsed.id).toBe('brief-rt');\n    expect(parsed.status).toBe('partial');\n    expect(parsed.body).toContain('# Partial Result');\n  });\n\n  it('should support all valid status types', () => {\n    const statuses = ['success', 'failure', 'partial', 'rejected'] as const;\n\n    for (const status of statuses) {\n      const response = BriefResponse.create({\n        id: `brief-${status}`,\n        status,\n        body: `Status: ${status}`,\n      });\n      expect(response.status).toBe(status);\n    }\n  });\n});\n"
  },
  {
    "path": "packages/brief-sdk/__tests__/trace.test.ts",
    "content": "import { describe, it, expect } from 'vitest';\nimport { Trace } from '../src/trace.js';\n\ndescribe('Trace.create & append', () => {\n  it('should create an empty trace', () => {\n    const trace = Trace.create();\n    expect(trace.length).toBe(0);\n    expect(trace.getEntries()).toEqual([]);\n  });\n\n  it('should append entries with auto-generated timestamps', () => {\n    const trace = Trace.create();\n    trace.append({ agent: 'agent-a', action: 'Did something.' });\n\n    expect(trace.length).toBe(1);\n    const entries = trace.getEntries();\n    expect(entries[0].agent).toBe('agent-a');\n    expect(entries[0].action).toBe('Did something.');\n    expect(entries[0].timestamp).toBeTruthy();\n  });\n\n  it('should append entries with briefId', () => {\n    const trace = Trace.create();\n    trace.append({\n      agent: 'agent-b',\n      action: 'Created brief.',\n      briefId: 'brief-001',\n    });\n\n    expect(trace.getEntries()[0].briefId).toBe('brief-001');\n  });\n\n  it('should support chained append calls', () => {\n    const trace = Trace.create()\n      .append({ agent: 'a', action: 'Step 1.' })\n      .append({ agent: 'b', action: 'Step 2.' })\n      .append({ agent: 'c', action: 'Step 3.' });\n\n    expect(trace.length).toBe(3);\n  });\n});\n\ndescribe('Trace.clone', () => {\n  it('should create an independent copy', () => {\n    const original = Trace.create();\n    original.append({ agent: 'agent-a', action: 'Original action.' });\n\n    const cloned = original.clone();\n    cloned.append({ agent: 'agent-b', action: 'Cloned action.' });\n\n    expect(original.length).toBe(1);\n    expect(cloned.length).toBe(2);\n  });\n});\n\ndescribe('Trace.merge', () => {\n  it('should merge entries without duplicates', () => {\n    const ts = '2026-02-06T10:00:00Z';\n\n    const traceA = Trace.create();\n    traceA.append({ agent: 'shared', action: 'Common action.', timestamp: ts });\n    traceA.append({ agent: 'agent-a', action: 'A-only action.', timestamp: '2026-02-06T10:01:00Z' });\n\n    const traceB = Trace.create();\n    traceB.append({ agent: 'shared', action: 'Common action.', timestamp: ts });\n    traceB.append({ agent: 'agent-b', action: 'B-only action.', timestamp: '2026-02-06T10:02:00Z' });\n\n    traceA.merge(traceB);\n\n    // Should have 3 entries: common + A-only + B-only (no duplicate of common)\n    expect(traceA.length).toBe(3);\n    const agents = traceA.getEntries().map((e) => e.agent);\n    expect(agents).toContain('shared');\n    expect(agents).toContain('agent-a');\n    expect(agents).toContain('agent-b');\n  });\n\n  it('should maintain chronological order after merge', () => {\n    const traceA = Trace.create();\n    traceA.append({ agent: 'a', action: 'First.', timestamp: '2026-02-06T10:00:00Z' });\n    traceA.append({ agent: 'a', action: 'Third.', timestamp: '2026-02-06T10:02:00Z' });\n\n    const traceB = Trace.create();\n    traceB.append({ agent: 'b', action: 'Second.', timestamp: '2026-02-06T10:01:00Z' });\n\n    traceA.merge(traceB);\n\n    const actions = traceA.getEntries().map((e) => e.action);\n    expect(actions).toEqual(['First.', 'Second.', 'Third.']);\n  });\n});\n\ndescribe('Trace serialization (toString / parse)', () => {\n  it('should serialize to valid trace.md format', () => {\n    const trace = Trace.create();\n    trace.append({\n      agent: 'agent-orchestrator',\n      action: 'Created delegation brief.',\n      briefId: 'brief-001',\n      timestamp: '2026-02-06T10:00:00Z',\n    });\n\n    const output = trace.toString();\n    expect(output).toContain('**Agent**: `agent-orchestrator`');\n    expect(output).toContain('@ `2026-02-06T10:00:00Z`');\n    expect(output).toContain('**Action**: Created delegation brief.');\n    expect(output).toContain('**Brief**: `brief-001`');\n  });\n\n  it('should round-trip through toString and parse', () => {\n    const original = Trace.create();\n    original.append({\n      agent: 'agent-a',\n      action: 'Step one.',\n      briefId: 'brief-aaa',\n      timestamp: '2026-02-06T10:00:00Z',\n    });\n    original.append({\n      agent: 'agent-b',\n      action: 'Step two.',\n      timestamp: '2026-02-06T10:05:00Z',\n    });\n\n    const serialized = original.toString();\n    const parsed = Trace.parse(serialized);\n\n    expect(parsed.length).toBe(2);\n    const entries = parsed.getEntries();\n    expect(entries[0].agent).toBe('agent-a');\n    expect(entries[0].action).toBe('Step one.');\n    expect(entries[0].briefId).toBe('brief-aaa');\n    expect(entries[1].agent).toBe('agent-b');\n    expect(entries[1].action).toBe('Step two.');\n    expect(entries[1].briefId).toBeUndefined();\n  });\n\n  it('should return empty string for empty trace', () => {\n    const trace = Trace.create();\n    expect(trace.toString()).toBe('');\n  });\n\n  it('should parse empty string into empty trace', () => {\n    const trace = Trace.parse('');\n    expect(trace.length).toBe(0);\n  });\n});\n"
  },
  {
    "path": "packages/brief-sdk/package.json",
    "content": "{\n  \"name\": \"brief-sdk\",\n  \"version\": \"1.0.0\",\n  \"description\": \"TypeScript SDK for the Brief protocol — explicit agent delegation made simple.\",\n  \"type\": \"module\",\n  \"main\": \"./dist/index.js\",\n  \"types\": \"./dist/index.d.ts\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/index.js\",\n      \"types\": \"./dist/index.d.ts\"\n    }\n  },\n  \"files\": [\n    \"dist\",\n    \"README.md\"\n  ],\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"test\": \"vitest run\",\n    \"test:watch\": \"vitest\"\n  },\n  \"keywords\": [\n    \"brief\",\n    \"agent\",\n    \"delegation\",\n    \"protocol\",\n    \"multi-agent\",\n    \"ai\"\n  ],\n  \"author\": \"OpenPerf\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/openperf/brief.git\",\n    \"directory\": \"packages/brief-sdk\"\n  },\n  \"homepage\": \"https://github.com/openperf/brief\",\n  \"bugs\": {\n    \"url\": \"https://github.com/openperf/brief/issues\"\n  },\n  \"dependencies\": {\n    \"yaml\": \"^2.4.0\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.4.0\",\n    \"vitest\": \"^2.0.0\"\n  }\n}\n"
  },
  {
    "path": "packages/brief-sdk/src/brief.ts",
    "content": "/**\n * Brief Protocol — Brief Class\n *\n * Represents a parsed `.brief.md` document. Provides methods to inspect\n * the delegation request and create a corresponding response.\n */\n\nimport type {\n  BriefMeta,\n  CreateBriefOptions,\n  CreateResponseOptions,\n} from './types.js';\nimport { parseDocument, serializeDocument } from './parser.js';\nimport { validateBriefMeta } from './validator.js';\nimport { BriefResponse } from './response.js';\n\nexport class Brief {\n  /** The parsed YAML frontmatter metadata. */\n  readonly meta: BriefMeta;\n\n  /** The Markdown body containing task instructions. */\n  readonly body: string;\n\n  /** The full serialized `.brief.md` content. */\n  readonly content: string;\n\n  private constructor(meta: BriefMeta, body: string, content: string) {\n    this.meta = meta;\n    this.body = body;\n    this.content = content;\n  }\n\n  // ── Convenience Getters ─────────────────────────────────────────────\n\n  get id(): string {\n    return this.meta.id;\n  }\n\n  get delegator(): string {\n    return this.meta.delegator;\n  }\n\n  get delegatee(): string {\n    return this.meta.delegatee;\n  }\n\n  get parentId(): string | undefined {\n    return this.meta.parentId;\n  }\n\n  /** Returns `true` if this brief has a parentId (i.e. it is a sub-brief). */\n  get isSubBrief(): boolean {\n    return this.meta.parentId !== undefined;\n  }\n\n  /** Returns `true` if further sub-delegation is allowed based on depth limits. */\n  get canDelegate(): boolean {\n    if (this.meta.maxDepth === undefined) return true;\n    const depth = this.meta.currentDepth ?? 0;\n    return depth < this.meta.maxDepth;\n  }\n\n  // ── Static Factory: Parse ───────────────────────────────────────────\n\n  /**\n   * Parse a raw `.brief.md` string into a `Brief` instance.\n   *\n   * @param content - The raw Markdown content with YAML frontmatter.\n   * @returns A validated `Brief` instance.\n   * @throws {Error} If parsing or validation fails.\n   *\n   * @example\n   * ```ts\n   * const brief = Brief.parse(fs.readFileSync('task.brief.md', 'utf-8'));\n   * console.log(brief.id, brief.delegator);\n   * ```\n   */\n  static parse(content: string): Brief {\n    const { meta, body } = parseDocument<BriefMeta>(content);\n\n    const validation = validateBriefMeta(meta);\n    if (!validation.valid) {\n      throw new Error(\n        `Invalid Brief document:\\n  - ${validation.errors.join('\\n  - ')}`,\n      );\n    }\n\n    return new Brief(meta, body, content.trim());\n  }\n\n  // ── Instance Methods ────────────────────────────────────────────────\n\n  /**\n   * Create a `BriefResponse` for this brief.\n   *\n   * @example\n   * ```ts\n   * const response = brief.createResponse({\n   *   status: 'success',\n   *   body: '# Done\\n\\nTask completed successfully.',\n   * });\n   * ```\n   */\n  createResponse(options: CreateResponseOptions): BriefResponse {\n    return BriefResponse.create({\n      id: this.meta.id,\n      status: options.status,\n      body: options.body,\n    });\n  }\n\n  /**\n   * Create a sub-brief for cascading delegation.\n   *\n   * This method automatically sets the `parentId` to this brief's id\n   * and increments the `currentDepth`.\n   *\n   * @throws {Error} If the maximum delegation depth has been reached.\n   *\n   * @example\n   * ```ts\n   * const subBrief = parentBrief.createSubBrief({\n   *   delegator: 'agent-b',\n   *   delegatee: 'agent-c',\n   *   body: '# Sub-task\\n\\nPlease update the docs.',\n   * });\n   * ```\n   */\n  createSubBrief(options: Omit<CreateBriefOptions, 'parentId' | 'currentDepth'>): Brief {\n    if (!this.canDelegate) {\n      throw new Error(\n        `Cannot create sub-brief: maximum delegation depth (${this.meta.maxDepth}) reached.`,\n      );\n    }\n\n    const nextDepth = (this.meta.currentDepth ?? 0) + 1;\n\n    const subOptions: CreateBriefOptions = {\n      ...options,\n      parentId: this.meta.id,\n      maxDepth: this.meta.maxDepth,\n      currentDepth: nextDepth,\n    };\n\n    return Brief.create(subOptions);\n  }\n\n  // ── Static Factory: Create ──────────────────────────────────────────\n\n  /**\n   * Create a new `Brief` from options. This is the primary way to\n   * construct a brief programmatically.\n   *\n   * @example\n   * ```ts\n   * const brief = Brief.create({\n   *   delegator: 'agent-a',\n   *   delegatee: 'agent-b',\n   *   body: '# Task\\n\\nDo something useful.',\n   * });\n   *\n   * // brief.content is a valid .brief.md string\n   * ```\n   */\n  static create(options: CreateBriefOptions): Brief {\n    const id = options.id ?? generateId();\n    const meta: BriefMeta = {\n      id,\n      protocolVersion: options.protocolVersion ?? '1.2.0',\n      delegator: options.delegator,\n      delegatee: options.delegatee,\n      timestamp: new Date().toISOString(),\n      parentId: options.parentId,\n      maxDepth: options.maxDepth,\n      currentDepth: options.currentDepth ?? (options.parentId ? undefined : 0),\n    };\n\n    const content = serializeDocument(meta as unknown as Record<string, unknown>, options.body);\n\n    return new Brief(meta, options.body.trim(), content);\n  }\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────\n\n/** Generate a short random id prefixed with \"brief-\". */\nfunction generateId(): string {\n  const hex = Array.from({ length: 6 }, () =>\n    Math.floor(Math.random() * 16).toString(16),\n  ).join('');\n  return `brief-${hex}`;\n}\n"
  },
  {
    "path": "packages/brief-sdk/src/index.ts",
    "content": "/**\n * # brief-sdk\n *\n * TypeScript SDK for the **Brief** protocol — explicit agent delegation\n * made simple.\n *\n * Brief turns chaotic multi-agent handoffs into structured, auditable\n * task briefings using plain Markdown files.\n *\n * ## Quick Start\n *\n * ```ts\n * import { Brief, BriefResponse, Trace } from 'brief-sdk';\n *\n * // Create a delegation brief\n * const brief = Brief.create({\n *   delegator: 'agent-a',\n *   delegatee: 'agent-b',\n *   body: '# Task\\\\n\\\\nDo something useful.',\n * });\n *\n * // Parse a received brief\n * const incoming = Brief.parse(rawMarkdown);\n *\n * // Create a response\n * const response = incoming.createResponse({\n *   status: 'success',\n *   body: '# Done\\\\n\\\\nTask completed.',\n * });\n *\n * // Track the delegation chain\n * const trace = Trace.create();\n * trace.append({ agent: 'agent-a', action: 'Delegated task.' });\n * ```\n *\n * @packageDocumentation\n */\n\nexport { Brief } from './brief.js';\nexport { BriefResponse } from './response.js';\nexport { Trace } from './trace.js';\nexport { parseDocument, serializeDocument } from './parser.js';\nexport { validateBriefMeta, validateResponseMeta } from './validator.js';\n\nexport type {\n  BriefMeta,\n  BriefStatus,\n  ResponseMeta,\n  CreateBriefOptions,\n  CreateResponseOptions,\n  TraceEntry,\n  ValidationResult,\n} from './types.js';\n"
  },
  {
    "path": "packages/brief-sdk/src/parser.ts",
    "content": "/**\n * Brief Protocol — Markdown + YAML Frontmatter Parser\n *\n * Parses and serializes documents in the `.brief.md` / `.response.md` format:\n *\n * ```\n * ---\n * key: value\n * ---\n *\n * # Markdown body here\n * ```\n */\n\nimport YAML from 'yaml';\n\n/**\n * The result of parsing a Brief-protocol Markdown document.\n */\nexport interface ParsedDocument<T> {\n  /** Parsed YAML frontmatter as a typed object. */\n  meta: T;\n\n  /** The Markdown body (everything after the closing `---`). */\n  body: string;\n}\n\nconst FRONTMATTER_REGEX = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/;\n\n/**\n * Parse a Markdown string with YAML frontmatter into structured data.\n *\n * @param content - The raw Markdown string.\n * @returns A `ParsedDocument` with typed `meta` and string `body`.\n * @throws {Error} If the frontmatter delimiters are missing or YAML is invalid.\n */\nexport function parseDocument<T>(\n  content: string,\n): ParsedDocument<T> {\n  const trimmed = content.trim();\n  const match = FRONTMATTER_REGEX.exec(trimmed);\n\n  if (!match) {\n    throw new Error(\n      'Invalid Brief document: missing YAML frontmatter delimiters (---).',\n    );\n  }\n\n  const [, yamlStr, body] = match;\n\n  let meta: T;\n  try {\n    meta = YAML.parse(yamlStr) as T;\n  } catch (err) {\n    const message = err instanceof Error ? err.message : String(err);\n    throw new Error(`Invalid YAML frontmatter: ${message}`);\n  }\n\n  if (meta === null || typeof meta !== 'object') {\n    throw new Error('YAML frontmatter must be a mapping (object), not a scalar or array.');\n  }\n\n  return { meta, body: body.trim() };\n}\n\n/**\n * Serialize structured data back into a Markdown string with YAML frontmatter.\n *\n * @param meta - The metadata object to serialize as YAML frontmatter.\n * @param body - The Markdown body string.\n * @returns A complete Markdown document string.\n */\nexport function serializeDocument<T extends Record<string, unknown> = Record<string, unknown>>(\n  meta: T,\n  body: string,\n): string {\n  // Remove undefined values to keep the output clean\n  const cleanMeta = Object.fromEntries(\n    Object.entries(meta).filter(([, v]) => v !== undefined),\n  );\n\n  const yamlStr = YAML.stringify(cleanMeta).trim();\n  return `---\\n${yamlStr}\\n---\\n\\n${body.trim()}\\n`;\n}\n"
  },
  {
    "path": "packages/brief-sdk/src/response.ts",
    "content": "/**\n * Brief Protocol — BriefResponse Class\n *\n * Represents a parsed `.response.md` document. This is the counterpart\n * to a `Brief` — it contains the result of a delegated task.\n */\n\nimport type { BriefStatus, ResponseMeta } from './types.js';\nimport { parseDocument, serializeDocument } from './parser.js';\nimport { validateResponseMeta } from './validator.js';\n\n/**\n * Options for creating a new BriefResponse directly.\n */\nexport interface CreateResponseDirectOptions {\n  /** The id of the brief this response corresponds to. */\n  id: string;\n\n  /** Outcome status. */\n  status: BriefStatus;\n\n  /** Markdown body containing the response details. */\n  body: string;\n}\n\nexport class BriefResponse {\n  /** The parsed YAML frontmatter metadata. */\n  readonly meta: ResponseMeta;\n\n  /** The Markdown body containing the response details. */\n  readonly body: string;\n\n  /** The full serialized `.response.md` content. */\n  readonly content: string;\n\n  private constructor(meta: ResponseMeta, body: string, content: string) {\n    this.meta = meta;\n    this.body = body;\n    this.content = content;\n  }\n\n  // ── Convenience Getters ─────────────────────────────────────────────\n\n  get id(): string {\n    return this.meta.id;\n  }\n\n  get status(): BriefStatus {\n    return this.meta.status;\n  }\n\n  get isSuccess(): boolean {\n    return this.meta.status === 'success';\n  }\n\n  // ── Static Factory: Parse ───────────────────────────────────────────\n\n  /**\n   * Parse a raw `.response.md` string into a `BriefResponse` instance.\n   *\n   * @param content - The raw Markdown content with YAML frontmatter.\n   * @returns A validated `BriefResponse` instance.\n   * @throws {Error} If parsing or validation fails.\n   *\n   * @example\n   * ```ts\n   * const response = BriefResponse.parse(rawContent);\n   * if (response.isSuccess) {\n   *   console.log('Task completed:', response.body);\n   * }\n   * ```\n   */\n  static parse(content: string): BriefResponse {\n    const { meta, body } = parseDocument<ResponseMeta>(content);\n\n    const validation = validateResponseMeta(meta);\n    if (!validation.valid) {\n      throw new Error(\n        `Invalid Response document:\\n  - ${validation.errors.join('\\n  - ')}`,\n      );\n    }\n\n    return new BriefResponse(meta, body, content.trim());\n  }\n\n  // ── Static Factory: Create ──────────────────────────────────────────\n\n  /**\n   * Create a new `BriefResponse` from options.\n   *\n   * @example\n   * ```ts\n   * const response = BriefResponse.create({\n   *   id: 'brief-a4b1c8',\n   *   status: 'success',\n   *   body: '# Done\\n\\nAll tasks completed.',\n   * });\n   * ```\n   */\n  static create(options: CreateResponseDirectOptions): BriefResponse {\n    const meta: ResponseMeta = {\n      id: options.id,\n      status: options.status,\n      timestamp: new Date().toISOString(),\n    };\n\n    const content = serializeDocument(\n      meta as unknown as Record<string, unknown>,\n      options.body,\n    );\n\n    return new BriefResponse(meta, options.body.trim(), content);\n  }\n}\n"
  },
  {
    "path": "packages/brief-sdk/src/trace.ts",
    "content": "/**\n * Brief Protocol — Trace Module\n *\n * The Trace is a separate, append-only log that travels with a delegation\n * chain. It provides a complete, chronological audit trail of every action\n * taken by every agent in the cascade.\n *\n * Format (Markdown):\n * ```\n * - **Agent**: `agent-id` @ `2026-02-06T03:50:00Z`\n *   - **Action**: Description of what happened.\n *   - **Brief**: `brief-abc123`\n * ```\n */\n\nimport type { TraceEntry } from './types.js';\n\nexport class Trace {\n  private entries: TraceEntry[] = [];\n\n  private constructor(entries: TraceEntry[] = []) {\n    this.entries = [...entries];\n  }\n\n  // ── Static Factories ────────────────────────────────────────────────\n\n  /** Create a new, empty trace. */\n  static create(): Trace {\n    return new Trace();\n  }\n\n  /**\n   * Parse a `trace.md` string back into a Trace instance.\n   *\n   * @example\n   * ```ts\n   * const trace = Trace.parse(fs.readFileSync('trace.md', 'utf-8'));\n   * console.log(trace.getEntries());\n   * ```\n   */\n  static parse(content: string): Trace {\n    const entries: TraceEntry[] = [];\n    const lines = content.split('\\n');\n\n    let current: Partial<TraceEntry> | null = null;\n\n    for (const line of lines) {\n      // Match: - **Agent**: `agent-id` @ `timestamp`\n      const agentMatch = line.match(\n        /^- \\*\\*Agent\\*\\*:\\s*`([^`]+)`\\s*@\\s*`([^`]+)`/,\n      );\n      if (agentMatch) {\n        if (current && current.agent && current.timestamp && current.action) {\n          entries.push(current as TraceEntry);\n        }\n        current = {\n          agent: agentMatch[1],\n          timestamp: agentMatch[2],\n        };\n        continue;\n      }\n\n      if (!current) continue;\n\n      // Match:   - **Action**: description\n      const actionMatch = line.match(/^\\s+- \\*\\*Action\\*\\*:\\s*(.+)/);\n      if (actionMatch) {\n        current.action = actionMatch[1].trim();\n        continue;\n      }\n\n      // Match:   - **Brief**: `brief-id`\n      const briefMatch = line.match(/^\\s+- \\*\\*Brief\\*\\*:\\s*`([^`]+)`/);\n      if (briefMatch) {\n        current.briefId = briefMatch[1];\n        continue;\n      }\n    }\n\n    // Push the last entry\n    if (current && current.agent && current.timestamp && current.action) {\n      entries.push(current as TraceEntry);\n    }\n\n    return new Trace(entries);\n  }\n\n  // ── Instance Methods ────────────────────────────────────────────────\n\n  /**\n   * Append a new entry to the trace.\n   *\n   * @example\n   * ```ts\n   * trace.append({\n   *   agent: 'agent-orchestrator',\n   *   action: 'Delegating code review task.',\n   *   briefId: 'brief-abc123',\n   * });\n   * ```\n   */\n  append(entry: Omit<TraceEntry, 'timestamp'> & { timestamp?: string }): this {\n    this.entries.push({\n      ...entry,\n      timestamp: entry.timestamp ?? new Date().toISOString(),\n    });\n    return this;\n  }\n\n  /** Get all trace entries as a readonly array. */\n  getEntries(): readonly TraceEntry[] {\n    return [...this.entries];\n  }\n\n  /** Get the number of entries in the trace. */\n  get length(): number {\n    return this.entries.length;\n  }\n\n  /**\n   * Create a deep copy of this trace. Used when passing the trace\n   * down to a sub-agent in a cascading delegation.\n   */\n  clone(): Trace {\n    return new Trace(this.entries.map((e) => ({ ...e })));\n  }\n\n  /**\n   * Merge another trace into this one. Only entries that are not already\n   * present (by agent+timestamp+action identity) are added.\n   * Used for fan-in scenarios where cloned traces share a common prefix.\n   */\n  merge(other: Trace): this {\n    const existingKeys = new Set(\n      this.entries.map((e) => `${e.agent}|${e.timestamp}|${e.action}`),\n    );\n    for (const entry of other.getEntries()) {\n      const key = `${entry.agent}|${entry.timestamp}|${entry.action}`;\n      if (!existingKeys.has(key)) {\n        this.entries.push(entry);\n        existingKeys.add(key);\n      }\n    }\n    // Sort by timestamp to maintain chronological order\n    this.entries.sort(\n      (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),\n    );\n    return this;\n  }\n\n  // ── Serialization ───────────────────────────────────────────────────\n\n  /**\n   * Serialize the trace to a `trace.md` formatted string.\n   *\n   * @example\n   * ```ts\n   * fs.writeFileSync('trace.md', trace.toString());\n   * ```\n   */\n  toString(): string {\n    if (this.entries.length === 0) return '';\n\n    return this.entries\n      .map((entry) => {\n        let line = `- **Agent**: \\`${entry.agent}\\` @ \\`${entry.timestamp}\\`\\n`;\n        line += `  - **Action**: ${entry.action}`;\n        if (entry.briefId) {\n          line += `\\n  - **Brief**: \\`${entry.briefId}\\``;\n        }\n        return line;\n      })\n      .join('\\n');\n  }\n}\n"
  },
  {
    "path": "packages/brief-sdk/src/types.ts",
    "content": "/**\n * Brief Protocol — Type Definitions\n *\n * These types define the core data structures of the Brief protocol.\n * A Brief is a Markdown document with YAML frontmatter that represents\n * an explicit delegation from one agent to another.\n */\n\n// ---------------------------------------------------------------------------\n// Brief (Request) Types\n// ---------------------------------------------------------------------------\n\n/**\n * Metadata fields stored in the YAML frontmatter of a `.brief.md` file.\n */\nexport interface BriefMeta {\n  /** Unique identifier for this brief. Auto-generated if not provided. */\n  id: string;\n\n  /** Protocol version string, e.g. \"1.2.0\". */\n  protocolVersion: string;\n\n  /** Identifier of the agent issuing the delegation. */\n  delegator: string;\n\n  /** Identifier (or capability query) of the target agent. */\n  delegatee: string;\n\n  /** ISO-8601 timestamp of when the brief was created. */\n  timestamp: string;\n\n  /**\n   * Optional. Links this brief to a parent brief, forming a cascade chain.\n   * A brief without a parentId is a **root brief**.\n   */\n  parentId?: string;\n\n  /**\n   * Optional. Maximum allowed delegation depth from the root brief.\n   * Used to prevent infinite recursion in cascading scenarios.\n   */\n  maxDepth?: number;\n\n  /**\n   * Optional. Current depth in the delegation chain.\n   * Automatically incremented when creating sub-briefs.\n   */\n  currentDepth?: number;\n}\n\n/**\n * Options for creating a new Brief via BriefFactory.\n * Only `delegator`, `delegatee`, and `body` are required.\n */\nexport interface CreateBriefOptions {\n  /** Identifier of the delegating agent. */\n  delegator: string;\n\n  /** Identifier or capability of the target agent. */\n  delegatee: string;\n\n  /** Markdown body containing the task instructions. */\n  body: string;\n\n  /** Optional. Custom id. Auto-generated if omitted. */\n  id?: string;\n\n  /** Optional. Protocol version. Defaults to \"1.2.0\". */\n  protocolVersion?: string;\n\n  /** Optional. Parent brief id for cascading. */\n  parentId?: string;\n\n  /** Optional. Maximum delegation depth. */\n  maxDepth?: number;\n\n  /** Optional. Current depth. Defaults to 0 for root briefs. */\n  currentDepth?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Response Types\n// ---------------------------------------------------------------------------\n\n/** Possible statuses for a brief response. */\nexport type BriefStatus = 'success' | 'failure' | 'partial' | 'rejected';\n\n/**\n * Metadata fields stored in the YAML frontmatter of a `.response.md` file.\n */\nexport interface ResponseMeta {\n  /** The id of the brief this response corresponds to. */\n  id: string;\n\n  /** Outcome status of the delegated task. */\n  status: BriefStatus;\n\n  /** ISO-8601 timestamp of when the response was created. */\n  timestamp: string;\n}\n\n/**\n * Options for creating a response to an existing Brief.\n */\nexport interface CreateResponseOptions {\n  /** Outcome status. */\n  status: BriefStatus;\n\n  /** Markdown body containing the response details. */\n  body: string;\n}\n\n// ---------------------------------------------------------------------------\n// Trace Types\n// ---------------------------------------------------------------------------\n\n/**\n * A single entry in the trace log.\n */\nexport interface TraceEntry {\n  /** Identifier of the agent performing the action. */\n  agent: string;\n\n  /** ISO-8601 timestamp. */\n  timestamp: string;\n\n  /** Human-readable description of the action taken. */\n  action: string;\n\n  /** Optional. The brief id associated with this action. */\n  briefId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Validation Types\n// ---------------------------------------------------------------------------\n\n/**\n * Result of a validation operation.\n */\nexport interface ValidationResult {\n  /** Whether the document is valid. */\n  valid: boolean;\n\n  /** List of validation error messages, if any. */\n  errors: string[];\n}\n"
  },
  {
    "path": "packages/brief-sdk/src/validator.ts",
    "content": "/**\n * Brief Protocol — Validators\n *\n * Validates the structure and content of Brief and Response metadata.\n */\n\nimport type { BriefMeta, ResponseMeta, ValidationResult } from './types.js';\n\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\nconst SEMVER_REGEX = /^\\d+\\.\\d+\\.\\d+/;\n\n/**\n * Validate Brief metadata fields.\n */\nexport function validateBriefMeta(meta: Partial<BriefMeta>): ValidationResult {\n  const errors: string[] = [];\n\n  if (!meta.id || typeof meta.id !== 'string') {\n    errors.push('Missing or invalid \"id\": must be a non-empty string.');\n  }\n\n  if (!meta.protocolVersion || !SEMVER_REGEX.test(meta.protocolVersion)) {\n    errors.push(\n      'Missing or invalid \"protocolVersion\": must be a semver string (e.g. \"1.2.0\").',\n    );\n  }\n\n  if (!meta.delegator || typeof meta.delegator !== 'string') {\n    errors.push('Missing or invalid \"delegator\": must be a non-empty string.');\n  }\n\n  if (!meta.delegatee || typeof meta.delegatee !== 'string') {\n    errors.push('Missing or invalid \"delegatee\": must be a non-empty string.');\n  }\n\n  if (!meta.timestamp || !ISO_DATE_REGEX.test(meta.timestamp)) {\n    errors.push(\n      'Missing or invalid \"timestamp\": must be an ISO-8601 date string.',\n    );\n  }\n\n  if (meta.maxDepth !== undefined && (typeof meta.maxDepth !== 'number' || meta.maxDepth < 1)) {\n    errors.push('\"maxDepth\" must be a positive integer.');\n  }\n\n  if (meta.currentDepth !== undefined && typeof meta.currentDepth !== 'number') {\n    errors.push('\"currentDepth\" must be a number.');\n  }\n\n  if (\n    meta.maxDepth !== undefined &&\n    meta.currentDepth !== undefined &&\n    meta.currentDepth > meta.maxDepth\n  ) {\n    errors.push(\n      `\"currentDepth\" (${meta.currentDepth}) exceeds \"maxDepth\" (${meta.maxDepth}).`,\n    );\n  }\n\n  return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate Response metadata fields.\n */\nexport function validateResponseMeta(meta: Partial<ResponseMeta>): ValidationResult {\n  const errors: string[] = [];\n\n  if (!meta.id || typeof meta.id !== 'string') {\n    errors.push('Missing or invalid \"id\": must be a non-empty string.');\n  }\n\n  const validStatuses = ['success', 'failure', 'partial', 'rejected'];\n  if (!meta.status || !validStatuses.includes(meta.status)) {\n    errors.push(\n      `Missing or invalid \"status\": must be one of ${validStatuses.join(', ')}.`,\n    );\n  }\n\n  if (!meta.timestamp || !ISO_DATE_REGEX.test(meta.timestamp)) {\n    errors.push(\n      'Missing or invalid \"timestamp\": must be an ISO-8601 date string.',\n    );\n  }\n\n  return { valid: errors.length === 0, errors };\n}\n"
  },
  {
    "path": "packages/brief-sdk/tsconfig.json",
    "content": "{\n  \"extends\": \"../../tsconfig.json\",\n  \"compilerOptions\": {\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\"\n  },\n  \"include\": [\"src/**/*.ts\"],\n  \"exclude\": [\"__tests__\", \"dist\"]\n}\n"
  },
  {
    "path": "packages/brief-sdk/vitest.config.ts",
    "content": "import { defineConfig } from 'vitest/config';\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    include: ['__tests__/**/*.test.ts'],\n  },\n});\n"
  },
  {
    "path": "pnpm-workspace.yaml",
    "content": "packages:\n  - \"packages/*\"\n  - \"examples/*\"\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"sourceMap\": true,\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true\n  }\n}\n"
  }
]