Context hub for agentic workflows - manage projects, tasks, sessions, and multi-agent coordination

version
0.5.1
GitHub stars
20

Install

/plugin install granary@granary

Run it inside Claude Code after adding the marketplace with /plugin marketplace add speakeasy-api/granary.

Contents

Discovered from source

Skills 5

Executing a Granary Task

You are a sub-agent spawned by an orchestrator to complete a specific task. Your responsibility is to:

  1. Build context from the task
  2. Implement the task as described
  3. Report your progress
  4. Signal completion or blockers back to the orchestrator

You do NOT coordinate other agents. You do the actual work.

Step 1: Build Context from the Task

First, use granary handoff to retrieve full context for your task:

granary handoff --tasks <task-id>

This returns:

  • Task description with goals, requirements, and acceptance criteria
  • Files to modify with exact paths and line numbers
  • Implementation details including code patterns to follow
  • Steering files attached to the task or its parent project
  • Global steering with project-wide conventions

Read this context carefully. The planner has done thorough research and provided everything you need. The handoff context is your primary source of truth.

Understanding the Handoff Output

The handoff includes:

SectionContains
Task DetailsGoal, context, requirements, acceptance criteria
Files to ModifyExact file paths with line numbers
Implementation DetailsCode examples, patterns, function signatures
Steering FilesProject conventions, existing patterns, research notes

If the handoff mentions specific files like src/services/user.rs:45-67, read those files to understand the existing patterns before making changes.

Verify Task Metadata (Optional)

If you need the raw task data:

granary show <task-id>
# or
granary task <task-id>

Use this to double-check task metadata (priority, dependencies, status).

Step 2: Start the Task

Mark the task as in-progress:

granary task <task-id> start

If working in a multi-agent environment, claim with a lease to prevent conflicts:

granary task <task-id> start --lease 30

The lease (in minutes) ensures no other agent claims this task while you work.

Step 3: Do the Work

This is your main responsibility. Implement whatever the task description specifies:

  • Write code
  • Create files
  • Run tests
  • Fix bugs
  • Whatever the task requires

Record Progress

Add comments as you work to maintain visibility for the orchestrator:

granary task <task-id> comments create "Started implementing the login form"
granary task <task-id> comments create "Completed form validation, now adding API integration" --kind progress

Comment kinds: note, progress, decision, blocker

Step 4: Report Completion

When you have successfully completed the task:

granary task <task-id> done --comment "Implemented login form with validation and API integration"

Important: Only mark done when the task is truly complete according to its acceptance criteria.

Handling Problems

If You Get Blocked

If you cannot continue due to external factors:

granary task <task-id> block --reason "Waiting for API credentials from ops team"

This signals to the orchestrator that this task needs attention.

If You Cannot Complete

If you cannot complete the task for any reason, release it so others can pick it up:

granary task <task-id> release

Then report back to the orchestrator with what went wrong.

Multi-Agent Safety

If working in parallel with other agents:

# Extend lease for long-running tasks
granary task <task-id> heartbeat --lease 30

# Check if task is still yours
granary task <task-id>

Exit codes to watch for:

  • 4 = Conflict (task claimed by another agent)
  • 5 = Blocked (dependencies not met)

Summary

As a sub-agent, your workflow is:

  1. Build context → granary handoff --tasks <id> to get full task details with steering
  2. Read referenced files → Examine files mentioned in handoff (e.g., src/foo.rs:45-67)
  3. Start task → granary task <id> start
  4. Do the work → Implement following the patterns and details provided
  5. Record progress → granary task <id> comments create "..."
  6. Complete or block → granary task <id> done or granary task <id> block

Remember: The planner has done thorough research. Your handoff context contains file paths, implementation details, and code patterns. Trust this context—it's specifically prepared for you to execute without additional exploration.

Planning Multi-Project Initiatives

Use this skill when work naturally spans multiple projects or services. Do NOT use for single-feature work—use /granary:plan-work instead.

Your role: High-level architecture, separation of concerns, dependency analysis, and spawning sub-agents for project planning. You do NOT plan individual project tasks yourself—you coordinate and synthesize.

Your Focus as Initiative Planner

You are a high-level coordinator. Your job is to:

  1. Collect broad context before any planning begins
  2. Design the project structure with clear boundaries
  3. Spawn sub-agents to handle detailed project planning
  4. Synthesize cross-project dependencies from sub-agent reports

You do NOT:

  • Plan detailed tasks within projects (sub-agents do this)
  • Implement anything directly
  • Make low-level technical decisions

When to Use Initiatives

Use initiatives when:

  • Work spans multiple services (API + frontend + workers)
  • Implementation has clear phases with dependencies (schema -> API -> UI)
  • Multiple teams or agents will work in parallel on different components
  • You need to track cross-project dependencies

Do NOT use initiatives when:

  • Work fits in a single project
  • There are no cross-project dependencies
  • It's a single feature in one service

Step 1: Comprehensive Context Collection

