# Brainfile - 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-08-13
---
## Table of Contents
1. Quick Start Guide
2. Getting Started with Contracts
3. Comprehensive Guide to Contracts
4. Agent Workflow Patterns
5. CLI & Terminal UI
6. MCP Server Integration
7. Core Library
8. Board Format Reference
9. API Reference
10. CLI Commands Reference
11. Contract Schema Reference
12. Schema Types
---
## 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
`
Initialize
`
brainfile init
`
This creates the .brainfile/ directory with:
- .brainfile/brainfile.md — Board configuration (columns, types)
- .brainfile/board/ — Active task files
- .brainfile/logs/ — Completion history (ledger.jsonl) and archives
.brainfile/
├── brainfile.md ← Board config (columns, types)
├── 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 to move, Enter for detail, ? for help, 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", "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
- Getting Started with Contracts — Define deliverables for AI agents
- CLI Commands — Full command reference and TUI guide
- MCP Integration — Connect your AI assistant directly
- Board Format Reference — File format and schema details
---
## 2. 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.
---
## 3. 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.
- maxRetries: Optional number of automatic retry attempts when validation fails. When set, failed validation auto-resets the contract to ready and re-dispatches to the agent.
- 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. |
Auto-Retry on Validation Failure
When contract.maxRetries is set and validation fails, the system automatically:
Captures feedback: Validation command output is written to contract.feedback
Increments retry count: contract.metrics.reworkCount is incremented
Checks retry limit: If reworkCount < maxRetries, proceed to step 4; otherwise, status remains failed
Resets status: Contract status changes back to ready
Re-dispatches: Task is automatically dispatched to the assigned agent with feedback
Example contract with auto-retry:
`
contract:
status: ready
maxRetries: 3
deliverables:
- path: src/feature.ts
validation:
commands:
- npm test -- feature
metrics:
reworkCount: 0
`
Retry flow:
Agent delivers → Validation runs → Test fails
System captures test output in feedback
System increments reworkCount to 1
Since 1 < 3 (maxRetries), status resets to ready
Agent is re-dispatched with the failure feedback
Agent fixes issue and delivers again
If validation passes: status → done. If fails again: repeat steps 2-6 until reworkCount >= maxRetries
Manual retry override:
Even if maxRetries is exceeded, the PM can force another attempt by resetting the contract status to ready (edit the task's YAML), letting the agent deliver again, and re-running:
`
brainfile contract validate --task task-1
`
::: warning Retry Accounting
The reworkCount is incremented during validation failure checks. With maxRetries: 3, you get up to 3 rework cycles (initial attempt + 3 retries = 4 total validation attempts).
:::
---
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 — Field-by-field reference
- Getting Started — 2-minute intro
---
## 4. 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
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 brainfile itself — the same task board that tracks your features can track improvements to the coordination layer.
---
## 5. 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
`
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
One list at a time, one column at a time. The header shows every column with a live count; * marks the column you are in. On a wide terminal, Enter opens a detail pane beside the list. On a narrow terminal, detail replaces the list until you press Esc.
Completed work is not a column. Press L to toggle the done view (logs/).
Keyboard Controls
::: tip Keyboard Quick Reference
| Key | Action |
|-----|--------|
| j / k or ↑ / ↓ | Move selection |
| h / l or Tab | Cycle column |
| Enter | Open detail (Enter on a child drills in) |
| esc | Back / clear filter |
| t | Cycle document type (task, epic, spec, plan, adr) |
| L | Toggle done view (completed logs/) |
| space | Collapse a parent, or toggle a subtask in detail |
| a / n | Add a document (title only) |
| N | Add, then open in $EDITOR |
| m | Move to a column |
| c | Complete |
| e | Edit the document in $EDITOR |
| p | Cycle priority (list) or jump to parent (detail) |
| d | Delete (list) or scroll the body (detail) |
| / | Filter (p:, #, @, type:, contract:, due:) |
| ? | Help |
| 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 (checks deliverables, runs commands, and on success archives to logs/ + ledger.jsonl)
See the Agent Contracts Guide for the full lifecycle and best practices.
:::
---
Archive & Restore
`
Complete locally (ledger + logs/.md) — same as brainfile complete
brainfile archive --task task-5
Export an already-completed task to GitHub or Linear
brainfile archive --task task-5 --to github
Restore from a v1 archive file (not logs/)
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
---
## 6. 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", "mcp"]
}
}
}
`
:::
::: tip Custom Path Setup
For a specific brainfile path:
`
{
"mcpServers": {
"brainfile": {
"command": "npx",
"args": ["brainfile", "mcp", "-f", "path/to/brainfile.md"]
}
}
}
`
:::
::: warning
Restart your AI assistant after adding or changing MCP configuration.
:::
---
Available Tools
The MCP server registers 11 tools. Several are action-based or accept arrays, so a single tool covers what would otherwise be many — task_move and task_patch accept one task ID or an array (bulk), subtask and contract dispatch on an action parameter.
Task Management
| Tool | Key parameters | Description |
|------|----------------|-------------|
| list_tasks | column?, tag?, type?, file? | List tasks, optionally filtered by column, tag, or document type |
| get_task | task, file? | Get detailed information about a specific task by ID |
| search | query?, column?, priority?, assignee?, recent?, task?, file? | Search tasks and logs, list recent completions (recent: true), or view one entry (task) |
| task_add | column, title, description?, priority?, tags?, assignee?, dueDate?, subtasks?, relatedFiles?, type?, parentId?, with_contract?, ready?, deliverables?, validation_commands?, constraints? | Create a task; optionally attach a contract in the same call |
| task_move | taskId (string or array), column, file? | Move one task or many to a column. Moving to a completionColumn auto-completes |
| task_patch | taskId (string or array), title?, description?, priority?, tags?, assignee?, dueDate?, relatedFiles?, parentId? | Update fields on one or many tasks. Pass null to remove a field |
| task_delete | task, file? | Permanently delete a task |
| task_complete | task, destination? (local/github/linear), file? | Complete a task (append to ledger.jsonl and archive), or archive to GitHub/Linear |
::: tip Bulk operations
There are no separate bulk_ tools. Pass an array of IDs to task_move or task_patch to act on multiple tasks at once — the response reports successCount/failureCount and per-task results.
:::
Subtasks — subtask
A single action-based tool. Set action to add, toggle, delete, or update.
| Parameter | Applies to | Description |
|-----------|------------|-------------|
| action | all | add \| toggle \| delete \| update |
| task | all | Parent task ID |
| subtask / subtasks | all | One ID/title or an array, depending on action |
| title / titles | update | New title(s) |
| completed | toggle | Set explicit state instead of flipping |
| all | toggle, delete | Target every subtask in the task |
Agent Briefs — brief
Per-agent attention primitive: "what changed that I should care about?" State is
per agent, stored locally in .brainfile/state/.json (gitignored).
| Tool | Key parameters | Description |
|------|----------------|-------------|
| brief | agent, peek?, file? | Get what changed for one agent since its last brief |
The first call for an agent returns a full orientation (agent instructions,
accepted ADRs and
instructions, assigned tasks, latest notes, recent completions). Every later call
returns a delta: new notes, task changes, completions, and whether the board
config changed. Pass peek: true to read without marking the brief as seen.
Notes are detected independently of updatedAt, because adding a note does not
bump it. Contract states are reported as current truth — Brainfile records no
prior status, so a brief never claims a transition it cannot know.
Agent Contracts — contract
A single action-based tool. Set action to attach, pickup, deliver, validate, graph, or activate.
| Action | Parameters | Description |
|--------|------------|-------------|
| attach | task, deliverables?, validation_commands?, constraints?, ready? | Attach a contract (default status draft; ready: true for immediate dispatch) |
| pickup | task | Claim a contract (status → in_progress); returns agent context markdown |
| deliver | task | Mark contract delivered (status → delivered) |
| validate | task | Check deliverables and run validation commands (status → done/failed) |
| graph | tasks (array with dependsOn), activate? | Attach contracts to multiple tasks atomically with DAG edges |
| activate | task or parentId | Flip draft → ready for one task or all children of a parent |
Contract workflow:
PM creates a task with a contract using task_add (with with_contract, deliverables, validation_commands, constraints), or attaches one later with contract action: attach.
Worker calls contract action: pickup to claim the work.
Worker implements the deliverables.
Worker calls contract action: deliver when done.
PM calls contract action: validate to check the work.
::: info Ledger queries are library API, not MCP tools
Completion history (ledger.jsonl) is queried through the @brainfile/core library (queryLedger, getFileHistory, getTaskContext, readLedger), not through dedicated MCP tools. From an assistant, use the search tool with recent: true to list recent completions. See Ledger Query API.
:::
---
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 task_move "I've moved task-3 to Done."
---
You: "Create a task for the performance issue we discussed"
Assistant: calls task_add* "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 is installed: npx brainfile --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", "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
- Board Format Reference — Complete file format and YAML structure
- Core Library — Build custom integrations with @brainfile/core`
- Contract Guide — Deep dive into the contract lifecycle and best practices
---
## 7. 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
- Board Format Reference — 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
---
## 8. Board Format Reference
Board Format
This is the file format brainfile runs on: project work stored as Markdown files with YAML frontmatter, validated against the JSON schema that ships inside the CLI. Everything the CLI, TUI, and MCP server do reads and writes this format.
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.
:::
---
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
---
`
::: 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 | Board format version |
| strict | boolean | No | Enforce type validation |
| types | object | No | Custom document types |
| agent | object | No | AI agent instructions |
| 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 (removed)
rules was removed by adr-2. Project guidance belongs in agent.instructions,
which is the block agents are already told to read.
Legacy files are still accepted: a rules: block parses without error, and
brainfile lint --fix folds each entry into agent.instructions (prefixed by
its former category) and removes the block.
---
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
- 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 field reference
---
## 9. 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.
---
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;
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 (removed)
::: warning Removed in v2
The Rules and Rule interfaces were removed by adr-2 and are no longer
exported from @brainfile/core or @brainfile/core/browser. The rules field
is gone from Board, BoardConfig, and Journal, and the addRule,
deleteRule, and findRuleLocation methods no longer exist.
Project guidance now lives in AgentInstructions, which
agents already read.
A legacy rules: block still parses without error, and brainfile lint warns
about it. brainfile lint --fix folds each entry into agent.instructions,
prefixed by its old category, and removes the block.
:::
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
- Board Format Reference — File format details
- CLI Commands — Command-line interface
- Core Library Guide — Usage examples
---
## 10. 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 | Complete locally, or export completed work to GitHub/Linear |
| 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 |
| types | Document type management |
| search | Search tasks and logs |
| brief | Per-agent delta orientation |
| log | View completed task logs |
| note | Append a timestamped note to a task log |
| 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 | Path to brainfile file (default: .brainfile/brainfile.md) |
| --force | Overwrite existing file |
---
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 file (auto-detect by default) |
| -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) |
---
show
Display full details of a single task.
`
brainfile show --task task-1
brainfile show -t task-42
`
Options:
| Option | Description |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to show (required) |
| --json | Output task data as JSON |
---
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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -c, --column | Column to add task to (default: todo) |
| -t, --title | Task title (required) |
| -d, --description | Task description |
| -p, --priority | Priority level (low, medium, high, critical) |
| --tags | Comma-separated tags |
| --assignee | Assignee name |
| --due-date | Due date (YYYY-MM-DD) |
| --subtasks | Comma-separated subtask titles |
| --files | Comma-separated related file paths |
| --type | Document type (e.g., epic, adr); determines ID prefix |
| --parent | Parent task ID (sets parentId on the new task file) |
| --child | Create a child task under the new parent (repeatable) |
| --with-contract | Attach a draft contract |
| --ready | With --with-contract: set contract status: ready instead of draft |
| --deliverable | Contract deliverable type:path:description (repeatable) |
| --validation | Contract validation command (repeatable) |
| --constraint | 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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to move (required) |
| -c, --column | Target column name or ID (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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to update (required) |
| --title | New task title |
| -d, --description | New task description |
| -p, --priority | Priority (low, medium, high, critical, or none to remove) |
| --tags | Comma-separated tags (replaces existing) |
| --assignee | Assignee name |
| --due-date | Due date (YYYY-MM-DD) |
| --clear-tags | Remove all tags |
| --clear-assignee | Remove assignee |
| --clear-due-date | Remove due date |
| --clear-priority | Remove priority |
---
delete
Permanently delete a task. Requires confirmation.
`
brainfile delete --task task-1 --force
`
Options:
| Option | Description |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to delete (required) |
| --force | Confirm deletion (required) |
---
archive
Complete a task locally (same as brainfile complete: ledger + logs/.md), or export an already-completed task from logs/ to GitHub Issues or Linear.
`
brainfile archive --task task-1 # complete locally
brainfile archive --task task-1 --to github # export from logs/ to GitHub
brainfile archive --all --to linear --dry-run
`
If the task is already in logs/, a local archive tells you so and points at --to github|linear for export.
Options:
| Option | Description |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to complete or export |
| --to | local (default, completes the task), github, or linear |
| --all | Export all completed tasks from logs/ to GitHub or Linear |
| --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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to restore (required) |
| -c, --column | Target column name or ID (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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Parent task ID (required) |
| --add | Add a new subtask |
| --delete | Delete a subtask |
| --update | Update a subtask (requires --title) |
| --toggle | Toggle subtask completion |
| --title | 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 to brainfile file (auto-detect by default) |
| --fix | Automatically fix issues when possible |
| --check | Exit with error code if issues found (for CI/CD) |
---
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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -l, --list | List all available templates |
| -u, --use | Create task from template |
| --title | Task title (for template usage) |
| --description | Task description (for template usage) |
| -c, --column | Column to add task to (default: todo) |
---
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 |
|-----|--------|
| j / k or ↑ / ↓ | Move selection |
| h / l or Tab | Cycle column |
| Enter | Open detail (Enter on a child drills in) |
| esc | Back / clear filter |
| t | Cycle document type (task, epic, spec, plan, adr) |
| L | Toggle done view (completed logs/) |
| space | Collapse a parent, or toggle a subtask in detail |
| a / n | Add a document (title only) |
| N | Add, then open in $EDITOR |
| m | Move to a column |
| c | Complete |
| e | Edit the document in $EDITOR |
| p | Cycle priority (list) or jump to parent (detail) |
| / | Filter |
| ? | Help |
| 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 | Installation scope: user or project (uninstall also accepts 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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID (required) |
| --force | Force epic completion even if child tasks are still active |
::: info Auto-Completion Cascade
When a task is completed:
Parent auto-completion: If this task is a child and all sibling tasks are also complete, the parent task auto-completes
Dependency unblocking: Tasks blocked by this task (via blockedBy) become unblocked
Auto-dispatch: Newly unblocked tasks with contracts are automatically dispatched to their assigned agents
This creates a cascading execution flow where completing one task can trigger the next phase of work automatically.
:::
---
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 (default status draft) |
| graph | Attach contracts to multiple tasks as a dependency graph |
| activate | Activate one or more draft contracts (draft → ready) |
Common Options:
| Option | Description |
|--------|-------------|
| -t, --task | Task ID (required) |
| -f, --file | Path to brainfile (auto-detects .brainfile/brainfile.md) |
Attach Options:
| Option | Description |
|--------|-------------|
| --ready | Set contract status: ready instead of draft |
| --deliverable | Add deliverable (format: type:path:description) |
| --validation | Add validation command (repeatable) |
| --constraint | Add constraint (repeatable) |
::: info Auto-Retry on Validation Failure
If contract.maxRetries is set and validation fails, the system automatically:
Captures validation output as feedback in contract.feedback
Resets contract status to ready
Re-dispatches the task to the agent for rework
:::
See the Contract Commands Reference for detailed documentation.
---
adr
Manage Architecture Decision Records.
`
brainfile adr promote -t adr-1
`
Promoting marks the ADR accepted and moves it to logs/. Accepted ADRs appear
in the board lane of brainfile brief.
Options (promote):
| Option | Description |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | ADR task ID to promote (required) |
---
types
Inspect and manage board document types.
`
brainfile types list
brainfile types add epic --completable true --id-prefix epic
`
---
brief
Per-agent orientation: what changed that this agent should care about.
The first call for an agent is a full orientation (board title, agent.instructions, accepted ADRs, assigned tasks, latest notes, recent completions). Later calls are a delta against that agent's checkpoint in .brainfile/state/.json (gitignored). --peek reads without advancing the checkpoint.
`
brainfile brief --agent codex
brainfile brief --agent codex --peek
brainfile brief --agent codex --json
`
Options:
| Option | Description |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| --agent | Agent identifier (required — state is per-agent) |
| --peek | Read without marking the brief as seen |
| --json | Machine-readable {version, kind, data} envelope |
---
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 |
|--------|-------------|
| -f, --file | Path to brainfile file (auto-detect by default) |
| -t, --task | Task ID to add note to (required) |
| --agent | Agent name for attribution |
---
migrate
Move root brainfile.md to .brainfile/ directory structure.
`
brainfile migrate
brainfile migrate --dir ./project
brainfile migrate --force
`
Options:
| Option | Description |
|--------|-------------|
| --dir | Directory containing legacy brainfile files (default: cwd) |
| --force | Overwrite existing migration outputs (task files/backups) |
| --logs-to-ledger | Migrate logs/.md files into ledger.jsonl |
---
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 config values |
| get | Get a specific config value |
| set | Set a config value |
| path | Show config file path |
---
auth
Authenticate with external services for archive functionality.
`
brainfile auth github
brainfile auth linear --token
brainfile auth status
brainfile auth logout github
`
Subcommands:
| Command | Description |
|---------|-------------|
| github | Authenticate with GitHub (--token or OAuth device flow) |
| linear | Authenticate with Linear (--token required) |
| status | Show authentication status for all providers |
| logout [provider] | Log out from a provider (github, linear, or --all) |
---
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 to brainfile file (auto-detect by default) |
---
Global Options
| Option | Description |
|--------|-------------|
| -V, --version | Output the version number |
| -h, --help | Display help for a command |
| -f, --file | Most commands accept a brainfile path (auto-detects .brainfile/brainfile.md by default) |
---
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 lint --check
`
Pre-commit Hook
`
#!/bin/bash
.git/hooks/pre-commit
if [ -f "brainfile.md" ]; then
npx brainfile 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
- Board Format Reference — File format details
---
## 11. 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 | List of items to be produced | No |
| validation | Validation | How to verify the work | No |
| constraints | Array | Implementation rules to follow | No |
| outOfScope | Array | 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.
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 | 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.
:::
---
## 12. 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) |
| 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 and document types. 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
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: {}
---
`
::: tip Vendor Extensions
The schema 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
- Board Format Reference — File format details
- API Reference — Library documentation
- Core Library — Build custom tools
---
---
## Support & Resources
- **Website**: https://brainfile.md
- **Quick Reference**: https://brainfile.md/llms.txt
- **Schema**: https://brainfile.md/v2
- **GitHub**: https://github.com/1broseidon/brainfile
- **Issues**: https://github.com/1broseidon/brainfile/issues
- **Discussions**: https://github.com/1broseidon/brainfile/discussions
---
End of Complete Reference
Auto-generated from markdown documentation