# Brainfile Protocol - Complete Reference for AI Agents > Comprehensive documentation for AI agents integrating with Brainfile > Auto-generated from markdown documentation Version: 2.0 Schema: https://brainfile.md/v2 Last Updated: 2026-03-02 --- ## Table of Contents 1. Quick Start Guide 2. Why Brainfile? 3. Getting Started with Contracts 4. Comprehensive Guide to Contracts 5. Agent Workflow Patterns 6. CLI & Terminal UI 7. MCP Server Integration 8. Pi Extension Integration 9. Core Library 10. Protocol Specification 11. API Reference 12. CLI Commands Reference 13. Contract Schema Reference 14. Schema Types 15. Complete Example --- ## 1. Quick Start Guide Quick Start ::: tip Bootstrap with an Agent Paste this URL into any agent chat and tell it to set up brainfile: `` https://brainfile.md/llms-install.txt ` The agent gets install commands, MCP config, CLI reference, and the contract workflow in one document. ::: Get a task board in your project in under a minute. Install ` npm install -g @brainfile/cli ` Initialize ` brainfile init ` This creates the .brainfile/ directory with: - .brainfile/brainfile.md — Board configuration (columns, types, rules) - .brainfile/board/ — Active task files - .brainfile/logs/ — Completion history (ledger.jsonl) and archives .brainfile/ ├── brainfile.md ← Board config (columns, types, rules) ├── board/ ← Active task files go here └── logs/ ← Completed history (ledger and archived files) Default columns are To Do and In Progress. Use It ::: tip Interactive TUI ` brainfile # No arguments launches the TUI brainfile tui # Explicit subcommand also works ` Navigate with keyboard: TAB for columns, j/k for tasks, Enter to expand, q to quit. ::: ::: tip CLI Commands ` brainfile list # See all tasks brainfile add --title "My first task" # Add a task brainfile move --task task-1 --column in-progress # Move columns brainfile complete --task task-1 # Complete (appends to ledger.jsonl and archives) ` ::: --- Add AI Integration Want your AI assistant to manage tasks directly? Add this to .mcp.json in your project: ` { "mcpServers": { "brainfile": { "command": "npx", "args": ["@brainfile/cli", "mcp"] } } } ` Works with Claude Code, Cursor, Cline, and any MCP-compatible tool. ::: tip What can AI do with this? Your assistant can now list tasks, create new ones, move them between columns, update priorities, and manage subtasks — all without you copy-pasting anything. ::: --- Agent Coordination (Optional) Brainfile allows you to create Contracts for your AI assistants. A contract defines exactly what an agent needs to deliver. Create a task with a contract ` brainfile add --title "Create API docs" \ --with-contract \ --deliverable "docs/api.md" \ --validation "npm run docs:build" ` How agents use it When an AI agent (like Claude or Cursor) picks up this task, it will see the structured deliverables and validation commands. This ensures the agent produces exactly what you need. ` sequenceDiagram participant PM as PM Agent participant Board as .brainfile/ participant Worker as Worker Agent PM->>Board: brainfile add --with-contract Worker->>Board: brainfile contract pickup Worker->>Worker: Implement deliverables Worker->>Board: brainfile contract deliver PM->>Board: brainfile contract validate Board-->>PM: ✓ done `` --- Next Steps - Why Brainfile? — The philosophy behind file-based coordination - Getting Started with Contracts — Define deliverables for AI agents - CLI Commands — Full command reference and TUI guide - MCP Integration — Connect your AI assistant directly - Protocol Specification — File format and schema details --- ## 2. Why Brainfile? The Agentic Coordination Manifesto The Context Gap AI agents are remarkably capable at implementation, but they operate in a void of coordination. While they can read your code, they cannot see your intent, your priorities, or your acceptance criteria unless you manually translate them from external tools (Jira, Linear, Notion) into every prompt. This creates an integration tax on the human: copying requirements, updating statuses, and manually verifying that the agent stayed within scope. Brainfile is the solution to the context gap. --- Principles of Coordination ::: info 1. Protocol over Platform Coordination should be an open standard, not a closed SaaS feature. By defining coordination as a file-system protocol, we enable any agent and any tool to participate without a central API or vendor lock-in. ::: ::: info 2. Context Locality The source of truth for work should live where the work happens: in the repository. When tasks and contracts are files in the codebase, they are naturally indexed by the agent alongside the source code, providing immediate, high-fidelity context. ::: ::: info 3. File-System Semantics Complex state management is replaced by simple file operations. Appending a record to logs/ledger.jsonl and archiving the task file is an immutable, searchable, and version-controlled record of completion. This simplicity is the key to scalability and resilience. ::: ::: info 4. Explicit Contracts Informal "please do X" requests are replaced by structured agreements. A contract defines exactly what constitutes success (deliverables) and how it will be measured (validation). This formalization reduces agent hallucination and ensures human-aligned outcomes. ::: ::: info 5. Architectural Memory Decisions made today should automatically guide the work of tomorrow. By promoting ADRs to project rules, the protocol ensures that every agent interaction is grounded in the project's established architectural standards. ::: --- The Infrastructure Advantage ::: tip What You Gain By adopting a file-based coordination protocol, you gain: - Bespoke Diffs: See exactly how requirements changed over time in your git history. - Offline Reliability: Your task board works on a plane, in a basement, or during a platform outage. - Zero Latency: No API round-trips to fetch task context. - Agent Interoperability: Use the same board with Claude, GitHub Copilot, Cursor, or your own custom agents. ::: --- Join the Ecosystem Brainfile is more than a tool; it's a way of thinking about how humans and machines build software together. - Read the Specification — The complete file format and YAML structure reference - Explore the CLI — Install in 30 seconds and start managing tasks from your terminal - Integrate the Core Library — Build custom tooling with @brainfile/core - Set Up MCP — Give your AI assistant direct access to your task board - Contract Guide — Learn how agents coordinate through structured agreements --- ## 3. Getting Started with Contracts Getting Started with Contracts Brainfile isn't just for human-to-human task management. Its most powerful feature is Agent Coordination: the ability for one AI assistant (acting as a PM) to assign structured work to another AI assistant (the worker). What are Contracts? A Contract is an optional set of rules attached to a task. It defines exactly what needs to be done, how it will be verified, and what constraints must be followed. When an AI agent sees a task with a contract, it doesn't just "try its best"—it follows a formal lifecycle to ensure the work meets your specifications. Why use them? - Reliability: Agents know exactly what deliverables are expected. - Automation: Validation commands can automatically check work before it's marked "Done". - Delegation: You (or your primary AI assistant) can delegate complex sub-tasks to other specialized agents with high confidence. A Simple Example Imagine you want an agent to create a new React component. Instead of a vague task, you create a contract: `` --- id: task-101 title: "Create UserProfile component" contract: status: ready deliverables: - type: file path: src/components/UserProfile.tsx description: Main component file - type: test path: src/components/UserProfile.test.tsx validation: commands: - npm test src/components/UserProfile.test.tsx constraints: - Use Tailwind CSS for styling - Must be a functional component --- ` The Coordination Lifecycle Ready (ready): The contract is defined and available for a worker agent to pick up. In Progress (in_progress): A worker agent has claimed the task and started work. Delivered (delivered): The worker has finished and is waiting for PM validation. Done (done): The work has been validated and accepted. Failed (failed): Validation failed — feedback is provided for rework. Blocked (blocked): The agent is stuck on an external dependency and needs PM help. Try it now You can add a contract to any task using the CLI: ` brainfile add --title "Refactor Auth" \ --with-contract \ --deliverable "file:src/auth.ts:Auth refactor" \ --validation "npm test" `` Next, learn about Complex Agent Workflows or see the full Contract Schema Reference. --- ## 4. Comprehensive Guide to Contracts Agent-to-Agent Contracts The Brainfile contract system provides a structured way for AI agents to coordinate work. It moves beyond simple task assignments by defining clear deliverables, implementation constraints, and validation procedures. Core Principles Agent-First Design: Optimized for the unique needs of AI-to-AI coordination. Explicit Expectations: Contracts define exactly what must be produced (deliverables) and how it will be verified (validation). Autonomous Execution: Once a contract is picked up, the worker agent has the autonomy to complete the task within the defined constraints. Trust + Verify: PM agents validate the results against the contract before closing the task. Single Source of Truth: Contracts are embedded directly in the brainfile.md task, keeping context and status in one place. The Contract Schema A contract is an optional property of a task. When present, it formalizes the "handshake" between agents. Task metadata: `` --- id: task-101 title: Implement rate limiter description: | Implement token bucket rate limiting to prevent API quota exhaustion. assignee: codex relatedFiles: - src/api/middleware.ts ` ::: info Task fields provide context The description and relatedFiles are the single source of truth for the agent. Write clear, specific requirements here — this is what the worker agent reads first to understand the job. ::: Contract definition: ` contract: status: ready deliverables: - type: file path: src/rateLimiter.ts description: Token bucket implementation - type: test path: src/__tests__/rateLimiter.test.ts description: Unit tests ` ::: tip Deliverables define "done" Each deliverable specifies an exact file path. The agent knows exactly what to produce, and the PM knows exactly what to check. ::: Validation rules: ` validation: commands: - "npm test -- rateLimiter" ` ::: tip Automated verification Validation commands run sequentially during contract validate. If any command exits non-zero, the contract is marked failed and the output is captured as feedback. ::: Implementation constraints: ` constraints: - "Use token bucket algorithm" - "Must be non-blocking (async)" --- ` ::: info Constraints guide, not restrict Keep constraints focused — 3–5 key requirements, not an exhaustive spec. The agent has autonomy within these guardrails. ::: Key Fields - status: The current state of the contract (ready, in_progress, delivered, done, failed, blocked). - deliverables: A list of specific files or artifacts the agent must produce. - validation.commands: Optional shell commands that the PM can run to automatically verify the work. - constraints: Guidelines or rules the agent must follow during implementation. - outOfScope: Explicitly defines what the agent should not do. - feedback: Used by the PM to provide guidance if a contract is rejected (status failed). --- Contract Lifecycle The lifecycle ensures that work is properly claimed, implemented, and verified. | State | Meaning | Next Action | |-------|---------|-------------| | 🔵 ready | Contract is available for an agent to claim. | Agent: contract pickup | | 🟡 in_progress | Agent is currently working on the deliverables. | Agent: contract deliver | | 🟣 delivered | Work is complete and awaiting PM review. | PM: contract validate | | 🟢 done | PM has verified and accepted the work. | PM: brainfile complete to append to ledger.jsonl and archive. | | 🔴 failed | Validation failed. Feedback is provided. | PM: Add feedback, reset to ready for rework. | | ⚠️ blocked | Agent is stuck and needs human/PM intervention. | PM: Resolve blocker and reset status to ready. Either party can set this status via manual YAML edit; there is no dedicated CLI command for it. | --- Working with Contracts Creating Contracts Contracts can be created alongside a task or attached to an existing one. ` Create task with contract brainfile add --with-contract --deliverable "file:src/auth.ts:Implementation" --validation "npm test" Attach contract to existing task brainfile contract attach -t task-42 --deliverable "docs:docs/api.md:API documentation" ` For Worker Agents Worker agents follow a claim-implement-deliver workflow: List: Find assigned contracts with brainfile list --contract ready. Pickup: Claim the task with brainfile contract pickup -t task-X. Implement: Follow the instructions in description and contract.constraints. Self-Verify: Run validation.commands manually to ensure quality. Deliver: Submit the work with brainfile contract deliver -t task-X. For PM Agents PM agents (usually humans or advanced LLMs) manage the lifecycle: Define: Create tasks with clear contracts. Assign: Set the assignee to the appropriate worker agent. Validate: Once delivered, run brainfile contract validate -t task-X. Result: - If successful: Status becomes done. Run brainfile complete to append to ledger.jsonl and archive. - If issues found: Status becomes failed. Edit task to add feedback and reset status to ready. ::: tip Quick Reference | Action | Command | |--------|---------| | Create with contract | brainfile add --with-contract --deliverable "file:path" --validation "cmd" | | Attach to existing | brainfile contract attach -t task-42 --deliverable "path" | | Pick up | brainfile contract pickup -t task-X | | Deliver | brainfile contract deliver -t task-X | | Validate | brainfile contract validate -t task-X | ::: State Tracking Contract metrics are tracked directly within the contract object in each task file: Metrics and Performance The system automatically tracks metrics to help evaluate agent performance and task complexity: - Timestamps: Records when work was picked up, delivered, and validated. - Duration: Calculates the total time spent in the in_progress state. - Rework Count: Tracks how many times a contract was rejected and re-picked up. These metrics are stored within the contract object in your brainfile.md`. --- Benefits of the System - Reduces Ambiguity: "Done" is clearly defined by deliverables and validation commands. - Enables Parallelism: Multiple agents can work on different contracts simultaneously without overlapping. - Automated Verification: Integration tests can be part of the contract, ensuring that agents don't break existing functionality. - Traceability: Each state transition is tracked, providing a clear history of how a feature was implemented. Related Pages - Agent Workflows — PM and worker coordination patterns - Contract Commands — Full CLI reference for contract operations - Contract Schema — Formal field-by-field specification - Getting Started — 2-minute intro --- ## 5. Agent Workflow Patterns Agent Workflow Patterns The contract system enables powerful coordination patterns between different types of agents. This guide outlines the standard roles and workflows for efficient project management. Roles ::: info PM Agent (Project Manager) The PM agent is responsible for the "What" and "Why". They break down high-level goals into actionable tasks, define contracts, and verify results. - Primary tools: add, patch, contract attach, contract validate. - Key responsibility: Ensure task descriptions are comprehensive and validation criteria are objective. ::: ::: info Worker Agent (The Doer) Worker agents (like codex, cursor, gemini) focus on the "How". They pick up contracts, implement code, and deliver artifacts. - Primary tools: list, contract pickup, contract deliver, show. - Key responsibility: Meet the deliverables and constraints defined in the contract. ::: --- The Standard Loop A typical feature implementation follows this cycle: `` sequenceDiagram participant PM participant Board as .brainfile/ participant Worker PM->>Board: Create task + contract Worker->>Board: contract pickup Worker->>Worker: Implement Worker->>Board: contract deliver PM->>Board: contract validate Board-->>PM: ✓ done ` Planning (PM) The PM agent analyzes the requirement and creates a task with a contract. ` brainfile add --title "Add OAuth2 Support" \ --description "Implement Google OAuth2 login flow. See design docs for details." \ --assignee codex \ --with-contract \ --deliverable "file:src/auth/oauth.ts:Implementation" \ --deliverable "test:src/auth/__tests__/oauth.test.ts:Tests" \ --validation "npm test -- oauth" \ --constraint "Use official google-auth-library" ` Execution (Worker) The worker agent detects the assignment and begins work. ` Worker checks for new tasks brainfile list --contract ready --assignee codex Worker claims the task brainfile contract pickup -t task-105 Worker reads full details brainfile show -t task-105 Worker implements code... Worker self-verifies npm test -- oauth Worker delivers brainfile contract deliver -t task-105 ` Verification (PM) The PM agent reviews the work and completes the task. ` PM sees delivered tasks brainfile list --contract delivered PM runs automated validation brainfile contract validate -t task-105 If all good, PM completes the task (appends to ledger.jsonl and archives) brainfile complete -t task-105 ` --- Handling Rework If the PM agent finds issues during validation or manual review, the rework flow is triggered. ` sequenceDiagram participant PM participant Board as .brainfile/ participant Worker PM->>Board: contract validate Board-->>PM: ✗ failed PM->>Board: Add feedback, reset to ready Worker->>Board: contract pickup (rework) Worker->>Worker: Fix issues Worker->>Board: contract deliver PM->>Board: contract validate Board-->>PM: ✓ done ` Validation Fails: brainfile contract validate fails — status becomes failed, feedback is added automatically. PM Adds Guidance: PM edits the task file to add or update contract.feedback with specific rework instructions. PM Resets Status: PM edits contract.status back to ready for rework. Worker Re-pickup: The worker sees the ready status, reads the feedback field via brainfile show, and runs contract pickup again. Fix & Re-deliver: Worker fixes the issue and runs contract deliver. --- Blocked Agents Sometimes a worker agent cannot proceed due to external factors (missing API keys, ambiguous requirements, upstream bugs). Agent Reports Blocked: The agent edits the task file to set contract.status to blocked and adds a note to the task log explaining the blocker. (Either the agent or PM can set this status via manual YAML edit; there is no dedicated CLI command for it.) PM Notification: The PM sees the blocked status in the TUI or via brainfile list. Resolution: The PM provides the missing info or fixes the dependency. Reset: The PM edits contract.status back to ready or in_progress. --- Advanced Patterns The Multi-Agent Pipeline Break a large feature into a sequence of contracts: Agent A (Architect): Produces an interface specification (docs/api.md). Agent B (Backend): Implements the API based on the spec. Agent C (Frontend): Consumes the API based on the spec. Automated Triage A specialized triage agent can monitor incoming bug reports (tasks without contracts), research the cause, and then attach a contract with specific relatedFiles and validation commands for a codex` agent to fix. Self-Referential Tasks Brainfile can manage its own development. Use contracts to coordinate work on the protocol itself — the same task board that tracks your features can track improvements to the coordination layer. --- ## 6. CLI & Terminal UI CLI & Terminal UI The Brainfile CLI gives you full control over your task board from the terminal. Use the interactive TUI for a visual experience, or run commands for automation. Installation `` npm install -g @brainfile/cli ` Verify installation: ` brainfile --version ` Core Features - Interactive TUI: A full-featured terminal kanban board. - Agent Coordination: Built-in support for Agent Contracts to coordinate work between AI assistants. - Rich Task Metadata: Support for priorities, tags, assignees, due dates, and subtasks. - Task Archival: Complete and archive tasks to searchable logs. --- Interactive TUI Launch an interactive kanban board in your terminal: ` brainfile ` Or open a specific file: ` brainfile ./path/to/brainfile.md ` TUI Layout The interactive board displays your columns side by side, with tasks flowing through your workflow:
To Do task-1, task-2 In Progress task-3 Done task-4
Keyboard Controls ::: tip Keyboard Quick Reference | Key | Action | |-----|--------| | TAB / Shift+TAB | Navigate between columns | | j / k or ↑ / ↓ | Navigate tasks | | Enter | Expand/collapse task details | | / | Search tasks | | ? | Show help | | r | Refresh | | q | Quit | ::: ::: info Real-time sync The TUI watches your file for changes — edits from your editor or AI assistants appear instantly. ::: --- Common Commands Initialize a New Board ` brainfile init ` Creates .brainfile/ directory with brainfile.md config, board/, and logs/ (completion history). Default columns: To Do and In Progress. List Tasks ` brainfile list # All tasks brainfile list --column todo # Filter by column brainfile list --tag bug # Filter by tag ` Add Tasks ` brainfile add --title "Implement auth" brainfile add --title "Fix bug" --priority high --tags "bug,urgent" brainfile add --title "Review PR" --assignee john --due-date 2025-02-01 ` Move Tasks ` brainfile move --task task-1 --column in-progress ` Complete Tasks ` brainfile complete --task task-1 # Appends to ledger.jsonl and archives ` Update Tasks ` brainfile patch --task task-1 --priority critical brainfile patch --task task-1 --title "New title" --tags "new,tags" brainfile patch --task task-1 --clear-assignee # Remove assignee ` Manage Subtasks ` brainfile subtask --task task-1 --add "Write tests" brainfile subtask --task task-1 --toggle task-1-1 brainfile subtask --task task-1 --delete task-1-2 ` --- Agent Contracts ::: info Agent-to-Agent Coordination The CLI facilitates structured coordination between agents through the contract system. Contracts define deliverables, validation commands, and constraints — enabling autonomous agent work with automated verification. Create Task with Contract ` brainfile add --title "Implement API" \ --with-contract \ --deliverable "src/api.ts" \ --validation "npm test" ` Worker Agent Lifecycle Pickup: brainfile contract pickup -t task-1 Deliver: brainfile contract deliver -t task-1 PM Agent Lifecycle Validate: brainfile contract validate -t task-1 (auto-checks deliverables and runs commands) Complete: brainfile complete -t task-1 (after validation passes) See the Agent Contracts Guide for the full lifecycle and best practices. ::: --- Archive & Restore ` Archive a task brainfile archive --task task-5 Restore from archive brainfile restore --task task-5 --column todo ` Validate ` brainfile lint # Check for issues brainfile lint --fix # Auto-fix issues brainfile lint --check # Exit with error code (for CI) ` --- Templates Create tasks from built-in templates: ` brainfile template --list brainfile template --use bug-report --title "Login fails on mobile" brainfile template --use feature-request --title "Add dark mode" ` Available templates: - bug-report — Bug tracking with triage subtasks - feature-request — Feature proposals - refactor — Code refactoring tasks --- Shell Aliases ::: tip Speed up your workflow Add these to your .bashrc or .zshrc: ::: ` alias bf="brainfile" alias bfl="brainfile list" alias bfa="brainfile add" alias bfm="brainfile move" ` --- Next Steps - Full Command Reference — Complete documentation for every command, option, and flag - MCP Server — Expose Brainfile as an MCP server for AI assistant integration - Agent Contracts Guide — Deep dive into the contract lifecycle and PM/worker coordination - CI/CD Examples — GitHub Actions, pre-commit hooks, and npm script automation - Core Library — Use @brainfile/core` programmatically in your own tools --- ## 7. MCP Server Integration MCP Server The Brainfile CLI includes a built-in MCP (Model Context Protocol) server. This lets AI assistants like Claude Code, Cursor, and Cline manage your tasks directly — no copy-paste, no manual updates. Why MCP? ::: info The Before & After Without MCP, your AI assistant can read your code but doesn't know what you're working on. You have to: - Explain the current task every conversation - Copy task descriptions into prompts - Manually update task status after work is done With MCP, your assistant: - Sees all your tasks and their status - Creates new tasks as work is identified - Moves tasks to "done" when complete - Updates priorities and metadata automatically It's the difference between "update my task board" and just having it happen. ::: --- Setup ::: tip Basic Setup Add to .mcp.json in your project root: `` { "mcpServers": { "brainfile": { "command": "npx", "args": ["@brainfile/cli", "mcp"] } } } ` ::: ::: tip Custom Path Setup For a specific brainfile path: ` { "mcpServers": { "brainfile": { "command": "npx", "args": ["@brainfile/cli", "mcp", "-f", "path/to/brainfile.md"] } } } ` ::: ::: warning Restart your AI assistant after adding or changing MCP configuration. ::: --- Available Tools Your AI assistant gets access to these operations: Task Management | Tool | Description | |------|-------------| | list_tasks | List all tasks, filter by column, tag, type, or contract status | | get_task | Get detailed information about a specific task | | search_tasks | Search tasks by query, column, priority, assignee | | add_task | Create a task with title, priority, tags, type, relatedFiles, etc. | | move_task | Move a task between columns | | patch_task | Update specific fields on a task | | delete_task | Permanently delete a task | | complete_task | Complete a task (append to ledger.jsonl and archive) | Bulk Operations | Tool | Description | |------|-------------| | bulk_move_tasks | Move multiple tasks to a column in one operation | | bulk_patch_tasks | Apply same patch to multiple tasks | | bulk_delete_tasks | Delete multiple tasks | | bulk_archive_tasks | Archive multiple tasks to local file | Archiving | Tool | Description | |------|-------------| | archive_task | Archive a task to the local archive | | restore_task | Restore an archived task to a column | Subtasks | Tool | Description | |------|-------------| | add_subtask | Add a subtask to a task | | toggle_subtask | Mark a subtask complete/incomplete | | update_subtask | Change a subtask's title | | delete_subtask | Remove a subtask | | bulk_set_subtasks | Set multiple subtasks to completed or incomplete at once | | complete_all_subtasks | Mark all subtasks in a task as completed or incomplete | Log Operations | Tool | Description | |------|-------------| | search_logs | Search completed task logs by query, or list recent completions | | append_log | Append a timestamped log entry to any task (active or completed) | Type Operations | Tool | Description | |------|-------------| | list_types | List board strict mode setting and custom type configuration | Rule Operations | Tool | Description | |------|-------------| | list_rules | List project rules, optionally filtered by category | | add_rule | Add a new project rule (always, never, prefer, context) | | delete_rule | Delete a project rule by category and ID | Agent Contracts | Tool | Description | |------|-------------| | contract_pickup | Claim a contract and set status to in_progress | | contract_deliver | Mark contract as delivered (ready for validation) | | contract_validate | Check deliverables exist and run validation commands | | attach_contract | Add contract to existing task with deliverables and validation | Contract workflow: PM creates task with contract using add_task (with with_contract, deliverables, validation_commands, constraints parameters) Worker agent calls contract_pickup to claim the work Worker implements the deliverables Worker calls contract_deliver when done PM calls contract_validate to check work --- Example Interactions You: "What tasks do I have in progress?" Assistant: calls list_tasks with column filter "You have 2 tasks in progress: task-3 'Fix auth bug' and task-7 'Update documentation'." --- You: "I finished the auth bug fix" Assistant: calls move_task "I've moved task-3 to Done." --- You: "Create a task for the performance issue we discussed" Assistant: calls add_task "Created task-12 'Investigate slow dashboard load' with high priority in To Do." --- Benefits Over Manual Updates | Aspect | Manual | MCP | |--------|--------|-----| | Context switching | Open board, find task, update | Zero | | Error risk | YAML typos possible | Type-safe operations | | Consistency | Varies by attention | Always correct format | | Speed | 30+ seconds | Instant | --- Supported Assistants The MCP server works with any tool that supports the Model Context Protocol: - Claude Code — Full support - Cursor — Full support - Cline — Full support - Other MCP clients — Should work, untested --- Troubleshooting Server not loading Check that @brainfile/cli is installed: npx @brainfile/cli --version Verify .mcp.json is valid JSON Restart your AI assistant completely Check assistant logs for MCP errors Tools not appearing Some assistants cache tool lists. Try: Restart the assistant Start a new conversation Explicitly ask "what brainfile tools do you have?" Wrong file being used Specify the file explicitly: ` "args": ["@brainfile/cli", "mcp", "-f", "./my-project/brainfile.md"] ` --- Manual Testing Run the MCP server directly to test: ` brainfile mcp brainfile mcp --file ./project/brainfile.md ` The server communicates via stdio — you'll see JSON-RPC messages if tools are called. --- Alternative: Agent Hooks ::: tip No MCP support? If your assistant doesn't support MCP, you can install hooks that remind you to update tasks: ::: ` brainfile hooks install claude-code brainfile hooks install cursor --scope project brainfile hooks install cline ` Hooks provide gentle reminders but don't give the assistant direct control. --- Next Steps - CLI Commands — Full command reference for manual task management - Protocol Specification — Complete file format and YAML structure specification - Core Library — Build custom integrations with @brainfile/core` - Pi Extension — User-focused PM/worker orchestration manual (bus-first realtime + JSONL audit/replay) - Contract Guide — Deep dive into the contract lifecycle and best practices --- ## 8. Pi Extension Integration Pi Extension Use the Brainfile Pi extension when you want to run multi-agent work as an operator, not as a custom integration author. This manual is focused on how to run orchestration reliably: - bring up PM + workers correctly - execute Direct / Pipeline / Fan-In showcase workflows - validate and close runs cleanly - troubleshoot common operational issues Source code on GitHub --- Mental Model (Operator View) You only need three concepts: Realtime notifications are bus-first - the local realtime bus is the primary trigger path for listener cycles Audit/replay is JSONL - .brainfile/state/pi-events.jsonl is the durable audit trail and replay source PM controls terminal orchestration decisions - workers pick up and deliver - PM validates and closes This gives fast coordination + auditable history without manual polling loops. --- 10-Minute Bring-Up (PM + Workers) 1) Install/activate the extension in your workspace `` git clone https://github.com/brainfile/protocol.git /tmp/brainfile-protocol cp -r /tmp/brainfile-protocol/example/integrations/pi/brainfile-extension/ .pi/extensions/brainfile-extension/ cd .pi/extensions/brainfile-extension && npm install ` Then in each Pi session: ` /reload ` 2) Start one PM session ` /listen role pm /listen on ` 3) Start worker sessions In each worker session: ` /listen role worker /listen on ` 4) Verify health from PM ` /listen status ` You should see: - active run ID - available workers (worker-1, worker-2, ...) - stale timeout Role hygiene checklist - Keep exactly one PM active per workspace run. - Keep all other sessions in worker mode. - Use auto mode only if you understand PM lock behavior. - Do not use sleep/manual polling loops; rely on event-driven listener flow. --- Session Roles and Assignment Behavior | Role | Main responsibility | |---|---| | PM | create/delegate contracts, validate deliveries, close runs | | Worker | pick up eligible contracts, implement, deliver | Worker identity is slot-based (worker-1, worker-2, ...). Routing is identity-based, not model-name-based. | Assignee on task | Pickup behavior | |---|---| | worker-2 | only worker-2 can pick it up | | pool or empty | any eligible idle worker | | legacy assignee (codex, claude, gemini) | treated as pool for compatibility | | pm | worker does not auto-pick | --- Operator Workflow (Plan → Execute → Validate → Close) 1) Plan and delegate (PM) - create task with contract deliverables/constraints - assign to worker-N (direct) or pool (shared) - set contract status to ready 2) Execute (workers) - worker listener auto-picks eligible ready tasks - worker implements and runs delivery checks - worker marks delivered 3) Validate (PM) - PM validates delivered contracts (contract.validate path) - success → done - failure → failed with feedback, then reset to ready 4) Close - complete/archive task after PM acceptance - run ends with run.closed when orchestration reaches terminal state --- Showcase Flows (Direct / Pipeline / Fan-In) For reproducible scenario definitions and checklists: - Runbook: /example/integrations/pi/brainfile-extension/SHOWCASE.md - Scenario definitions: /example/integrations/pi/brainfile-extension/examples/showcase-scenarios.md - Acceptance harness: /guides/orchestration-acceptance A) Direct 1:1 Dispatch Goal: non-target worker cannot claim a direct-targeted task. Expected operator evidence: - rejection decision with reasonCode=dispatch_target_mismatch - accepted pickup only for target worker Quick audit checks: ` rg "dispatch_target_mismatch" .brainfile/state/pi-events.jsonl ` B) Pipeline DAG (dependsOn) Goal: downstream stage unlocks only when prerequisites satisfy readiness policy. Expected operator evidence: - blocked/waiting reason dependency_unmet before prerequisites complete - downstream delegation only after prerequisites are satisfied Quick audit checks: ` rg "dependency_unmet" .brainfile/state/pi-events.jsonl ` C) Fan-Out / Fan-In Barrier (join.mode=barrier) Goal: join/synthesis stage waits until required branches satisfy barrier policy. Expected operator evidence: - waiting reason join_waiting while branches are incomplete - optional dependency_failed if barrier policy is violated by failed branches - no early join delegation Quick audit checks: ` rg "join_waiting|dependency_failed" .brainfile/state/pi-events.jsonl ` --- Run Lifecycle Signals You Should Watch | Event | Operator meaning | |---|---| | run.started | PM orchestration run is active | | run.blocked | run cannot proceed (stale/failed/blocked conditions) | | run.closed | run reached terminal state (success, blocked, etc.) | | contract.delegated | PM delegated work | | contract.picked_up | worker successfully claimed task | | contract.delivered | worker submitted for PM validation | | contract.validated | PM accepted/rejected delivery | PM chat notifications are intentionally quiet and focused on meaningful orchestration events (blocked/close + delivery readiness signals), while full detail remains in JSONL audit. --- Commands You’ll Use Most Listener | Command | Use | |---|---| | /listen on | start listener | | /listen off | stop listener | | /listen status | inspect run/workers/stale timeout | | /listen role | set role | | /listen now | run a single diagnostic cycle | Task/contract operations | Command | Use | |---|---| | /bf contract pickup | manual claim (when needed) | | /bf contract deliver | submit delivery | | /bf contract validate | PM validation | | /bf move | move task state | | /bf status | inspect active task | --- Troubleshooting Duplicate PM avoidance Symptom: two sessions both try to orchestrate as PM. What to do: - keep only one explicit PM session (/listen role pm) - keep others as workers (/listen role worker) - if using auto, rely on PM lock arbitration and verify via /listen status Delayed duplicate messages / late status noise Symptom: old status/decision messages appear after task completion. What to do: - treat .brainfile/state/pi-events.jsonl as source-of-truth audit - use thread + inReplyTo for conversational clarity - rely on PM validation state in board/log files for final authority Stale tasks and blocked runs Symptom: task remains in_progress too long; run moves to blocked. What to do: - PM checks /listen status for worker presence and stale timeout - inspect task.stale / run.blocked records in JSONL - either unblock dependency or reset task to ready with feedback Workspace override: ` { "brainfileExtension": { "staleTimeoutSeconds": 1800 } } ` Reload behavior Symptom: session restart or /reload interrupted listener state. What to do: - run /reload - re-apply role (/listen role pm|worker) - run /listen on - verify with /listen status The listener catches up from persisted offsets + JSONL audit, so recovery is event-driven and does not require manual polling loops. --- A2A Messaging (Operator Essentials) Use brainfile_send_message for PM↔worker coordination inside task threads: - keep threadId as task: - set inReplyTo when responding - use message.blocker` for actionable blockers This keeps orchestration decisions and conversation context auditable together. --- See Also - Orchestration Guide - AI Agent Integration - MCP Server --- ## 9. Core Library TypeScript (@brainfile/core) @brainfile/core is the TypeScript library that powers all Brainfile tools. Use it to build custom integrations, scripts, or entirely new interfaces. Installation `` npm install @brainfile/core ` ::: tip Quick Start ` import { Brainfile, addTask } from '@brainfile/core'; import fs from 'fs'; const board = Brainfile.parse(fs.readFileSync('.brainfile/brainfile.md', 'utf-8')); const result = addTask(board, 'todo', { title: 'My task', priority: 'high' }); if (result.success) fs.writeFileSync('.brainfile/brainfile.md', Brainfile.serialize(result.board!)); ` ::: Quick Example ` import { Brainfile, addTask, moveTask } from '@brainfile/core'; import fs from 'fs'; // Parse a brainfile const markdown = fs.readFileSync('brainfile.md', 'utf-8'); let board = Brainfile.parse(markdown); // Add a task (immutable - returns new board) const result = addTask(board, 'todo', { title: 'New feature', priority: 'high', tags: ['feature'] }); if (result.success) { board = result.board!; } // Move a task const moveResult = moveTask(board, 'task-1', 'todo', 'in-progress', 0); if (moveResult.success) { board = moveResult.board!; } // Save changes const output = Brainfile.serialize(board); fs.writeFileSync('brainfile.md', output); ` --- Core Concepts Immutable Operations ::: info Key concept All operations are immutable — they return a new board object rather than modifying the original. ::: ` const result = addTask(board, 'todo', { title: 'Task' }); // Original unchanged console.log(board.columns[0].tasks.length); // 0 // New board has the task console.log(result.board!.columns[0].tasks.length); // 1 ` Operation Results Every operation returns a BoardOperationResult: ` interface BoardOperationResult { success: boolean; board?: Board; // New board if successful error?: string; // Error message if failed } ` Always check success before using the result: ` const result = moveTask(board, 'task-999', 'todo', 'done', 0); if (!result.success) { console.error(result.error); // "Task not found: task-999" } ` --- ::: info Immutable Pattern All board operations follow the same pattern: call the function, check result.success, then use result.board! for the updated state. The original board is never mutated. ::: Board Operations Add Task ` import { addTask, TaskInput } from '@brainfile/core'; const input: TaskInput = { title: 'Implement auth', description: 'Add OAuth2 support', priority: 'high', tags: ['security', 'feature'], assignee: 'john', dueDate: '2025-02-01', subtasks: ['Research', 'Implement', 'Test'] // Creates subtasks }; const result = addTask(board, 'todo', input); ` Patch Task ::: tip Removing fields Set a field to null to remove it from the task. ::: ` import { patchTask, TaskPatch } from '@brainfile/core'; // Update fields const result = patchTask(board, 'task-1', { priority: 'critical', tags: ['urgent'] }); // Remove fields const removeResult = patchTask(board, 'task-1', { assignee: null, // Removes assignee dueDate: null // Removes due date }); ` Move Task ` import { moveTask } from '@brainfile/core'; // Move task-1 from todo to in-progress, at position 0 const result = moveTask(board, 'task-1', 'todo', 'in-progress', 0); ` Delete Task ` import { deleteTask } from '@brainfile/core'; const result = deleteTask(board, 'todo', 'task-1'); ` Archive & Restore ` import { archiveTask, restoreTask } from '@brainfile/core'; // Archive const archiveResult = archiveTask(board, 'done', 'task-5'); // Restore to a column const restoreResult = restoreTask(board, 'task-5', 'todo'); ` --- Subtask Operations ` import { addSubtask, toggleSubtask, updateSubtask, deleteSubtask } from '@brainfile/core'; // Add subtask (ID auto-generated) const addResult = addSubtask(board, 'task-1', 'Write tests'); // Toggle completion const toggleResult = toggleSubtask(board, 'task-1', 'task-1-1'); // Update title const updateResult = updateSubtask(board, 'task-1', 'task-1-1', 'New title'); // Delete const deleteResult = deleteSubtask(board, 'task-1', 'task-1-2'); ` --- Parsing & Serialization Parse ` import { Brainfile, BrainfileParser } from '@brainfile/core'; // Simple parse const board = Brainfile.parse(markdown); // Parse with error details const result = BrainfileParser.parseWithErrors(markdown); if (!result.board) { console.error('Parse error:', result.error); } if (result.warnings) { console.warn('Warnings:', result.warnings); } ` Serialize ` import { Brainfile, BrainfileSerializer } from '@brainfile/core'; // Simple serialize const output = Brainfile.serialize(board); // With options const output = BrainfileSerializer.serialize(board, { indent: 2, lineWidth: 80, trailingNewline: true }); ` --- Validation & Linting ` import { Brainfile, BrainfileLinter } from '@brainfile/core'; // Validate structure const validation = Brainfile.validate(board); if (!validation.valid) { validation.errors.forEach(e => console.log(${e.path}: ${e.message})); } // Lint raw content const lintResult = Brainfile.lint(content); console.log(lintResult.issues); // Lint with auto-fix const fixedResult = Brainfile.lint(content, { autoFix: true }); console.log(fixedResult.fixedContent); ` --- Templates ` import { Brainfile } from '@brainfile/core'; // List templates const templates = Brainfile.getBuiltInTemplates(); // Create from template const task = Brainfile.createFromTemplate('bug-report', { title: 'Login fails on mobile', description: 'Users see error on iOS Safari' }); ` --- Realtime Sync Utilities For building UIs with live updates: ` import { hashBoardContent, hashBoard, diffBoards } from '@brainfile/core'; // Hash content to detect changes const hash = hashBoardContent(markdown); if (hash !== lastHash) { // Content changed, re-parse } // Diff boards for incremental updates const diff = diffBoards(oldBoard, newBoard); if (diff.tasksMoved.length > 0) { // Handle moved tasks } ` --- TypeScript Types ` import type { Board, Column, Task, Subtask, TaskInput, TaskPatch, BoardOperationResult } from '@brainfile/core'; ` See API Reference for complete type definitions. --- Next Steps - API Reference — Complete method signatures, parameters, and return types - Protocol Specification — Full YAML structure and field reference - Schema Types — JSON schema definitions for all document types - MCP Server — AI assistant integration using @brainfile/core` under the hood - CLI Source — See how the CLI uses the core library --- ## 10. Protocol Specification Protocol Specification The Brainfile protocol defines a structured format for project tasks stored in markdown files with YAML frontmatter. v2 Architecture Brainfile v2 uses a directory-based structure: `` .brainfile/ ├── brainfile.md # Board Configuration ├── board/ # Active task files │ ├── task-1.md │ └── epic-1.md └── logs/ # Completed Documents ├── ledger.jsonl # Unified event log ├── task-2.md # (legacy) Completed task └── adr-1.md # (legacy) Completed ADR ` File Discovery | Path | Priority | Notes | |------|----------|-------| | .brainfile/brainfile.md | 1 (preferred, v2) | Directory-based architecture | | brainfile.md | 2 | Root file (legacy compat) | | .brainfile.md | 3 | Hidden, backward compat | Completion ::: info Completion Model Completed tasks are moved from board/ to logs/ via brainfile complete. Completion appends a JSON record to logs/ledger.jsonl and archives the task file. ::: board/ brainfile complete logs/ --- YAML Structure Board Config (brainfile.md) ` --- title: string # Required columns: # Required - id: string # Required — unique kebab-case identifier title: string # Required — display title completionColumn: boolean # Optional — auto-complete on move All below are optional type: board schema: string protocolVersion: string strict: boolean # Enforce type validation types: # Custom document types epic: idPrefix: epic completable: true adr: idPrefix: adr completable: false agent: instructions: [] llmNotes: string rules: always: [] never: [] prefer: [] context: [] --- ` ::: tip Minimal Example The smallest valid board config: ` --- title: My Project columns: - id: todo title: To Do --- ` ::: Task File (board/task-1.md) ` --- id: task-1 # Required — unique ID type: task # Optional — defaults to "task" title: Implement feature # Required column: todo # Required (active tasks) priority: high # Optional assignee: codex # Optional tags: [backend] # Optional relatedFiles: [src/main.ts] # Optional parentId: epic-1 # Optional dueDate: "2026-03-01" # Optional subtasks: # Optional - id: task-1-1 title: Write tests completed: false contract: # Optional status: ready deliverables: - path: src/feature.ts --- Description Task details here. Log - 2026-02-18T10:00:00Z: Created ` ::: tip Minimal Example The smallest valid task file: ` --- id: task-1 title: My task column: todo --- ` ::: --- Field Reference Board Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | title | string | Yes | Project or board title | | type | string | No | Document type (default: board) | | schema | string | No | JSON schema URL for validation | | protocolVersion | string | No | Protocol version | | strict | boolean | No | Enforce type validation | | types | object | No | Custom document types | | agent | object | No | AI agent instructions | | rules | object | No | Project rules | | columns | array | Yes | Workflow columns | | statsConfig | object | No | Statistics configuration | Column Fields Columns are config-only in v2 (no embedded tasks): | Field | Type | Required | Description | |-------|------|----------|-------------| | id | string | Yes | Unique identifier (kebab-case) | | title | string | Yes | Display title | | completionColumn | boolean | No | Auto-complete on move | Task Fields Each task is a standalone .md file in .brainfile/board/: | Field | Type | Required | Description | |-------|------|----------|-------------| | id | string | Yes | Unique ID (pattern: {type}-N, e.g., task-1, epic-2) | | type | string | No | Document type (default: task) | | title | string | Yes | Task title | | column | string | Yes | Column ID (required for active tasks, omitted in logs/) | | description | string | No | Detailed description (markdown) | | priority | string | No | low, medium, high, critical | | effort | string | No | trivial, small, medium, large, xlarge | | assignee | string | No | Person/agent responsible | | dueDate | string | No | ISO 8601 date | | tags | array | No | String tags for filtering | | relatedFiles | array | No | File paths | | blockedBy | array | No | Task IDs that block this task | | subtasks | array | No | Subtask objects | | contract | object | No | Agent contract | | createdAt | string | No | ISO 8601 timestamp | | updatedAt | string | No | ISO 8601 timestamp, set on mutations | | completedAt | string | No | Set when appended to ledger.jsonl and archived to logs/ | | parentId | string | No | Parent document ID (any type) | | position | number | No | Sort position within the column | Subtask Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | id | string | Yes | Unique ID (e.g., task-1-1) | | title | string | Yes | Subtask title | | completed | boolean | Yes | Completion status | --- Standard Column IDs These IDs are conventional but not required. The default brainfile init creates todo and in-progress: | ID | Purpose | |----|---------| | backlog | Tasks not yet scheduled | | todo | Tasks to be started | | in-progress | Tasks being worked on | | review | Tasks pending review | ::: info No default "done" column In v2, task completion is handled by appending a record to ledger.jsonl and moving the file to logs/ via brainfile complete. A "done" column is not created by default. You can optionally add one with completionColumn: true if you want auto-completion behavior. ::: --- Agent Instructions The agent block guides AI assistant behavior: ` agent: instructions: - Modify only the YAML frontmatter - Preserve all IDs - Keep ordering - Make minimal changes - Preserve unknown fields llmNotes: "Prefer functional patterns and comprehensive tests" ` | Instruction | Reason | |-------------|--------| | Modify only YAML frontmatter | Content after --- is user documentation | | Preserve all IDs | Changing IDs breaks references | | Keep ordering | Maintains visual consistency | | Make minimal changes | Reduces merge conflicts | | Preserve unknown fields | Future-proofs against extensions | --- Rules Block Project rules for AI and human reference: ` rules: always: - id: 1 rule: write tests for new features - id: 2 rule: update task status as you work never: - id: 1 rule: commit directly to main prefer: - id: 1 rule: functional patterns over classes context: - id: 1 rule: TypeScript monorepo with Jest ` --- Schema Reference Official Schemas | Type | URL | |------|-----| | Base | https://brainfile.md/v2/base.json | | Board | https://brainfile.md/v2/board.json | | Task | https://brainfile.md/v2/task.json | | Contract | https://brainfile.md/v2/contract.json | | Epic | https://brainfile.md/v2/epic.json | | ADR | https://brainfile.md/v2/adr.json | Browse all: brainfile.md/v2/ Type Inference When type is omitted, tools detect by: Schema URL pattern (/v2/board.json → board) Structural analysis (columns[] → board) Default: board --- ID Patterns ::: info ID Assignment IDs are auto-generated by the CLI and must never be changed manually. Changing an ID breaks all references — parentId, blockedBy, and subtask IDs all depend on stable document IDs. ::: Document IDs Pattern: {type}-N where N is a sequential number. ` - id: task-1 # Standard task - id: task-15 - id: epic-1 # Epic - id: adr-3 # Architecture Decision Record ` Subtask IDs Pattern: {taskId}-N where N is a sequential number within the parent task. ` For a task with id: task-1 subtasks: - id: task-1-1 - id: task-1-2 ` --- Version History v2.0.0 (Current) - Per-task file architecture (board/, logs/) - Custom document types with strict mode - Epic and ADR as first-class types - Contract system with lifecycle - parentId linking model 1.0.0 (Legacy) - Single-file embedded tasks - Board-only task management - Full MCP tool support v0.5.0 - Added base schema with inheritance - Added agent.tools for CLI tool configuration v0.4.0 - Added protocolVersion field - Added effort and blockedBy task fields - Added llmNotes to agent block v0.3.0 - Changed default to non-hidden files (brainfile.md) - Added agent instruction block - Added subtasks support --- Best Practices Use non-hidden files — Better visibility, AI-friendly Include agent instructions — Consistent AI behavior Preserve IDs — Never regenerate or change task IDs Use semantic IDs — Sequential task-1, task-2 Keep descriptions concise — But informative Archive completed tasks — Keep board clean --- Example Board Config (.brainfile/brainfile.md) ` --- title: My Project type: board schema: https://brainfile.md/v2/board.json columns: - id: todo title: To Do - id: in-progress title: In Progress strict: true types: epic: idPrefix: epic completable: true agent: instructions: - Update task status as you work - Preserve all IDs rules: always: - id: 1 rule: write tests for new features --- My Project Project documentation can go here. ` Task File (.brainfile/board/task-1.md) ` --- id: task-1 type: task title: Implement user authentication column: todo priority: high tags: [backend, security] subtasks: - id: task-1-1 title: Setup OAuth provider completed: false - id: task-1-2 title: Create login UI completed: false --- Description Add OAuth2 support for Google and GitHub. `` --- Next Steps - Schema Types — JSON schema definitions for all document types - API Reference — Programmatic access via @brainfile/core - CLI Commands — Command-line interface reference - Contract Schema — Contract object specification --- ## 11. API Reference API Reference Complete documentation for @brainfile/core TypeScript library. Getting Started Install the core library: `` npm install @brainfile/core ` Minimal usage example: ` import { Brainfile, addTask, moveTask } from "@brainfile/core"; import { readFileSync, writeFileSync } from "fs"; // Parse a brainfile const content = readFileSync(".brainfile/brainfile.md", "utf-8"); const board = Brainfile.parse(content); // Add a task const result = addTask(board!, "todo", { title: "My first task" }); // Serialize and save if (result.success) { const markdown = Brainfile.serialize(result.board!); writeFileSync(".brainfile/brainfile.md", markdown); } ` ::: info All operations are immutable Board operations return a new Board object — the original is never modified. Always check result.success before using result.board. ::: --- Brainfile Class The main class provides static methods for all core operations. Parsing Brainfile.parse(content: string): Board | null Parse markdown content into a Board object. ` const board = Brainfile.parse(markdownString); if (board) { console.log(board.title); } ` Brainfile.parseWithErrors(content: string): ParseResult Parse with detailed error and warning information. ` const result = Brainfile.parseWithErrors(markdownString); if (result.board) { console.log("Parsed successfully"); if (result.warnings) { console.warn("Warnings:", result.warnings); } } else { console.error("Parse error:", result.error); } ` Serialization Brainfile.serialize(board: Board, options?: SerializeOptions): string Serialize a Board object back to markdown format. ` const markdown = Brainfile.serialize(board, { indent: 2, lineWidth: 80, trailingNewline: true, }); ` Validation Brainfile.validate(board: Board): ValidationResult Validate a board against the schema. ` const validation = Brainfile.validate(board); if (!validation.valid) { validation.errors.forEach((err) => { console.log(${err.path}: ${err.message}); }); } ` Linting Brainfile.lint(content: string, options?: LintOptions): LintResult Lint raw content for issues, optionally auto-fixing. ` // Check for issues const result = Brainfile.lint(content); console.log(result.issues); // Auto-fix issues const fixedResult = Brainfile.lint(content, { autoFix: true }); console.log(fixedResult.fixedContent); ` Templates Brainfile.getBuiltInTemplates(): TaskTemplate[] Get all built-in task templates. ` const templates = Brainfile.getBuiltInTemplates(); templates.forEach((t) => console.log(${t.id}: ${t.name})); ` Brainfile.getTemplate(id: string): TaskTemplate | undefined Get a specific template by ID. Brainfile.createFromTemplate(templateId: string, values: Record): Partial Create a task from a template. ` const task = Brainfile.createFromTemplate("bug-report", { title: "Login fails on mobile", description: "Users cannot log in on iOS", }); ` Location Finding Brainfile.findTaskLocation(content: string, taskId: string): Location Find line number of a task in source. Brainfile.findRuleLocation(content: string, ruleId: number, ruleType: RuleType): Location Find line number of a rule in source. --- Board Operations All operations are immutable and return BoardOperationResult. ::: info Error Handling Pattern Every operation returns { success, board?, error? }. Always check success before accessing board — a failed operation returns error with a descriptive message and board will be undefined. ::: addTask(board, columnId, input): BoardOperationResult ` import { addTask, type TaskInput } from "@brainfile/core"; const result = addTask(board, "todo", { title: "Implement auth", description: "Add OAuth2 support", priority: "high", tags: ["security"], assignee: "john", dueDate: "2025-02-01", subtasks: ["Research", "Implement", "Test"], }); if (result.success) { board = result.board!; } ` patchTask(board, taskId, patch): BoardOperationResult Set fields to null to remove them. ` import { patchTask } from "@brainfile/core"; // Update fields patchTask(board, "task-1", { priority: "critical" }); // Remove fields patchTask(board, "task-1", { assignee: null, dueDate: null }); ` moveTask(board, taskId, fromColumn, toColumn, toIndex): BoardOperationResult ` import { moveTask } from "@brainfile/core"; moveTask(board, "task-1", "todo", "in-progress", 0); ` deleteTask(board, columnId, taskId): BoardOperationResult ` import { deleteTask } from "@brainfile/core"; deleteTask(board, "todo", "task-1"); ` archiveTask(board, columnId, taskId): BoardOperationResult ` import { archiveTask } from "@brainfile/core"; archiveTask(board, "done", "task-5"); ` restoreTask(board, taskId, columnId): BoardOperationResult ` import { restoreTask } from "@brainfile/core"; restoreTask(board, "task-5", "todo"); ` --- Contract Operations All contract operations return BoardOperationResult and are immutable. ::: info Contract Status Transitions Status changes are validated — you can't move from ready to done directly. Use the lifecycle: ready → in_progress → delivered → done. See setTaskContractStatus for status updates. ::: setTaskContract(board, taskId, contract): BoardOperationResult Set or replace the complete contract for a task. ` import { setTaskContract, type Contract } from "@brainfile/core"; const contract: Contract = { status: "ready", deliverables: [ { type: "file", path: "src/feature.ts", description: "Implementation" }, { type: "test", path: "src/__tests__/feature.test.ts" }, ], validation: { commands: ["npm test"], }, constraints: ["Follow existing patterns"], }; const result = setTaskContract(board, "task-1", contract); ` clearTaskContract(board, taskId): BoardOperationResult Remove the contract from a task. setTaskContractStatus(board, taskId, status): BoardOperationResult Update just the contract status. ` import { setTaskContractStatus } from "@brainfile/core"; setTaskContractStatus(board, "task-1", "in_progress"); ` patchTaskContract(board, taskId, patch): BoardOperationResult Update specific contract fields. Set fields to null to remove them. ` import { patchTaskContract } from "@brainfile/core"; // Update fields patchTaskContract(board, "task-1", { status: "delivered", constraints: ["New constraint"], }); // Remove fields patchTaskContract(board, "task-1", { validation: null, }); ` addTaskContractDeliverable(board, taskId, deliverable): BoardOperationResult Add a deliverable to the contract. ` import { addTaskContractDeliverable } from "@brainfile/core"; addTaskContractDeliverable(board, "task-1", { type: "docs", path: "docs/api.md", description: "API documentation", }); ` removeTaskContractDeliverable(board, taskId, path): BoardOperationResult Remove a deliverable by path. addTaskContractValidationCommand(board, taskId, command): BoardOperationResult Add a validation command. removeTaskContractValidationCommand(board, taskId, command): BoardOperationResult Remove a validation command. addTaskContractConstraint(board, taskId, constraint): BoardOperationResult Add a constraint. removeTaskContractConstraint(board, taskId, constraint): BoardOperationResult Remove a constraint. --- Bulk Operations Process multiple tasks in a single operation. All bulk operations return BulkOperationResult. ::: info Partial Success Bulk operations can partially succeed — some tasks may fail while others succeed. Always check results for per-task status, and use successCount/failureCount for summary. ::: moveTasks(board, taskIds, toColumnId): BulkOperationResult Move multiple tasks to a column. ` import { moveTasks } from "@brainfile/core"; const result = moveTasks(board, ["task-1", "task-2", "task-3"], "done"); console.log(Success: ${result.successCount}, Failed: ${result.failureCount}); result.results.forEach((r) => { if (!r.success) { console.log(Failed to move ${r.id}: ${r.error}); } }); ` patchTasks(board, taskIds, patch): BulkOperationResult Apply the same patch to multiple tasks. ` import { patchTasks } from "@brainfile/core"; patchTasks(board, ["task-1", "task-2"], { priority: "high", assignee: "john" }); ` deleteTasks(board, taskIds): BulkOperationResult Delete multiple tasks. archiveTasks(board, taskIds): BulkOperationResult Archive multiple tasks. ` import { archiveTasks } from "@brainfile/core"; archiveTasks(board, ["task-10", "task-11", "task-12"]); ` --- Subtask Operations addSubtask(board, taskId, title): BoardOperationResult ID is auto-generated as task-N-M. deleteSubtask(board, taskId, subtaskId): BoardOperationResult updateSubtask(board, taskId, subtaskId, title): BoardOperationResult toggleSubtask(board, taskId, subtaskId): BoardOperationResult ` import { addSubtask, deleteSubtask, updateSubtask, toggleSubtask, } from "@brainfile/core"; addSubtask(board, "task-1", "New subtask"); toggleSubtask(board, "task-1", "task-1-1"); updateSubtask(board, "task-1", "task-1-1", "Updated title"); deleteSubtask(board, "task-1", "task-1-2"); ` --- Realtime Sync Utilities ::: info TUI Integration These utilities power the TUI's real-time file watching. Use hashBoardContent to detect file changes and diffBoards to compute minimal UI updates. ::: hashBoardContent(content: string): string SHA-256 hash of raw content. Use to detect file changes. ` const hash = hashBoardContent(markdown); if (hash !== lastHash) { refreshBoard(); } ` hashBoard(board: Board): string Hash of serialized board. Deterministic fingerprint for sharing. diffBoards(previous: Board, next: Board): BoardDiff Compute structural differences for incremental UI updates. ` const diff = diffBoards(oldBoard, newBoard); if (diff.tasksMoved.length > 0) { // Handle moved tasks } ` --- Types Board ` interface Board { title: string; protocolVersion?: string; schema?: string; agent?: AgentInstructions; rules?: Rules; columns: Column[]; archive?: Task[]; // legacy compat strict?: boolean; // v2: enforce type validation types?: TypesConfig; // v2: custom document types } ` Column ` interface Column { id: string; title: string; tasks: Task[]; // legacy compat / in-memory operations completionColumn?: boolean; // v2: auto-complete on move } ` Task ` interface Task { id: string; title: string; column?: string; // v2: column ID reference type?: string; // v2: document type description?: string; relatedFiles?: string[]; assignee?: string; tags?: string[]; priority?: "low" | "medium" | "high" | "critical"; effort?: "trivial" | "small" | "medium" | "large" | "xlarge"; blockedBy?: string[]; dueDate?: string; subtasks?: Subtask[]; contract?: Contract; parentId?: string; // v2: parent document ID position?: number; // v2: sort position within column createdAt?: string; updatedAt?: string; // v2: ISO 8601 timestamp completedAt?: string; } ` Contract ` interface Contract { status: ContractStatus; version?: number; deliverables?: Deliverable[]; validation?: ValidationConfig; constraints?: string[]; outOfScope?: string[]; feedback?: string; metrics?: ContractMetrics; } type ContractStatus = | "ready" | "in_progress" | "delivered" | "done" | "failed" | "blocked"; interface Deliverable { type?: string; // "file", "test", "docs", "design", "research" path: string; description?: string; } interface ValidationConfig { commands?: string[]; } interface ContractMetrics { pickedUpAt?: string; deliveredAt?: string; duration?: number; reworkCount?: number; } ` ::: info v2 migration ContractContext is deprecated. Use task.description for background and task.relatedFiles for relevant files instead. ::: Subtask ` interface Subtask { id: string; title: string; completed: boolean; } ` TaskInput For addTask(): ` interface TaskInput { title: string; description?: string; priority?: "low" | "medium" | "high" | "critical"; tags?: string[]; assignee?: string; dueDate?: string; relatedFiles?: string[]; template?: "bug" | "feature" | "refactor"; subtasks?: string[]; // Titles only, IDs auto-generated } ` TaskPatch For patchTask(). Use null to remove fields. ` interface TaskPatch { title?: string; description?: string | null; priority?: "low" | "medium" | "high" | "critical" | null; tags?: string[] | null; assignee?: string | null; dueDate?: string | null; relatedFiles?: string[] | null; template?: "bug" | "feature" | "refactor" | null; } ` ContractPatch For patchTaskContract(). Use null to remove fields. ` interface ContractPatch { status?: ContractStatus; version?: number; deliverables?: Deliverable[] | null; validation?: ValidationConfig | null; constraints?: string[] | null; outOfScope?: string[] | null; feedback?: string | null; } ` BoardOperationResult ` interface BoardOperationResult { success: boolean; board?: Board; // New board if success error?: string; // Error message if failed } ` BulkOperationResult For bulk operations (moveTasks, patchTasks, deleteTasks, archiveTasks). ` interface BulkOperationResult { success: boolean; // True if all operations succeeded board?: Board; // New board if at least one operation succeeded results: BulkItemResult[]; successCount: number; failureCount: number; } interface BulkItemResult { id: string; // Task ID success: boolean; error?: string; // Error message if failed } ` BoardDiff ` interface BoardDiff { metadataChanged: boolean; columnsAdded: ColumnDiff[]; columnsRemoved: ColumnDiff[]; columnsUpdated: ColumnDiff[]; columnsMoved: ColumnDiff[]; tasksAdded: TaskDiff[]; tasksRemoved: TaskDiff[]; tasksUpdated: TaskDiff[]; tasksMoved: TaskDiff[]; } ` AgentInstructions ` interface AgentInstructions { instructions?: string[]; llmNotes?: string; } ` Rules ` interface Rules { always?: Rule[]; never?: Rule[]; prefer?: Rule[]; context?: Rule[]; } interface Rule { id: number; rule: string; } ` SerializeOptions ` interface SerializeOptions { indent?: number; // Default: 2 lineWidth?: number; // Default: 80 trailingNewline?: boolean; // Default: true } ` ValidationResult ` interface ValidationResult { valid: boolean; errors: ValidationError[]; } interface ValidationError { path: string; message: string; } ` ParseResult ` interface ParseResult { board: Board | null; error?: string; warnings?: string[]; } ` --- Low-Level Classes For advanced usage: ` import { BrainfileParser, BrainfileSerializer, BrainfileValidator, BrainfileLinter, } from "@brainfile/core"; // Parser BrainfileParser.parse(markdown); BrainfileParser.parseWithErrors(markdown); BrainfileParser.findTaskLocation(markdown, "task-1"); // Serializer BrainfileSerializer.serialize(board, options); // Validator BrainfileValidator.validate(board); // Linter BrainfileLinter.lint(content, { autoFix: true }); BrainfileLinter.getSummary(lintResult); BrainfileLinter.groupIssues(lintResult); `` --- Next Steps - Protocol Specification — File format details - CLI Commands — Command-line interface - Core Library Guide — Usage examples --- ## 12. CLI Commands Reference CLI Command Reference Complete documentation for all @brainfile/cli commands. ::: tip Most Used Commands | Command | Jump to | |---------|---------| | brainfile add | Create tasks with contracts, subtasks, and metadata | | brainfile list | Filter and display tasks by column, tag, or contract status | | brainfile move | Move tasks between columns | | brainfile complete | Complete tasks — append to ledger.jsonl and archive to logs/ | | brainfile contract | Manage contracts — pickup, deliver, validate | | brainfile patch | Update fields on existing tasks | ::: Command Overview `` brainfile [file] # Open TUI (auto-detects .brainfile/brainfile.md) brainfile # Run CLI command brainfile mcp # Start MCP server for AI assistants ` Commands | Command | Description | |---------|-------------| | init | Create a new brainfile | | list | Display tasks | | show | Display single task details | | add | Create a new task | | move | Move task between columns | | patch | Update task fields | | delete | Permanently delete a task | | archive | Archive a task | | restore | Restore from archive | | subtask | Manage subtasks | | lint | Validate and fix syntax | | template | Create from templates | | tui | Interactive terminal UI | | hooks | AI agent hook integration | | complete | Complete a task (append to ledger.jsonl and archive to logs/) | | contract | Manage agent-to-agent contracts | | adr | ADR lifecycle management | | rules | Manage project rules | | types | Document type management | | search | Search tasks and logs | | log | View completed task logs | | migrate | Move brainfile to .brainfile/ directory | | config | Manage user configuration | | auth | Authenticate with external services | | mcp | MCP server for AI assistants | --- init Create a new .brainfile/ project directory with board config, board/, and logs/. ` brainfile init brainfile init --force # Overwrite existing ` Options: | Option | Description | |--------|-------------| | -f, --file | Output path (default: .brainfile/brainfile.md) | | --force | Overwrite if file exists | --- list Display all tasks with optional filtering. ::: tip Essential Command list is the go-to command for finding tasks. Combine filters like --column and --tag to narrow results. Use --contract ready to find work waiting for agents. ::: ` brainfile list brainfile list --column "In Progress" brainfile list --tag bug brainfile list --contract ready ` Options: | Option | Description | |--------|-------------| | -f, --file | Path to brainfile (auto-detects .brainfile/brainfile.md) | | -c, --column | Filter by column | | -t, --tag | Filter by tag | | --parent | Filter by parent task ID (parentId) | | --contract | Filter by contract status (ready, in_progress, delivered, done, failed, blocked) | --- show Display full details of a single task. ` brainfile show --task task-1 brainfile show -t task-42 ` Options: | Option | Description | |--------|-------------| | -t, --task | Task ID (required) | | -f, --file | Path to brainfile (auto-detects .brainfile/brainfile.md) | | --json | Output task data as JSON | Output includes: - Task ID, title, column, priority, tags, assignee - Full description - Subtasks with completion status - Related files - Contract details (if present) --- add Create a new task with all available fields. ::: tip Power Command add supports one-shot creation of tasks with contracts, subtasks, and full metadata. Use --with-contract along with --deliverable and --validation to create ready-to-assign work items. ::: ` brainfile add --title "Implement auth" brainfile add --title "Fix bug" --priority high --tags "bug,urgent" brainfile add --title "Auth overhaul" --child "OAuth flow" --child "Session handling" brainfile add --title "Design doc" --type adr --column todo ` Options: | Option | Description | |--------|-------------| | -t, --title | Task title (required) | | -c, --column | Target column (default: todo) | | -d, --description | Task description | | -p, --priority | low, medium, high, or critical | | --type | Document type (e.g., epic, adr; default: task) | | --parent | Parent task/epic ID | | --child | Create child task(s) under the new parent (repeatable) | | --tags <list> | Comma-separated tags | | --assignee <name> | Assignee name | | --due-date <date> | Due date (YYYY-MM-DD) | | --subtasks <list> | Comma-separated subtask titles | | --files <list> | Comma-separated related file paths | | --with-contract | Attach a contract (status=ready) | | --deliverable <spec> | Contract deliverable: type:path:description (repeatable) | | --validation <command> | Contract validation command (repeatable) | | --constraint <text> | Contract constraint (repeatable) | --- move Move a task to a different column. ::: tip Workflow Progression Use move to progress tasks through your workflow. Moving to a completion column (if configured) can auto-complete the task. ::: ` brainfile move --task task-1 --column "In Progress" brainfile move --task task-5 --column done ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | -c, --column <name> | Target column (required) | --- patch Update specific fields of a task. Use --clear- options to remove fields. ` brainfile patch --task task-1 --priority critical brainfile patch --task task-1 --title "Updated" --tags "new,tags" brainfile patch --task task-1 --clear-assignee ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | --title <text> | New title | | --description <text> | New description | | --priority <level> | New priority | | --tags <list> | New tags (comma-separated) | | --assignee <name> | New assignee | | --due-date <date> | New due date | | --clear-description | Remove description | | --clear-priority | Remove priority | | --clear-tags | Remove tags | | --clear-assignee | Remove assignee | | --clear-due-date | Remove due date | --- delete Permanently delete a task. Requires confirmation. ` brainfile delete --task task-1 --force ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | --force | Confirm deletion (required) | --- archive Archive a task locally or to an external service (GitHub Issues, Linear). ` brainfile archive --task task-1 brainfile archive --task task-1 --to github brainfile archive --all --to linear --dry-run ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID to archive | | --to <destination> | Archive destination: local, github, or linear | | --all | Archive all tasks from local archive to external service | | --dry-run | Preview what would be created without making changes | --- restore Restore an archived task to a column. ` brainfile restore --task task-1 --column todo ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | -c, --column <name> | Target column (required) | --- subtask Manage subtasks within a task. ` brainfile subtask --task task-1 --add "New subtask" brainfile subtask --task task-1 --toggle task-1-1 brainfile subtask --task task-1 --update task-1-1 --title "Updated" brainfile subtask --task task-1 --delete task-1-2 ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Parent task ID (required) | | --add <title> | Add a new subtask | | --toggle <id> | Toggle subtask completion | | --update <id> | Update subtask (use with --title) | | --delete <id> | Delete a subtask | | --title <text> | New title (for --update) | --- lint Validate brainfile syntax and auto-fix issues. ` brainfile lint # Check for issues brainfile lint --fix # Auto-fix issues brainfile lint --check # Exit with error (for CI) ` Options: | Option | Description | |--------|-------------| | -f, --file <path> | Path to brainfile (auto-detects .brainfile/brainfile.md) | | --fix | Automatically fix issues | | --check | Exit with error code if issues found | What it checks: - YAML syntax errors - Unquoted strings with colons (auto-fixable) - Duplicate column IDs - Missing required fields --- template Create tasks from built-in templates. ` brainfile template --list brainfile template --use bug-report --title "Login fails" brainfile template --use feature-request --title "Dark mode" ` Options: | Option | Description | |--------|-------------| | -l, --list | List available templates | | -u, --use <id> | Create from template | | --title <text> | Task title (required with --use) | | --description <text> | Task description | | -c, --column <name> | Target column (default: todo) | Built-in Templates: - bug-report — Bug tracking with triage steps - feature-request — Feature proposals - refactor — Code refactoring tasks --- tui Launch interactive terminal UI. This is the default when running brainfile without arguments. ` brainfile # Opens TUI (auto-detects .brainfile/brainfile.md) brainfile ./tasks.md # Opens TUI with specific file brainfile tui # Explicit TUI command ` Keyboard Controls: | Key | Action | |-----|--------| | TAB / Shift+TAB | Navigate columns | | j/k or ↑/↓ | Navigate tasks | | Enter | Expand/collapse task | | / | Search tasks | | ? | Show help | | r | Refresh | | q | Quit | --- hooks Install integration hooks for AI coding assistants. ` brainfile hooks install claude-code brainfile hooks install cursor --scope project brainfile hooks install cline brainfile hooks list brainfile hooks uninstall claude-code --scope all ` Supported Assistants: - Claude Code - Cursor - Cline Options: | Option | Description | |--------|-------------| | --scope <scope> | user (default), project, or all | --- complete Complete a task — appends a record to ledger.jsonl and moves it from board/ to logs/. ::: tip Board Hygiene complete archives finished work to logs/, keeping your active board clean. Use --force for epics with remaining child tasks. ::: ` brainfile complete --task task-1 brainfile complete -t epic-1 --force ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | --force | Force epic completion even if child tasks are still active | --- contract Manage the lifecycle of agent-to-agent contracts. ::: tip Agent Coordination The contract command drives the full agent-to-agent workflow: pickup → deliver → validate. See the Contracts Guide for lifecycle details. ::: ` brainfile contract pickup --task task-1 brainfile contract deliver --task task-1 brainfile contract validate --task task-1 brainfile contract attach --task task-1 --deliverable "file:src/feature.ts:Implementation" ` Subcommands: | Command | Description | |---------|-------------| | pickup | Claim a contract and set status to in_progress | | deliver | Mark contract as delivered (ready for validation) | | validate | Check deliverables and run validation commands | | attach | Add contract to existing task | Common Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | -f, --file <path> | Path to brainfile (auto-detects .brainfile/brainfile.md) | Attach Options: | Option | Description | |--------|-------------| | --deliverable <spec> | Add deliverable (format: type:path:description) | | --validation <command> | Add validation command (repeatable) | | --constraint <text> | Add constraint (repeatable) | See the Contract Commands Reference for detailed documentation. --- adr Manage Architecture Decision Records. ` brainfile adr promote -t adr-1 --category always ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | ADR task ID (required) | | --category <cat> | Rule category: prefer, always, never, context | --- rules Manage project rules. ` brainfile rules # List all rules brainfile rules list --category always # Filter by category brainfile rules add always "Write tests" # Add a rule brainfile rules delete always 1 # Delete rule by ID ` --- types Inspect and manage board document types. ` brainfile types list brainfile types add epic --completable true --id-prefix epic ` --- search Search across active tasks and completed logs. ` brainfile search "auth" brainfile search "bug" --column todo ` --- log View and search completed task logs. ` brainfile log # List recent completions brainfile log -t task-10 # View specific log brainfile log --search "auth" # Search logs ` --- note Append a timestamped note to a task's log section. ` brainfile note -t task-1 "Started implementation" brainfile note -t task-1 "Fixed failing test" --agent codex ` Options: | Option | Description | |--------|-------------| | -t, --task <id> | Task ID (required) | | --agent <name> | Agent name for attribution | | [message] | Log message to append (positional argument) | --- migrate Move root brainfile.md to .brainfile/ directory structure. ` brainfile migrate brainfile migrate --dir ./project brainfile migrate --force ` Options: | Option | Description | |--------|-------------| | --dir <path> | Project directory (default: current directory) | | --force | Overwrite existing .brainfile/brainfile.md | What it does: - Creates .brainfile/ directory - Moves brainfile.md → .brainfile/brainfile.md - Creates .brainfile/.gitignore (ignores state.json) - Preserves all content exactly --- config Manage user configuration stored in ~/.config/brainfile/config.json. ` brainfile config list brainfile config get archive.default brainfile config set archive.default github brainfile config path ` Subcommands: | Command | Description | |---------|-------------| | list | Show all configuration values | | get <key> | Get specific config value | | set <key> <value> | Set config value | | path | Show config file path | Common Config Keys: - archive.default — Default archive destination (local, github, linear) - archive.github.owner — GitHub repository owner - archive.github.repo — GitHub repository name - archive.linear.teamId — Linear team ID --- auth Authenticate with external services for archive functionality. ` brainfile auth github brainfile auth linear --token <api-key> brainfile auth status brainfile auth logout github ` Subcommands: | Command | Description | |---------|-------------| | github [--token <token>] | Authenticate with GitHub (auto-detects gh CLI or uses OAuth) | | linear --token <token> | Authenticate with Linear API | | status | Show authentication status for all services | | logout [provider] [--all] | Log out from service(s) | Options: | Option | Description | |--------|-------------| | --token <token> | API token (required for Linear, optional for GitHub) | | --all | Log out from all services | --- mcp Start an MCP (Model Context Protocol) server for AI assistant integration. ` brainfile mcp brainfile mcp --file ./project/brainfile.md ` Options: | Option | Description | |--------|-------------| | -f, --file <path> | Path to brainfile (auto-detects .brainfile/brainfile.md) | Available MCP Tools (30): Task Management: | Tool | Description | |------|-------------| | list_tasks | List tasks with optional filtering (column, tag, type, contract status) | | get_task | Get detailed information about a specific task | | search_tasks | Search tasks by query, column, priority, assignee | | add_task | Create a task with title, priority, tags, type, relatedFiles, contracts | | move_task | Move task between columns | | patch_task | Update task fields | | delete_task | Permanently delete a task | | complete_task | Complete a task (append to ledger.jsonl and archive) | Bulk Operations: | Tool | Description | |------|-------------| | bulk_move_tasks | Move multiple tasks to a column | | bulk_patch_tasks | Apply same patch to multiple tasks | | bulk_delete_tasks | Delete multiple tasks | | bulk_archive_tasks | Archive multiple tasks | Archiving: | Tool | Description | |------|-------------| | archive_task | Archive a task (local, GitHub, or Linear) | | restore_task | Restore from archive | Subtasks: | Tool | Description | |------|-------------| | add_subtask | Add a subtask | | toggle_subtask | Toggle subtask completion | | update_subtask | Update subtask title | | delete_subtask | Delete a subtask | | bulk_set_subtasks | Set multiple subtasks to completed or incomplete | | complete_all_subtasks | Mark all subtasks as completed or incomplete | Agent Contracts: | Tool | Description | |------|-------------| | contract_pickup | Claim a contract (status → in_progress) | | contract_deliver | Mark contract as delivered | | contract_validate | Check deliverables and run validation commands | | attach_contract | Add contract to existing task | Logs, Types, and Rules:* | Tool | Description | |------|-------------| | search_logs | Search completed task logs | | append_log | Append a timestamped log entry to a task | | list_types | List board type configuration | | list_rules | List project rules | | add_rule | Add a project rule | | delete_rule | Delete a project rule | --- Global Options | Option | Description | |--------|-------------| | --help | Display help for command | | --version | Display CLI version | Exit Codes | Code | Meaning | |------|---------| | 0 | Success | | 1 | Error (invalid arguments, file not found) | | 2 | Validation error (with lint --check) | --- CI/CD Integration GitHub Actions ` name: Validate Brainfile on: [push, pull_request] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Validate run: npx @brainfile/cli lint --check ` Pre-commit Hook ` #!/bin/bash .git/hooks/pre-commit if [ -f "brainfile.md" ]; then npx @brainfile/cli lint --check if [ $? -ne 0 ]; then echo "brainfile.md has validation errors" exit 1 fi fi ` npm Scripts ` { "scripts": { "tasks": "brainfile list", "tasks:lint": "brainfile lint --fix", "precommit": "brainfile lint --check" } } `` --- Next Steps - CLI & TUI Guide — Getting started with the CLI - MCP Server — AI assistant integration - Protocol Specification — File format details --- ## 13. Contract Schema Reference Contract Schema Reference The Contract object is an optional extension to a Brainfile task. It defines the formal agreement between a requester (PM) and a worker (Agent). Source of Truth: contract.json ::: tip See also For a field-by-field walkthrough with examples, see Types → Contract. ::: Object Structure | Field | Type | Description | Required | |-------|------|-------------|----------| | status | string | Current lifecycle state (see below) | Yes | | deliverables | Array<Deliverable> | List of items to be produced | No | | validation | Validation | How to verify the work | No | | constraints | Array<string> | Implementation rules to follow | No | | outOfScope | Array<string> | Explicitly out-of-scope items | No | | feedback | string | PM feedback after failed validation | No | | version | integer | Contract version (incremented on amendment) | No | | metrics | Metrics | Auto-tracked timing and rework data | No | Lifecycle Status (status) Contracts follow a strict state machine to coordinate between different agents. - 🔵 ready: Work is defined and available for an agent to pick up. - 🟡 in_progress: An agent has claimed the task and is working on it. - 🟣 delivered: Work is completed and submitted for validation. - 🟢 done: Work has passed validation and is finalized. - 🔴 failed: Work failed validation or was abandoned. - ⚠️ blocked: Agent is stuck on an external dependency. <StateMachine /> Deliverable Object Each item in the deliverables array defines a specific output. | Field | Type | Description | |-------|------|-------------| | type | string | Category (e.g., file, test, docs, refactor) | | path | string | Path to the file or identifier for the deliverable | | description| string | (Optional) Human-readable explanation | Validation Object | Field | Type | Description | |-------|------|-------------| | commands | Array<string> | Shell commands to execute for validation | Metrics Object Auto-tracked by the CLI. Do not manually edit. | Field | Type | Description | |-------|------|-------------| | pickedUpAt | string | ISO 8601 timestamp when agent picked up | | deliveredAt | string | ISO 8601 timestamp when agent delivered | | duration | number | Seconds between pickup and delivery | | reworkCount | number | Times contract was re-picked up after failure | --- Example (YAML) In a v2 task file (.brainfile/board/task-63.md): ::: info Task metadata The task's own fields (description, relatedFiles, assignee) provide context. The contract focuses on deliverables and validation. ::: `` --- id: task-63 type: task title: "Update API documentation" column: todo assignee: codex relatedFiles: - src/routes/api.ts contract: status: ready version: 1 deliverables: - type: docs path: docs/api-v2.md description: "Updated REST endpoints" validation: commands: - npm run docs:verify constraints: - Use Swagger/OpenAPI 3.0 format - Document all error codes outOfScope: - Changing the authentication logic --- Description Preparing for the Q3 mobile app release. ` ::: info Key fields explained - deliverables — Exact file paths the agent must produce. The PM validates these exist. - validation.commands — Shell commands run automatically during contract validate. - constraints — Implementation rules the agent must follow (not validated automatically). - outOfScope — Prevents scope creep by explicitly excluding items. ::: ::: tip Full walkthrough For a step-by-step guide to creating, assigning, and validating contracts, see the Contracts Guide. ::: ::: info v2 changes In v2, context.background moved to task.description and context.relevantFiles moved to task.relatedFiles. The context` object is deprecated. ::: --- ## 14. Schema Types Schema Types Brainfile uses JSON Schema to define the structure of board configuration and task files. Available Schemas | Schema | v2 URL | Purpose | |--------|--------|---------| | Base | /v2/base.json | Shared fields (title, agent, rules) | | Board | /v2/board.json | Board configuration (columns, types) | | Task | /v2/task.json | Standalone task documents | | Contract | /v2/contract.json | Task contract object (task.contract) | | Epic | /v2/epic.json | Epic documents (groups related tasks) | | ADR | /v2/adr.json | Architecture Decision Records | ::: tip Extensible by design These are the built-in types, but Brainfile is not limited to them. You can define your own schema types for any use case — bug, rfc, spike, incident, whatever fits your workflow. Just set type: your-type in the frontmatter and optionally point schema: to your own JSON Schema URL. ::: Board (Default) Board configuration defines columns, document types, and project rules. Tasks are standalone files in .brainfile/board/. `` --- type: board schema: https://brainfile.md/v2/board.json title: My Project columns: - id: todo title: To Do - id: in-progress title: In Progress types: epic: idPrefix: epic completable: false --- ` ::: tip Minimal Board ` --- type: board title: My Project columns: - id: todo title: To Do --- ` Only title and one column are required. ::: View Board Schema · Example Task Standalone task documents with YAML frontmatter and optional markdown body. Each task is an individual .md file in .brainfile/board/ (active) or .brainfile/logs/ (completion history). ` --- id: task-1 title: Implement feature column: todo priority: high tags: [backend] assignee: codex parentId: epic-1 --- ` ::: tip Minimal Task ` --- id: task-1 title: Fix login bug column: todo --- ` Only id, title, and column are required. ::: View Task Schema · Docs Contract (Task Extension) Task contracts define structured deliverables, validation commands, and constraints for PM-to-agent workflows. Embedded in the contract field of a task file. ` contract: status: ready deliverables: - type: file path: src/feature.ts description: Implementation validation: commands: - npm test ` ::: tip Minimal Contract ` contract: status: ready ` Only status is required — deliverables and validation are optional. ::: View Contract Schema · Docs Parent-Child Relationships Any document can be a parent or child of any other document using parentId. The parent tracks its children with a children array, and each child points back with parentId. This is not limited to epics — you can nest tasks under tasks, ADRs under epics, or any combination that fits your workflow. ` Parent: a regular task --- id: task-10 title: Refactor auth module column: in-progress children: [task-11, task-12, task-13] --- Child: points back to parent --- id: task-11 title: Extract token validation column: todo parentId: task-10 --- ` Epic A common pattern for grouping related work. Epics extend the task schema with children and status fields, but any type can serve as a parent. ` --- id: epic-1 type: epic title: Authentication System column: in-progress children: [task-1, task-3, task-4] status: active --- ` ::: tip Minimal Epic ` --- id: epic-1 type: epic title: Authentication System column: todo --- ` children and status are optional — add them as tasks are created. ::: View Epic Schema ADR Architecture Decision Records with lifecycle status and supersession tracking. Extends the task schema. ` --- id: adr-1 type: adr title: Use Postgres for user data column: todo status: proposed --- ` ::: tip Minimal ADR ` --- id: adr-1 type: adr title: Use Postgres for user data column: todo --- ` status defaults to proposed if omitted. ::: View ADR Schema Base Schema All brainfile config files inherit from the base schema which defines shared fields: ` --- title: string # Required type: string # Optional (defaults to board) schema: string # Optional JSON schema URL protocolVersion: string # Optional version string agent: identity: string # System prompt identity instructions: [] llmNotes: string tools: {} rules: always: [] never: [] prefer: [] context: [] --- ` ::: tip Vendor Extensions The protocol supports arbitrary vendor extensions using the x-* naming convention (e.g., x-otto: {}). - Opaque processing: Internal keys are preserved and never transformed. - Round-tripping: Unknown fields are guaranteed to survive parse-serialize cycles. ::: ::: tip Minimal Base ` --- title: My Project --- ` Only title is required — everything else has sensible defaults. ::: View Base Schema Type Inference When type is not specified, tools determine the type by: Schema URL — /v2/board.json → board Filename suffix — project.board.md → board Structural analysis — columns[]` present → board Default → board Schema Directories | Version | URL | Status | |---------|-----|--------| | v2 | brainfile.md/v2/ | Current | Next Steps - Protocol Specification — File format details - API Reference — Library documentation - Core Library — Build custom tools --- ## 15. Complete Example Example v2 workspace from protocol/example/.brainfile/: Files: - .brainfile/brainfile.md - .brainfile/board/adr-1.md - .brainfile/board/epic-1.md - .brainfile/board/task-1.md - .brainfile/logs/task-2.md ### .brainfile/brainfile.md ```markdown --- type: board title: Brainfile v2 Example Board schema: https://brainfile.md/v2/board.json protocolVersion: 2.0.0 strict: true agent: instructions: - Use the CLI or MCP tools for task operations when available - Preserve all IDs and unknown fields - Update task column as you work (todo → in-progress → review → done) - Use contracts when handing work off to another agent llmNotes: | This is an example Brainfile v2 workspace. - Board config lives in .brainfile/brainfile.md - Active docs live in .brainfile/board/ - Completed docs live in .brainfile/logs/ rules: always: - id: 1 rule: Write tests for bug fixes and new features - id: 2 rule: Keep tasks small and independently completable never: - id: 1 rule: Change or regenerate existing task IDs prefer: - id: 1 rule: Store context in task.description and files in task.relatedFiles context: - id: 1 rule: This repo uses TypeScript and Node types: epic: idPrefix: epic completable: false schema: https://brainfile.md/v2/epic.json adr: idPrefix: adr completable: false schema: https://brainfile.md/v2/adr.json columns: - id: todo title: To Do order: 1 - id: in-progress title: In Progress order: 2 - id: review title: Review order: 3 - id: done title: Done order: 4 completionColumn: true --- # Example Workspace This folder demonstrates the v2 layout: - `.brainfile/brainfile.md` (this file) - `.brainfile/board/` (active task/epic/adr files) - `.brainfile/logs/` (completed task files) ``` ### .brainfile/board/adr-1.md ```markdown --- id: adr-1 type: adr title: Use token bucket for rate limiting column: review tags: [architecture, backend] status: accepted --- ## Decision Use a token bucket algorithm per provider. ## Rationale - Allows bursts while enforcing an average rate - Simple to reason about and test ## Consequences - Requires tracking bucket state per provider key - Needs careful clock/timer handling to avoid drift ``` ### .brainfile/board/epic-1.md ```markdown --- id: epic-1 type: epic title: Improve API reliability column: todo priority: medium tags: [backend, reliability] status: active children: - task-1 - adr-1 --- ## Goal Reduce outages and improve resilience for API traffic spikes. ``` ### .brainfile/board/task-1.md ```markdown --- id: task-1 type: task title: Implement rate limiting column: in-progress priority: high effort: medium assignee: codex tags: [backend, api] relatedFiles: - src/api/gateway.ts - src/middleware/rateLimit.ts subtasks: - id: sub-1 title: Add token bucket implementation completed: true - id: sub-2 title: Add unit tests completed: false contract: status: in_progress version: 1 deliverables: - type: file path: src/rateLimiter.ts description: Token bucket rate limiter - type: test path: src/__tests__/rateLimiter.test.ts description: Unit tests for limiter behavior validation: commands: - npm test -- rateLimiter - npm run build constraints: - Use token bucket algorithm - Keep implementation non-blocking (async) outOfScope: - UI for rate limit settings --- ## Context We need to protect upstream providers from bursty traffic and avoid quota exhaustion. ## Notes - Prefer per-provider buckets - Include clear error messages when rejecting requests ``` ### .brainfile/logs/task-2.md ```markdown --- id: task-2 type: task title: Add CI validation for brainfile priority: medium tags: [ci, tooling] completedAt: "2026-02-01T12:00:00Z" contract: status: done version: 1 deliverables: - type: file path: .github/workflows/validate.yml description: CI workflow that runs brainfile lint and tests validation: commands: - npx @brainfile/cli lint --check metrics: pickedUpAt: "2026-02-01T10:00:00Z" deliveredAt: "2026-02-01T11:00:00Z" validatedAt: "2026-02-01T12:00:00Z" duration: 3600 reworkCount: 0 --- Completed and validated. ``` --- ## Support & Resources - **Website**: https://brainfile.md - **Quick Reference**: https://brainfile.md/llms.txt - **Schema**: https://brainfile.md/v2 - **GitHub**: https://github.com/brainfile - **Issues**: https://github.com/brainfile/protocol/issues - **Discussions**: https://github.com/brainfile/protocol/discussions --- End of Complete Reference Auto-generated from markdown documentation