This is your most important step. Before creating an initiative, gather broad context to inform the entire planning process. You are building the foundation that sub-agents will rely on.

1.1 Search for Prior Art

# Search granary for related existing work
granary search "feature keywords"
granary initiatives  # Check existing initiatives
granary projects     # See all projects

1.2 Understand Current Implementation

Research the codebase at a high level:

  • What services/modules exist that will be affected?
  • What boundaries already exist in the architecture?
  • What shared dependencies or interfaces might be needed?
  • What are the current limitations of the system?
# Example: understand existing architecture
ls -la src/
grep -r "mod " src/lib.rs
cat README.md

1.3 Gather External Context

Use web search and documentation lookup to understand:

  • Industry best practices for similar features
  • Framework/library documentation for relevant technologies
  • Potential pitfalls or known issues others have encountered

This external research provides valuable context that sub-agents will benefit from when planning their projects.

1.4 Document Limitations and Constraints

Before proceeding, document:

  • Technical limitations of the current system
  • Resource or time constraints
  • Dependencies on external systems or teams
  • Known risks or uncertainties

1.5 Decision Tree

SituationAction
Work fits in one projectUse /granary:plan-work instead
Related initiative existsAdd projects to existing initiative
Work spans 2+ distinct projects with dependenciesCreate new initiative

Step 2: Create the Initiative

granary initiatives create "Initiative Name" \
  --description "High-level goal spanning multiple projects"

Example:

granary initiatives create "User Authentication System" \
  --description "Implement auth across API, web app, and mobile app with shared token service"

Step 3: Design Separation of Concerns

Break the initiative into logical projects. Each project should:

  • Be independently implementable (given its dependencies)
  • Have a clear boundary (service, module, or phase)
  • Be completable by a single agent

Think carefully about:

  • What depends on what? Which components need to exist before others can start?
  • What can run in parallel? Which projects have no dependencies on each other?
  • Where are the interfaces? What contracts need to be defined between projects?

Example breakdown:

Initiative: User Authentication System
├── Project: Auth Token Service (shared backend) — no deps, can start first
├── Project: API Auth Integration — depends on token service
├── Project: Web App Login — depends on API auth
└── Project: Mobile App Login — depends on API auth (parallel with Web App)

Step 4: Create Projects and Add to Initiative

# Create each project with clear descriptions for sub-agents
granary projects create "Auth Token Service" \
  --description "JWT token generation and validation service"
# Output: auth-token-service-abc1

granary projects create "API Auth Integration" \
  --description "Add authentication middleware to API endpoints"
# Output: api-auth-integration-def2

# Add projects to initiative
granary initiative <initiative-id> add-project auth-token-service-abc1
granary initiative <initiative-id> add-project api-auth-integration-def2

Step 5: Analyze and Set Up Project Dependencies

This is critical. Review each project pair and ask:

  • Does project A need anything from project B to start?
  • Does project B produce interfaces/APIs that project A consumes?
  • Are there shared schemas or contracts that must exist first?
# API Auth depends on Token Service being complete
granary project api-auth-integration-def2 deps add auth-token-service-abc1

# Web App depends on API Auth
granary project web-app-login-ghi3 deps add api-auth-integration-def2

Key principle: A project is blocked until ALL its dependency projects have ALL tasks done.

Step 6: Verify the Dependency Structure

Before spawning sub-agents, verify the structure makes sense:

# View the initiative dependency graph
granary initiative <initiative-id> graph

# View as mermaid diagram (paste into GitHub/VSCode)
granary initiative <initiative-id> graph --format mermaid

# Check overall status
granary initiative <initiative-id> summary

