# Intent-Engine: AI Agent Guide
**Version**: {{VERSION}}
**Purpose**: This document helps AI agents understand Intent-Engine's core concepts and interface design
---
## ๐ง Important: Code Formatting
**CRITICAL**: This project enforces code formatting with `cargo fmt`.
### Automatic Setup (No Action Needed)
Git hooks are **automatically installed** on your first `cargo build`. The pre-commit hook will:
- Run `cargo fmt --all` before every commit
- Auto-add formatted files to your commit
- Prevent unformatted code from being committed
### Verification
Check that hooks are installed:
```bash
ls -la .git/hooks/pre-commit # Should exist and be executable
```
### Manual Override
If you need to bypass the hook (not recommended):
```bash
git commit --no-verify
```
To manually install hooks:
```bash
./scripts/setup-git-hooks.sh
```
To disable automatic installation:
```bash
export SKIP_GIT_HOOKS_SETUP=1
cargo build
```
### How It Works
1. **First build**: `build.rs` detects no hooks โ installs them automatically
2. **Every commit**: Pre-commit hook โ runs `cargo fmt` โ adds changes โ continues commit
3. **CI validation**: Runs `cargo fmt --all -- --check` to ensure compliance
---
## ๐ Authoritative Specification
> **CRITICAL**: Before working with Intent-Engine, understand the specification hierarchy:
>
> **Single Source of Truth**: `docs/INTERFACE_SPEC.md`
>
> The INTERFACE_SPEC.md document is the **authoritative blueprint** for all Intent-Engine interfaces:
> - โ
**CLI Interface**: Command signatures, parameters, atomic behaviors, JSON output formats
> - โ
**Rust API**: Public types, function signatures
> - โ
**Data Models**: Exact field names, types, lifecycle semantics
> - โ
**Guarantees**: SemVer stability, breaking change policies
>
> **This AGENT.md is a derived guide** that explains concepts and patterns.
> **In case of any conflict**, defer to INTERFACE_SPEC.md.
>
> When implementing features, writing tests, or building integrations:
> 1. Read INTERFACE_SPEC.md first to understand the contract
> 2. Use this guide to understand the philosophy and patterns
> 3. Validate your work against the spec's requirements
---
## ๐ฏ Core Philosophy
Intent-Engine is built on the **Focus-Driven Architecture** principle:
1. **Single Focus Point**: `current_task_id` is the central concept
2. **Atomic Operations**: Commands combine multiple steps (start, switch, done)
3. **Context-Aware Intelligence**: Recommendations based on current focus
4. **Hierarchical Task Trees**: Parent-child relationships with enforced completion order
5. **Persistent Memory**: Cross-session state in SQLite database
---
## ๐ Data Model
### Task
```
Task {
id: i64,
name: String,
spec: Option<String>, // Markdown specification
status: String, // "todo", "doing", "done"
priority: Option<i32>, // Priority level: 1=critical, 2=high, 3=medium, 4=low
// CLI accepts: --priority critical|high|medium|low
complexity: Option<i32>, // Optional complexity rating
parent_id: Option<i64>, // Parent task for subtasks
first_todo_at: Option<Timestamp>, // Lifecycle tracking
first_doing_at: Option<Timestamp>,
first_done_at: Option<Timestamp>
}
```
### Event
```
Event {
id: i64,
task_id: i64,
timestamp: Timestamp,
log_type: String, // "decision", "blocker", "milestone", "note"
discussion_data: String // Markdown content
}
```
### Workspace State
```
current_task_id: Option<i64> // The focused task (or null)
```
---
## ๐ Key Design Principles
### 1. Focus-Driven Operations
Most operations work on `current_task_id`:
```bash
# NO explicit ID needed - uses current_task_id
task done
event add --type decision --data-stdin
task spawn-subtask --name "Configure JWT"
```
### 2. Atomic Operations
Commands perform multiple steps atomically:
**`task start <ID>`**:
1. Set task status to `doing`
2. Set as `current_task_id`
3. Return full context with events
**`task switch <ID>`**:
1. Previous task: `doing` โ `todo`
2. New task: `todo` โ `doing`
3. Update `current_task_id`
**`task done`** (NO parameters):
1. Verify all subtasks are `done`
2. Current task โ `done`
3. Clear `current_task_id`
### 3. Context-Aware Intelligence
**`task pick-next`** uses depth-first strategy:
**Priority 1**: Subtasks of current focused task
```sql
SELECT * FROM tasks
WHERE parent_id = current_task_id AND status = 'todo'
ORDER BY priority ASC NULLS LAST
LIMIT 1
```
**Priority 2**: Top-level tasks (if no focused subtasks)
```sql
SELECT * FROM tasks
WHERE parent_id IS NULL AND status = 'todo'
ORDER BY priority ASC NULLS LAST
LIMIT 1
```
---
## ๐ New Features (v0.2+)
### Task Dependencies (v0.2)
Define task dependencies to ensure prerequisites are met:
```bash
# Task 43 depends on Task 42
task add-dependency --blocked 43 --blocking 42
```
**Behaviors**:
- `task start` will fail if task has incomplete dependencies
- `task pick-next` automatically filters out blocked tasks
- Circular dependency detection prevents invalid configurations
### Priority Levels (v0.2)
Tasks now support priority enum values:
```bash
task add --name "Fix critical bug" --priority critical
task add --name "Add feature" --priority high
task add --name "Refactor code" --priority medium
task add --name "Update docs" --priority low
```
**Priority levels** (1 = highest):
- `critical` โ priority 1
- `high` โ priority 2
- `medium` โ priority 3
- `low` โ priority 4
`task pick-next` sorts by priority automatically.
### Event Filtering (v0.2)
`event list` now supports advanced filtering:
```bash
# All decisions across all tasks
event list --type decision
# Recent blockers from last 7 days
event list --type blocker --since 7d
# Latest 10 events for a specific task
event list --task-id 42 --limit 10
# All events from a task
event list --task-id 42
```
**Filter parameters**:
- `--type`: Filter by event type (decision, blocker, milestone, note)
- `--since`: Time-based filter (e.g., "7d", "24h", "30m", "60s")
- `--limit`: Maximum results (default: 50)
- `--task-id`: Optional - omit for global search
### Unified Search (v0.4)
The `search` command replaces `task search` and searches both tasks AND events:
```bash
# Search across tasks and events
search "JWT authentication"
# Search only tasks
search "JWT" --include-tasks
# Search only events
search "JWT" --include-events
```
**Returns mixed results**:
- Task matches with snippets
- Event matches with full task ancestry chain
- FTS5 highlighting with `**keywords**`
### Plan Interface (v0.6)
The `plan` command enables **declarative task creation** with batch operations, idempotency, and automatic dependency resolution:
```bash
# Create task structure from JSON stdin
cat > project.json <<'JSON'
{
"tasks": [
{
"name": "User Authentication",
"spec": "Implement full auth system",
"priority": "high",
"children": [
{"name": "JWT Implementation"},
{"name": "OAuth2 Integration", "depends_on": ["JWT Implementation"]}
]
}
]
}
JSON
ie plan < project.json
```
**Key Capabilities**:
- **Batch Creation**: Create entire task trees in one transaction
- **Idempotent Updates**: Run same plan multiple times โ same result
- **Name-Based Identity**: Tasks identified by name, not ID
- **Dependency Resolution**: Automatic name-to-ID mapping
- **Cycle Detection**: Tarjan's SCC algorithm prevents circular dependencies
- **Hierarchical Nesting**: `children` field creates parent-child relationships
**TaskTree Structure**:
```typescript
interface TaskTree {
name: string // Required: unique task identifier
spec?: string // Optional: task specification
depends_on?: string[] // Optional: dependency task names
task_id?: number // Optional: explicit ID for updates
}
```
**Example: Complex Project Setup**
```json
{
"tasks": [
{
"name": "Backend API",
"priority": "critical",
"children": [
{"name": "Database Schema"},
{"name": "REST Endpoints", "depends_on": ["Database Schema"]},
{"name": "Authentication", "depends_on": ["Database Schema"]}
]
},
{
"name": "Frontend",
"depends_on": ["Backend API"]
}
]
}
```
**Idempotent Updates**:
```bash
# First run: Creates all tasks
ie plan < project.json
# Output: Created: 5, Updated: 0
# Modify specs, run again: Updates existing tasks
ie plan < project_v2.json
# Output: Created: 0, Updated: 5
# No changes, run again: No-op, same result
ie plan < project_v2.json
# Output: Created: 0, Updated: 5
```
**Error Handling**:
- โ Circular dependencies detected automatically
- โ Missing dependency references rejected
- โ Duplicate task names in request rejected
- โ
All operations atomic (all-or-nothing)
**See**: [docs/archive/PLAN_INTERFACE_GUIDE.md](docs/archive/PLAN_INTERFACE_GUIDE.md) for comprehensive guide and migration examples.
---
## ๐ ๏ธ Essential Commands
### Task Management
| `task add` | Create single task | `--name`, `--parent`, `--spec-stdin` | โ |
| `plan` | Batch create/update tasks (v0.6) | JSON from stdin | โ (declarative) |
| `task start <ID>` | Start task | `<TASK_ID>`, `--with-events` | Sets focus |
| `task done` | Complete current | None | โ
Yes |
| `task switch <ID>` | Switch focus | `<TASK_ID>` | Changes focus |
| `task spawn-subtask` | Create + switch | `--name`, `--spec-stdin` | โ
Yes |
| `task pick-next` | Recommend next | `--format` | Context-aware |
| `task list` | Filter by metadata | `--status`, `--parent` | โ |
| `task add-dependency` | Define dependencies | `--blocked`, `--blocking` | โ |
| `search` | Unified search (tasks+events) | `<QUERY>`, `--include-tasks`, `--include-events` | โ |
### Event Recording
| `event add` | Record event | `--type`, `--task-id?`, `--data-stdin` | โ
Yes (if no --task-id) |
| `event list` | List events | `--task-id?`, `--type?`, `--since?`, `--limit?` | โ (global if no task-id) |
### Workspace
| `current` | Get focused task | None |
| `current --set <ID>` | Set focus | `<TASK_ID>` |
| `report` | Generate report | `--since`, `--status`, `--summary-only` |
---
## ๐จ Output Formats
All commands output **JSON by default**.
### Standard Task Output
```json
{
"id": 42,
"name": "Implement authentication",
"status": "doing",
"spec": "Use JWT with 7-day expiry...",
"parent_id": null,
"priority": 1,
"first_doing_at": "2024-11-09T10:05:00Z"
}
```
### Special Output Structures
**TaskWithEvents** (from `task start --with-events`):
```json
{
"task": { ... },
"events_summary": {
"total_count": 3,
"recent_events": [...]
}
}
```
**SearchResult** (from `task search --snippet`):
```json
{
"task_id": 42,
"name": "Implement **authentication**",
"spec_snippet": "Use **JWT** with refresh tokens...",
"rank": 0.95
}
```
**PickNextResult** (from `task pick-next --format json`):
```json
{
"recommended_task": { ... },
"reason": "subtask_of_current",
"context": {
"current_task_id": 42,
"strategy": "depth_first"
}
}
```
---
## ๐ Typical Workflow
### Starting Work
```bash
# See what's available
task pick-next
# Start the recommended task
task start 42 --with-events
# Review context and spec
# Task 42 is now current_task_id
```
### During Work
```bash
# Discover a subtask is needed
task spawn-subtask --name "Configure JWT secret"
# Creates subtask and automatically switches to it
# Record decision
# Complete subtask
task done
# Automatically clears current_task_id
```
### Continuing Parent Task
```bash
# Switch back to parent
task switch 42
# Or let pick-next suggest next subtask
task pick-next # Will recommend other subtasks of 42
# Complete parent when all children done
task done
```
---
## โ ๏ธ Common Pitfalls
### โ DON'T: Pass ID to `task done`
```bash
task done 42 # WRONG - command takes no parameters
```
### โ
DO: Use focus-driven approach
```bash
task start 42 # Set as current
task done # Complete current
```
### โ DON'T: Use `list` for text search
```bash
task list --name "auth" # WRONG - list is for metadata only (status, parent)
```
### โ
DO: Use `search` for text
```bash
search "auth AND jwt" # Correct - searches both tasks and events
```
### โ DON'T: Forget to set current task before `done`
```bash
task done # ERROR if no current task
```
### โ
DO: Always start or switch first
```bash
task start 42
task done # Works
```
---
## ๐งช Testing Guidelines
### When writing tests, ensure:
1. **Focus State**: Set up `current_task_id` before testing focus-driven commands
2. **Atomic Verification**: Check all steps of atomic operations complete
3. **Hierarchy Rules**: Parent tasks can't be done until children are done
4. **Event Flexibility**: Test both `--task-id` and current-task modes
5. **Search vs Find**: Separate tests for metadata filtering vs text search
### Test Data Setup
```bash
# Create task hierarchy
task add --name "Parent" # ID 1
task start 1
task spawn-subtask --name "Child 1" # ID 2, now current
task done # Child 1 done
task spawn-subtask --name "Child 2" # ID 3, now current
task done # Child 2 done
task switch 1 # Back to parent
task done # Parent done (all children done)
```
---
## ๐ Key Documents
- **Authoritative Spec**: `docs/INTERFACE_SPEC.md`
- **AI Integration**: `CLAUDE.md` and `MIGRATION_v0.10.0.md`
- **Migration Guide**: `MIGRATION_v0.10.0.md` (v0.9.x โ v0.10.0)
- **Test Files**: `tests/interface_spec_test.rs`, Dashboard integration tests
---
## ๐ Design Rationale
### Why Focus-Driven?
1. **Cognitive Load**: Humans naturally focus on one task at a time
2. **Context Retention**: No need to constantly specify "which task"
3. **Atomic Safety**: Focus prevents accidental operations on wrong tasks
4. **AI Efficiency**: Reduces token usage (no repetitive ID passing)
### Why Atomic Operations?
1. **Consistency**: Multiple steps succeed or fail together
2. **Simplicity**: One command does "the right thing"
3. **Safety**: No partial state changes
4. **Ergonomics**: Fewer commands to remember
### Why Hierarchical Tasks?
1. **Problem Decomposition**: Natural way to break down complex work
2. **Forced Completion**: Parent can't complete until children done
3. **Context Awareness**: `pick-next` recommends subtasks first
4. **Progress Tracking**: Tree structure shows work breakdown
---
## ๐ฎ Future Considerations (Post-1.0)
- **Multiple Workspaces**: Separate focus contexts for different projects
- **Task Templates**: Reusable task structures with subtasks
- **Time Tracking**: Automatic time spent per task/status
- **Dependency Graphs**: Tasks depend on other tasks (not just parent-child)
- **Collaborative State**: Multiple users with separate focus points
---
**Last Updated**: 2025-11-14
**Spec Version**: {{VERSION}}
**Status**: Experimental (Pre-1.0)