Review the graph for:

  • Circular dependencies (error)
  • Missing dependencies (projects that should depend on each other but don't)
  • Overly sequential structure (could more projects run in parallel?)

Step 7: Spawn Sub-Agents for Project Planning

Do NOT plan project tasks yourself. Spawn sub-agents to handle detailed project planning. Each sub-agent focuses deeply on one project while you maintain the high-level view.

7.1 Get Projects Ready for Planning

# Get all projects in the initiative
granary initiative <initiative-id> projects

# Identify which projects are unblocked (no project dependencies)
granary initiative <initiative-id> graph

7.2 Spawn Sub-Agents with Large Context Models

Critical: Use the largest context model available (e.g., claude-opus-4-5-20250101 or opus) for sub-agents. These planning tasks benefit from deep reasoning and extensive context windows.

For each unblocked project, spawn a sub-agent using the Task tool:

Use Task tool with:
  prompt: [see template below]
  subagent_type: "general-purpose"
  model: "claude-opus-4-5-20250101"  # Use largest available context model
  run_in_background: true  # Spawn in parallel when multiple projects are unblocked

7.3 Sub-Agent Prompt Template

Provide each sub-agent with:

  1. Project context from your high-level research
  2. Clear directive to use /granary:plan-work
  3. Instruction to report back with cross-project dependencies

Example prompt:

Use /granary:plan-work to plan the project `auth-token-service-abc1`.

## Context
This project is part of the "User Authentication System" initiative.
Goal: Implement JWT token generation and validation service.

## High-Level Context from Initiative Planning
- The API will consume tokens via middleware (future project: api-auth-integration)
- Token format should be JWT with RS256 signing
- Existing auth patterns found in src/middleware/ use Bearer tokens
- Reference: https://jwt.io/introduction for JWT best practices

## Your Task
1. Research the project scope thoroughly
2. Create detailed tasks with file paths, implementation details, and acceptance criteria
3. Set up task dependencies within the project

## Required Report Back
When planning is complete, summarize:
1. **Tasks created** - List of tasks with brief descriptions
2. **Cross-project interfaces** - What APIs, types, or contracts does this project expose that other projects will depend on?
3. **Cross-project dependencies identified** - Did you discover dependencies on other initiative projects not yet captured?
4. **Risks or blockers** - Any concerns that affect the broader initiative

7.4 Spawn in Parallel

Spawn sub-agents for all unblocked projects simultaneously:

# If projects A, B, C have no project dependencies, spawn all three at once:

Use Task tool (all in ONE message):
  1. prompt: [Project A planning prompt]
     model: "claude-opus-4-5-20250101"
     run_in_background: true

  2. prompt: [Project B planning prompt]
     model: "claude-opus-4-5-20250101"
     run_in_background: true

  3. prompt: [Project C planning prompt]
     model: "claude-opus-4-5-20250101"
     run_in_background: true

7.5 Collect and Synthesize Reports

After sub-agents complete, review their reports for:

  • Cross-project dependencies they identified (update initiative dependency graph if needed)
  • Shared interfaces that need coordination between projects
  • Risks that affect multiple projects
# Update dependencies if sub-agents identified new ones
granary project <project-B> deps add <project-A>

# Verify updated structure
granary initiative <initiative-id> graph --format mermaid

Step 8: Hand Off to Orchestration

Once all projects have been planned by sub-agents, the initiative is ready for /granary:orchestrate:

# Verify all projects have tasks
granary initiative <initiative-id> summary

# Get the next actionable task across the entire initiative
granary initiative <initiative-id> next

# Get ALL unblocked tasks (for parallel execution)
granary initiative <initiative-id> next --all

Example: Full Initiative Planning Flow

# 1. Research the codebase (understand existing architecture)

# 2. Create initiative
granary initiatives create "Payment Processing" \
  --description "Add payment support: Stripe integration, checkout flow, order management"

# 3. Design separation of concerns and create projects
granary projects create "Stripe Service" --description "Stripe API integration wrapper"
granary projects create "Checkout API" --description "Checkout endpoints and cart management"
granary projects create "Checkout UI" --description "Frontend checkout flow"
granary projects create "Order Service" --description "Order persistence and status tracking"

# 4. Add to initiative
granary initiative payment-processing-xyz1 add-project stripe-service-abc1
granary initiative payment-processing-xyz1 add-project checkout-api-def2
granary initiative payment-processing-xyz1 add-project checkout-ui-ghi3
granary initiative payment-processing-xyz1 add-project order-service-jkl4

# 5. Analyze dependencies and set them up
granary project checkout-api-def2 deps add stripe-service-abc1
granary project checkout-ui-ghi3 deps add checkout-api-def2
granary project order-service-jkl4 deps add checkout-api-def2

# 6. Verify structure
granary initiative payment-processing-xyz1 graph --format mermaid

# 7. Spawn sub-agents to plan unblocked projects
# stripe-service-abc1 is unblocked -> spawn agent with /granary:plan-work

# 8. Once planned, check readiness
granary initiative payment-processing-xyz1 summary

Summary

  1. Collect context broadly -> Prior art, current implementation, limitations, external docs, web search
  2. Assess -> Is this truly multi-project work?
  3. Create initiative -> High-level container with context documentation
  4. Design separation -> Clear boundaries, identify interfaces
  5. Create projects -> Add to initiative with good descriptions
  6. Analyze dependencies -> Review all project pairs, set project-level dependencies
  7. Verify structure -> Check graph for issues
  8. Spawn sub-agents -> Use largest context model (opus), provide context, request cross-project dependency reports
  9. Synthesize reports -> Update dependencies based on sub-agent findings
  10. Hand off -> Orchestrator uses initiative-level commands

Your output: A well-structured initiative with projects and dependencies. Sub-agents handle detailed task planning within each project and report back cross-project dependencies they discover.

Key principle: You are a high-level coordinator. Gather broad context, design the structure, delegate deep planning to sub-agents, then synthesize their findings.

Orchestrating Implementation with Granary

This skill is for implementation-time orchestration. Your job is to coordinate sub-agents to implement planned work. You do NOT plan or design—you delegate and track.

Critical: Trust the Scheduler

NEVER determine task parallelism by:

  • Checking if blocked_by is null/empty on individual tasks
  • Assuming tasks are independent because they don't have explicit blockers
  • Launching more tasks than granary next --all returns
  • Inspecting task metadata to make your own parallelism decisions

granary next --all is the ONLY source of truth for what can run in parallel. It considers:

  • Explicit task dependencies (task_dependencies table)
  • Project dependencies (project_dependencies table)
  • Task status (draft tasks are never returned)
  • Claims and leases
  • Implicit ordering requirements

If granary next --all returns 2 tasks, spawn exactly 2 agents. Not 6. Not 4. Exactly 2.

Output Format

Always use --format=prompt instead of --json for granary commands. The --format=prompt output is specifically designed for LLM consumption—it's token-efficient and easy to parse without wasting context on JSON syntax.

Only use --json when you need to extract specific fields via jq, and always filter the output:

# Only if you need specific fields
granary task <id> --json | jq '.id, .status'

Primary Use-Case

You are prompted to implement a project. Follow these steps:

Step 1: Get Granary Overview

granary summary

This shows all projects, their status, and task counts. Understand what exists before proceeding.

Step 2: Find Your Target Project

If given a project name, find it:

granary projects
granary project <project-id>

Finding Projects and Tasks

Search for projects and tasks by title:

granary search "query"                # Find matching projects and tasks
granary search "api" --format=prompt  # LLM-friendly output

This is useful when you know part of the project or task name but not the exact ID.

Step 3: Assess Project Readiness

Examine the project structure:

granary project <project-id> tasks

Decision tree:

SituationAction
Project has no tasksUse /granary:plan-work skill to plan first
Project has tasks but they lack detailUse /granary:plan-work skill to refine
Single simple project with clear descriptionImplement directly as one task
Project has tasks with dependenciesHappy path - proceed to Step 4

Step 4: Start Orchestration Session

granary session start "implementing-<project-name>" --mode execute
granary session add <project-id>

Step 5: The Orchestration Loop

Your sole focus: hand off tasks to sub-agents. You do NOT implement tasks yourself.

Key principle: Maximize parallelism. Always look for opportunities to run multiple tasks concurrently. Tasks without dependencies on each other can and should run in parallel.

Get ONLY the Tasks Granary Says Are Ready

# Get ONLY tasks the scheduler has determined are ready
granary next --all --format=prompt

This returns only the tasks that are ready to execute. The scheduler has already evaluated dependencies, project ordering, claims, and status. Spawn agents for exactly the tasks returned—no more, no fewer.

If no tasks are returned, either all tasks are complete or remaining tasks are blocked.

DO NOT bypass this by:

  • Listing all project tasks and filtering by blocked_by == null
  • Assuming tasks without explicit blockers can run in parallel
  • Making your own judgment calls about task independence

The scheduler knows things you don't. Trust it.

Spawning Agents in Parallel

When multiple tasks are unblocked, spawn them all at once using parallel Task tool calls:

# If granary next --all returns task-1, task-2, task-3:

Use Task tool (call all three in a SINGLE message):
  1. prompt: "Execute granary task task-1. Use /granary:execute-task skill."
     subagent_type: "general-purpose"
     run_in_background: true

  2. prompt: "Execute granary task task-2. Use /granary:execute-task skill."
     subagent_type: "general-purpose"
     run_in_background: true

  3. prompt: "Execute granary task task-3. Use /granary:execute-task skill."
     subagent_type: "general-purpose"
     run_in_background: true

Important: Use run_in_background: true for parallel execution. This allows multiple agents to work simultaneously.

The Loop

  1. Ask the scheduler what's ready → granary next --all --format=prompt
  2. Spawn agents for exactly those tasks → One Task tool call per task, all in the same message
  3. Monitor progress → Check on background agents, wait for completions
  4. Repeat → When agents complete, ask the scheduler again for newly unblocked tasks

Critical: Never spawn more agents than tasks returned by granary next --all. If it returns 2 tasks, spawn 2 agents. Period.

Single Task Fallback

If only one task is available or tasks must be sequential:

granary next --format=prompt

Then spawn a single agent and wait for completion before checking for the next task.

What Sub-Agents Do

Each sub-agent is responsible for:

  • Building context (granary handoff --tasks <id>)
  • Starting the task (granary task <id> start)
  • Doing the actual implementation
  • Marking the task done (granary task <id> done) or blocked

Note: You do NOT need to run granary handoff yourself. Sub-agents handle their own context building. Your job is to identify unblocked tasks and spawn agents.

Step 6: Handle Completion

When all tasks are done:

granary session close --summary "Completed implementation of <project-name>"

Handling Edge Cases

Sub-Agent Gets Blocked

If a sub-agent cannot complete:

# Sub-agent should have blocked the task:
granary task <task-id> block --reason "..."

# You see it when checking next task
granary next --format=prompt  # Will skip blocked tasks

Conflict Prevention

Sub-agents should claim tasks with leases:

granary task <task-id> claim --owner "Worker-1" --lease 30
# Exit code 4 = conflict (task claimed by another)

Checkpointing

Before risky operations:

granary checkpoint create "before-major-change"

# If things go wrong
granary checkpoint restore before-major-change

Common Mistakes

Inspecting tasks to determine parallelism

# WRONG - Don't do this
granary project <id> tasks --json | jq '.[] | select(.blocked_by == null)'

This bypasses the scheduler and leads to race conditions. Just because a task has no explicit blocked_by value doesn't mean it's ready to run. The scheduler considers implicit dependencies, project ordering, and other factors you can't see in task metadata.

Assuming task independence

# WRONG - Don't assume tasks can run together
granary show task-1  # blocked_by: null
granary show task-2  # blocked_by: null
granary show task-3  # blocked_by: null
# "All three have no blockers, I'll run them all!"

Tasks may have implicit logical dependencies. Task-3 might implement a service that uses schemas from task-1. Running them in parallel causes compiler errors.

Overriding scheduler decisions

# WRONG - Don't second-guess the scheduler
granary next --all  # Returns 2 tasks
# "But I checked and 6 tasks have no blockers, I'll launch 6 agents"

If granary next --all returns 2 tasks, there's a reason. Trust it.

The right approach

# RIGHT - Trust the scheduler completely
granary next --all --format=prompt
# Returns task-1, task-2
# Spawn exactly 2 agents, one for each task

Only spawn agents for tasks returned by granary next --all. When they complete, run the command again to discover what's newly unblocked.

Summary

  1. Get overview → granary summary
  2. Find project → granary projects
  3. Assess readiness → Are tasks planned? If not, use plan-work skill
  4. Start session → granary session start
  5. Loop: delegate tasks → Use granary next --all, spawn agents for exactly the tasks returned
  6. Close session → granary session close

Your job is coordination, not implementation. Sub-agents use granary handoff to build their own context and do the actual work—you just spawn agents for the tasks that granary next --all returns.

Remember: granary next --all is the scheduler. Trust it completely. If it returns 2 tasks, spawn 2 agents. Don't inspect task metadata to make your own parallelism decisions—that path leads to race conditions and compiler errors.

Planning Work in Granary

Use this skill when you need to break down work into projects and tasks, or when an orchestrator determines a project needs planning before implementation.

Before You Plan: Do Thorough Research

Critical: Before creating any tasks, conduct comprehensive research of the codebase. Each task description is the ONLY context a sub-agent receives—they cannot ask follow-up questions or explore further. Your research directly determines whether tasks succeed or fail.

Check for Existing Work First

Before creating a new project or task, search for similar existing work:

# Search for similar projects and tasks
granary search "user profile"
granary search "authentication"
granary search "api endpoint"

Decision tree based on search results:

Search ResultAction
Exact match found (same feature)Don't duplicate—add tasks to existing project or update existing tasks
Similar project existsReview it—maybe extend it instead of creating a new project
Related tasks exist in other projectsConsider dependencies or consolidation
No matchesSafe to create new project

Example: Avoiding duplication

$ granary search "profile"
Projects:
  user-profile-abc1: "User Profile" (3 tasks, 1 completed)

Tasks:
  settings-xyz9-task-2: "Add profile settings page"

In this case, don't create a new "User Profile" project—add your tasks to user-profile-abc1 or coordinate with the existing work.

Research Checklist

  • Search granary - Check for existing similar projects and tasks
  • Locate all relevant files - Find existing implementations, tests, configs
  • Understand existing patterns - How does the codebase handle similar features?
  • Identify dependencies - What modules/services will be affected?
  • Note file paths and line numbers - Sub-agents need exact locations
  • Document function signatures - What interfaces exist?
  • Find test patterns - How are similar features tested?

Research Tools

# Check for existing planned work
granary search "feature keywords"
granary projects                    # List all projects
granary project <id> tasks          # See tasks in a specific project

# Find relevant files in codebase
glob "**/*.rs" | grep -i auth
grep -r "UserService" src/

# Understand existing patterns
cat src/services/user.rs | head -100

Document your findings in steering files (see Section 5) before creating tasks.

1. Create a Project

Group related tasks into a project:

granary projects create "Feature Name" --description "Clear description of what this project achieves"

Output gives you a project ID like feature-name-abc1.

2. Break Down into Tasks

Create focused, actionable tasks:

granary project <project-id> tasks create "Task title" \
  --description "**Goal:** What this task accomplishes

**Context:** Why this task exists

**Requirements:**
- Specific deliverable 1
- Specific deliverable 2

**Acceptance Criteria:**
- [ ] Criterion 1
- [ ] Criterion 2" \
  --priority P1

Priority Levels

PriorityWhen to Use
P0Critical, blocking other work
P1Important, should do soon
P2Normal priority (default)
P3Nice to have

Writing Good Task Descriptions

The task description is the ONLY context a sub-agent receives. Sub-agents cannot explore the codebase or ask questions—they rely entirely on what you provide.

Include:

  • Goal: One sentence on what this achieves
  • Context: Why this matters, background info
  • Requirements: Specific deliverables
  • Files to Modify: Exact paths with line numbers where relevant
  • Implementation Details: Suggested approach, function signatures, patterns to follow
  • Acceptance Criteria: How to verify completion

Bad vs Good Task Descriptions

Bad: "Fix the auth bug"

Good:

**Goal:** Fix null pointer in UserService.getById when user not found.

**Context:** Currently throws NullPointerException when querying non-existent user IDs. Should gracefully handle missing users.

**Files to Modify:**
- `src/services/user_service.rs:142-156` - The `get_by_id` function
- `src/errors/mod.rs:23` - Add UserNotFoundException if not present
- `tests/services/user_service_test.rs` - Add test case

**Implementation Details:**
The existing pattern in `src/services/post_service.rs:89` handles this well:
```rust
pub fn get_by_id(id: Uuid) -> Result<Option<Post>, ServiceError> {
    // Returns Ok(None) for missing records
}

Follow this pattern—return Result<Option<User>, ServiceError> instead of Result<User, ServiceError>.

Acceptance Criteria:

  • get_by_id returns Ok(None) for missing users
  • Existing callers updated to handle Option
  • Test added for missing user case

### Linking Files in Descriptions

Always provide exact file paths and line numbers:

| Instead of...                | Write...                                          |
| ---------------------------- | ------------------------------------------------- |
| "the user service"           | `src/services/user_service.rs`                    |
| "the auth middleware"        | `src/middleware/auth.rs:45-67`                    |
| "follow the existing pattern"| "follow pattern in `src/handlers/posts.rs:23-45`" |
| "add tests"                  | "add tests in `tests/unit/user_test.rs`"          |

### Implementation Detail Examples

**For new endpoints:**

Implementation Details: Add handler in src/handlers/profile.rs. Follow the pattern from src/handlers/user.rs:34-56:

  1. Create GetProfileHandler struct implementing Handler trait
  2. Use ProfileService::get_by_user_id() (already exists at src/services/profile.rs:12)
  3. Return ApiResponse<ProfileDto> matching existing response format
  4. Register route in src/routes/mod.rs:45 following existing pattern

**For refactoring:**

Implementation Details: Extract validation logic from src/handlers/user.rs:78-112 into src/validators/user_validator.rs.

Existing validator pattern at src/validators/post_validator.rs:

  • Implement Validator<T> trait
  • Return ValidationResult with field-level errors
  • Use #[derive(Validate)] macro for struct validation

The three validation functions to extract:

  • validate_email() (lines 82-89)
  • validate_password() (lines 91-98)
  • validate_username() (lines 100-110)

**For bug fixes:**

Implementation Details: Root cause: calculate_total() at src/cart/pricing.rs:45 doesn't account for null discounts.

Fix approach:

  1. Add null check before discount application (line 52)
  2. Use discount.unwrap_or(Decimal::ZERO) pattern (see src/cart/tax.rs:23)
  3. Add debug logging using existing tracing::debug! macro

## 3. Add Dependencies

If tasks must be done in order:

```bash
# task-2 depends on task-1 (task-2 cannot start until task-1 is done)
granary task <project-id>-task-2 deps add <project-id>-task-1

# View dependencies
granary task <project-id>-task-2 deps graph

You can also specify dependencies at task creation time:

granary project <project-id> tasks create "Dependent task" \
  --dependencies <project-id>-task-1

Only add dependencies when truly required - over-constraining reduces parallelism.

4. Start a Planning Session (Optional)

For complex planning:

granary session start "planning-feature-x" --mode plan
granary session add <project-id>

5. Steering Files

Steering files provide standards, conventions, and context that sub-agents should follow during implementation. Set these up during planning so orchestrators and sub-agents have the guidance they need.

Steering Scopes

ScopeWhen IncludedUse Case
Global (default)Always in context/handoffsProject-wide standards
--project <id>When project is in session scopeProject-specific patterns
--task <id>When handing off that specific taskTask-specific research
--for-sessionDuring session, auto-deleted on closeTemporary research notes

Adding Steering Files (optional)

Steering files are useful for:

  • Transient files, produced during deep research, e.g.:
    • Summary of a technical article
    • Explanation of how a system works
  • Task or project specific guidelines
# Global steering (always included)
granary steering add docs/coding-standards.md

# Project-attached (only when this project is in context)
granary steering add docs/auth-patterns.md --project auth-proj-abc1

# Task-attached (only in handoffs for this specific task)
granary steering add .granary/task-research.md --task auth-proj-abc1-task-3

# Session-attached (temporary, auto-deleted on session close)
granary steering add .granary/temp-notes.md --for-session

# List current steering files
granary steering list

# Remove steering (specify scope to match)
granary steering rm docs/auth-patterns.md --project auth-proj-abc1

When to Use Each Scope

  • Global: Project-wide coding standards, architecture decisions
  • Project-attached: Module-specific patterns (e.g., auth module conventions)
  • Task-attached: Research specific to one task (avoid polluting other handoffs)
  • Session-attached: Temporary research during planning that shouldn't persist

Example: Adding Steering During Planning

# During planning, document patterns you discover
cat > docs/auth-patterns.md << 'EOF'
# Authentication Patterns

## Existing Conventions
- Auth middleware in src/middleware/auth.rs uses JWT tokens
- User model in src/models/user.rs with bcrypt password hashing
- Session storage uses Redis (see src/services/session.rs)

## Key Conventions
- All API endpoints return JSON with {data, error, meta} structure
- Use `ApiError` type for error handling
- Tests go in tests/ directory, not inline
EOF

# Attach to the project so sub-agents get this context
granary steering add docs/auth-patterns.md --project auth-proj-abc1

Example: Planning a User Profile Feature

Step 1: Check for Existing Work

First, search granary for similar projects or tasks:

$ granary search "profile"
No matching projects or tasks found.

$ granary search "user"
Projects:
  user-auth-def2: "User Authentication" (4 tasks, 4 completed)

Tasks:
  user-auth-def2-task-3: "Implement user login endpoint"

Analysis: No existing profile work, but there's a completed auth project. We can reference patterns from user-auth-def2 when building our profile feature. Safe to create a new project.

Step 2: Research the Codebase

Now thoroughly research the codebase:

# Find existing user-related code
glob "**/*user*"
grep -r "struct User" src/

# Understand the API patterns
cat src/handlers/mod.rs
cat src/routes/mod.rs | head -50

# Check existing types
cat src/types/user.rs

# Find test patterns
ls tests/
cat tests/handlers/user_test.rs | head -30

Research findings to document:

  • User model at src/models/user.rs:12-45 has id, email, name, created_at
  • Missing: bio, avatar_url fields needed for profile
  • Handler pattern at src/handlers/user.rs:23-67 - uses axum::Json<T>
  • Routes registered in src/routes/api.rs:34
  • Tests use mockall for service mocking (see tests/handlers/user_test.rs:5)

Step 3: Create Project and Tasks

# Create project
granary projects create "User Profile" --description "Add user profile page with edit capability. Extends existing User model with profile fields."
# Output: user-profile-abc1

# Task 1: Extend the data model
granary project user-profile-abc1 tasks create "Extend User model with profile fields" \
  --description "**Goal:** Add profile fields to the User model and create database migration.

**Context:** User model exists but lacks profile-specific fields.

**Files to Modify:**
- \`src/models/user.rs:12-45\` - Add new fields to User struct
- \`src/schema.rs\` - Update diesel schema (auto-generated after migration)
- \`migrations/\` - Create new migration file

**Implementation Details:**
Add these fields to the User struct at \`src/models/user.rs:12\`:
\`\`\`rust
pub struct User {
    // existing fields...
    pub bio: Option<String>,        // max 500 chars
    pub avatar_url: Option<String>, // validated URL
}
\`\`\`

Create migration following pattern in \`migrations/2024_01_15_create_users/up.sql\`:
\`\`\`sql
ALTER TABLE users ADD COLUMN bio TEXT;
ALTER TABLE users ADD COLUMN avatar_url VARCHAR(2048);
\`\`\`

**Acceptance Criteria:**
- [ ] Migration runs successfully (\`diesel migration run\`)
- [ ] User struct compiles with new fields
- [ ] Existing user queries still work" \
  --priority P0
# Output: user-profile-abc1-task-1

# Task 2: Create Profile DTOs and validation
granary project user-profile-abc1 tasks create "Create Profile DTOs with validation" \
  --description "**Goal:** Create request/response DTOs for profile endpoints.

**Files to Modify:**
- \`src/types/mod.rs:1\` - Add mod declaration
- \`src/types/profile.rs\` - New file for DTOs

**Implementation Details:**
Follow existing DTO pattern at \`src/types/user.rs:8-25\`:
\`\`\`rust
#[derive(Serialize, Deserialize)]
pub struct ProfileResponse {
    pub id: Uuid,
    pub name: String,
    pub email: String,
    pub bio: Option<String>,
    pub avatar_url: Option<String>,
}

#[derive(Deserialize, Validate)]
pub struct UpdateProfileRequest {
    #[validate(length(max = 100))]
    pub name: Option<String>,
    #[validate(length(max = 500))]
    pub bio: Option<String>,
    #[validate(url)]
    pub avatar_url: Option<String>,
}
\`\`\`

Use \`validator\` crate (already in Cargo.toml) for validation.

**Acceptance Criteria:**
- [ ] DTOs serialize/deserialize correctly
- [ ] Validation rejects invalid inputs
- [ ] Unit tests in \`tests/types/profile_test.rs\`" \
  --priority P0 \
  --dependencies user-profile-abc1-task-1
# Output: user-profile-abc1-task-2

# Task 3: Implement API handlers
granary project user-profile-abc1 tasks create "Implement profile API handlers" \
  --description "**Goal:** Create GET and PUT handlers for profile endpoints.

**Context:** DTOs defined in task-2. User model extended in task-1.

**Files to Modify:**
- \`src/handlers/mod.rs:5\` - Add mod declaration
- \`src/handlers/profile.rs\` - New handler file
- \`src/routes/api.rs:34\` - Register new routes
- \`tests/handlers/profile_test.rs\` - New test file

**Implementation Details:**
Follow handler pattern at \`src/handlers/user.rs:23-67\`:

\`\`\`rust
// GET /api/profile/:id
pub async fn get_profile(
    State(pool): State<DbPool>,
    Path(user_id): Path<Uuid>,
) -> Result<Json<ProfileResponse>, ApiError> {
    let user = UserService::get_by_id(&pool, user_id)
        .await?
        .ok_or(ApiError::NotFound)?;
    Ok(Json(ProfileResponse::from(user)))
}

// PUT /api/profile/:id (requires auth)
pub async fn update_profile(
    State(pool): State<DbPool>,
    Extension(current_user): Extension<AuthUser>,
    Path(user_id): Path<Uuid>,
    Json(req): Json<UpdateProfileRequest>,
) -> Result<Json<ProfileResponse>, ApiError> {
    // Verify user can only update own profile
    if current_user.id != user_id {
        return Err(ApiError::Forbidden);
    }
    req.validate()?;
    // ... update logic
}
\`\`\`

Register routes in \`src/routes/api.rs:34\` following existing pattern:
\`\`\`rust
.route(\"/profile/:id\", get(get_profile))
.route(\"/profile/:id\", put(update_profile).layer(auth_middleware()))
\`\`\`

**Acceptance Criteria:**
- [ ] GET returns profile data
- [ ] PUT requires authentication
- [ ] PUT validates ownership (users can only edit own profile)
- [ ] Integration tests pass" \
  --priority P1 \
  --dependencies user-profile-abc1-task-2
# Output: user-profile-abc1-task-3

# Add steering file with research findings
cat > docs/profile-patterns.md << 'EOF'
# Profile Feature Patterns

## Existing Codebase Patterns
- Handlers use `axum` extractors: `State`, `Path`, `Json`, `Extension`
- Auth middleware at `src/middleware/auth.rs:12` adds `AuthUser` to extensions
- Error handling uses `ApiError` enum at `src/errors/api_error.rs`
- All responses wrapped in `Json<T>`

## Database Access
- Use `UserService` at `src/services/user.rs` for queries
- Connection pool passed via `State<DbPool>`
- Async queries with `sqlx`

## Testing
- Integration tests in `tests/handlers/`
- Use `TestApp::new()` helper at `tests/common/mod.rs:8`
- Mock services with `mockall` when needed
EOF

granary steering add docs/profile-patterns.md --project user-profile-abc1

Summary

  1. Search for existing work - Use granary search to find similar projects/tasks before creating duplicates
  2. Research thoroughly - Explore the codebase, find patterns, note file paths and line numbers
  3. Create project with clear description (or add to existing project if found)
  4. Break into tasks with detailed descriptions including:
    • Exact file paths with line numbers
    • Implementation details with code examples
    • References to existing patterns to follow
  5. Add dependencies only where truly required
  6. Set up steering to document research findings and conventions
  7. Hand off to /granary:orchestrate for implementation

Remember: Sub-agents only see task descriptions. Every detail they need must be in the task or steering files—they cannot explore or ask questions.

Setting Up Granary

Use this skill when the user asks you to set up granary in their project.

1. Check Installation

First, verify granary is installed:

which granary

If not installed, direct the user to install it:

# macOS/Linux
curl -fsSL https://raw.githubusercontent.com/speakeasy-api/granary/main/scripts/install.sh | sh

# Windows PowerShell
irm https://raw.githubusercontent.com/speakeasy-api/granary/main/scripts/install.ps1 | iex

2. Initialize Workspace

Initialize granary in the project directory:

granary init

This creates a .granary/ directory with the SQLite database.

3. Verify Setup

Check that granary is working:

granary doctor

Done

Granary is now ready. The user can:

  • Create projects with granary projects create "Project Name" --description "..."
  • Create tasks with granary project <id> tasks create "Task title" --description "..."
  • Start sessions with granary session start "session-name"

Commands 1

Granary Status Command

When the user runs /granary:status, provide a summary of the current granary state.

Steps

  1. Current Session: Run: granary session current --json Display: Session name, mode, owner

  2. Task Summary: Run: granary tasks --json Display: Count by status (todo, in_progress, done, blocked)

  3. Next Action: Run: granary next --json Display: The next recommended task

  4. Blockers: Run: granary tasks --status blocked --json Display: Any blocked tasks and their reasons

Output Format

Format as clean markdown:

Granary Status

Session: [name] ([mode] mode) Owner: [owner]

Tasks

  • Todo: [count]
  • In Progress: [count]
  • Done: [count]
  • Blocked: [count]

Next Action

[Task title and ID]

Blockers

[List blocked tasks with reasons, or "None"]

Sponsors

Details

Marketplace
speakeasy-api/granary
Author
Daniel Kovacs
Category
Productivity