AgentSkillsCN

Agent Context Handoff

智能体上下文交接

SKILL.md

Skill: Agent Context Management and Handoff

Version: 1.0
Status: Phase 4 Implementation
Author: Agent Task Management System
Date: 2026-02-16


Overview

This skill provides comprehensive guidance for agents to manage context, capture work state, and hand off cleanly between sessions using the td task management CLI integrated with openspec. The system enables smooth work continuity without requiring manual document parsing or maintenance.

Key Principle: Work in td, never manually edit spec files during handoff. Let pre-commit rendering keep documents synchronized.


Core Workflow: The Handoff Cycle

Phase 1: Session Start

Every time you begin work, establish context:

bash
# Start a new session (runs automatically with td usage --new-session)
td usage --new-session

# Check what issues are awaiting review or ready
td current

# Get full context for your task
td context <task-id>

Phase 2: Work in Progress

As you work, track progress and blockers:

bash
# Log progress (basic)
td log "Implemented feature X, moving to unit tests"

# Log a decision (important for next agent)
td log --decision "Chose async pattern over sync because..."

# Log a blocker (external dependency)
td log --blocker "Waiting on API schema from backend team - can't proceed until [date]"

# Log an attempted approach (don't re-try this)
td log --tried "Attempted regex-based parsing, too fragile for edge cases"

# Log a hypothesis (what you're testing)
td log --hypothesis "Theory: performance slowdown is in the sort function"

# Log a result (what you discovered)
td log --result "Profiler shows sort is not the bottleneck; it's the network call"

Phase 3: Handoff to Next Agent

When pausing or completing work, capture state:

bash
# Standard handoff with multiple sections
td handoff <task-id> \
  --done "Implemented core parsing logic with 95% test coverage" \
  --done "Added error handling for malformed inputs" \
  --remaining "Add integration tests with real API" \
  --remaining "Update documentation" \
  --decision "Used recursive descent parser for clarity over speed" \
  --uncertain "Not sure if current performance meets SLA; needs profiling"

# Alternative: Multi-line format
td handoff <task-id> <<EOF
done:
  - Implemented core feature
  - Added unit tests
remaining:
  - Integration tests
  - Performance tuning
  - Update docs
decisions:
  - Used async/await for better readability
  - Stored cache in memory instead of Redis
uncertain:
  - Does this meet the 100ms latency requirement?
  - Should we pre-warm the cache on startup?
EOF

# Quick handoff (minimal context)
td handoff <task-id> "Completed parsing, needs integration tests"

Phase 4: Resume Work

When coming back or another agent takes over:

bash
# Get complete context including previous handoffs and blockers
td context <task-id>

# See what blockers exist (is this task even unblocked?)
td context <task-id> | grep -i blocker

# Start fresh work
td start <task-id>

# Continue from previous context
td log "Resuming from previous session: [summary from context]"

Context Retrieval: What td context Provides

When you run td context <task-id>, you receive:

code
TASK DETAILS:
├─ Title & Description (what you're building)
├─ Acceptance Criteria (how to know when you're done)
├─ Status & Priority
└─ Parent Feature/Epic (what this contributes to)

PREVIOUS WORK (Handoff History):
├─ Done Items (what previous agents completed)
├─ Remaining Items (what they couldn't finish)
├─ Decisions Made (why they chose certain approaches)
├─ Uncertainties (open questions)
└─ Blockers (external dependencies preventing progress)

SESSION CONTEXT:
├─ Which agent/session worked on this
├─ When they worked on it
├─ How long it took
└─ Complete chronology of work across sessions

RELATED ARTIFACTS:
├─ Link to spec.md (if you want full requirement details)
├─ Link to proposal.md (if you want business context)
├─ Link to design.md (if you want architecture)
└─ Parent feature_id and spec_feature_id

Example usage:

bash
$ td context td-87cb57
Task: td-87cb57 [P2] "opsx-render command SHALL generate spec.md from td state"
Parent: td-9bdd82 (TD to OpenSpec Rendering)
Feature: td-31bda7 (Agent task management and auditing system)

ACCEPTANCE CRITERIA:
  - When opsx-render is invoked, it reads td state
  - Command outputs spec.md with all requirements
  - Task IDs and hierarchy are preserved
  - Output matches openspec template format

PREVIOUS HANDOFF (from ses_78f257):
Done:
  - Analyzed td task structure and data model
  - Identified required fields for rendering
  - Created data extraction algorithm
  
Remaining:
  - Implement opsx-render command
  - Add template rendering logic
  - Test with live td data
  
Decisions:
  - Using JSON export from td for data source
  - Jinja2 for template rendering (familiar, well-tested)
  - Output to stdout for pipeline compatibility
  
Uncertain:
  - Edge case: what if a task has no description?
  - Edge case: deeply nested hierarchy - how to handle?

Blockers:
  - None currently

[Full task context from archive/spec files available]

Requirement 1: Agent Handoff SHALL Capture Complete Work Context

Requirement ID: td-d3d2ae

Status: ✅ IMPLEMENTED (td CLI supports all features)

What You Need to Do

Use td handoff to document:

  1. What was completed (--done)

    • Specific, measurable accomplishments
    • Not vague ("did stuff"), be specific ("implemented UserRepository.findById with pagination")
    • Include test coverage if applicable
  2. What remains (--remaining)

    • Specific, actionable next steps
    • Don't say "finish the feature", say "add integration tests with mocked API and update UserService.test.ts"
    • Estimate effort if possible ("2-4 hours")
  3. Decisions made (--decision)

    • Why you chose this approach
    • What alternatives you considered and rejected
    • Key trade-offs ("chose async/await for readability over raw promises")
  4. Uncertainties (--uncertain)

    • Open questions that need resolving
    • Performance concerns that need profiling
    • Design decisions that need validation

Example Implementation

bash
# Work on a feature for a while...
# Then capture state before switching tasks

td handoff td-87cb57 \
  --done "Implemented JSON data extraction from td state" \
  --done "Created helper functions for requirement tree traversal" \
  --done "Added 14 unit tests with 95% coverage" \
  --remaining "Implement spec.md template rendering using Jinja2" \
  --remaining "Add acceptance criteria injection into rendered spec" \
  --remaining "Test with real openspec project structure" \
  --decision "Used JSON export (vs direct db query) for isolation and testability" \
  --decision "Chose Jinja2 template engine for its excellent error messages" \
  --uncertain "Will template render performance be acceptable for large specs (1000+ reqs)?" \
  --uncertain "Should we cache rendered output or always re-render from td?"

Acceptance Criteria

  • td handoff command accepts all context parameters (--done, --remaining, --decision, --uncertain)
  • ✅ Multiple items can be specified (repeatable flags)
  • ✅ Context is stored in td and retrievable via td context
  • ✅ Next agent can read full context without parsing spec files

Requirement 2: Context Retrieval SHALL Provide Agent-Ready Summary

Requirement ID: td-5788e3

Status: ✅ IMPLEMENTED (td CLI provides full context)

What You Need to Do

Use td context (or td show) to retrieve complete work context:

bash
# Get full context for a task
td context <task-id>

# Get context plus parent/child hierarchy
td context <task-id> --children

# Get machine-readable JSON (for scripts/integrations)
td context <task-id> --json

# Render markdown in descriptions for easier reading
td context <task-id> --render-markdown

What's Included

The output includes:

  • Task Details: Title, description, acceptance criteria, priority, status
  • Work History: All previous handoffs with --done, --remaining, --decision, --uncertain
  • Blocker Status: All logged blockers so you know what's preventing progress
  • Timeline: When each session worked on this and for how long
  • Hierarchy: Parent spec/feature/epic relationships
  • References: Links to proposal.md, design.md, spec.md if needed

Example Usage Patterns

bash
# Get context to understand what to do next
td context td-87cb57

# Check if task is blocked before starting work
td context td-87cb57 | grep -i blocker

# Show hierarchy to understand scope
td context td-87cb57 --children

# Get machine-readable for integration
td context td-87cb57 --json | jq '.handoffs'

# Render markdown for better readability
td context td-87cb57 --render-markdown

Acceptance Criteria

  • td context command returns all necessary information (title, description, acceptance criteria)
  • ✅ Previous handoffs are included (done/remaining/decision/uncertain)
  • ✅ Blocker information is visible in context
  • ✅ Output is human-readable and agent-friendly
  • ✅ Hierarchy information is clear (parent spec, feature_id, etc.)
  • ✅ No need to read spec files; context is self-contained

Requirement 3: Handoff Workflow SHALL Work Without Document Editing

Requirement ID: td-33624b

Status: ✅ IMPLEMENTED (workflow is pure td CLI)

What You Need to Do

IMPORTANT: Never manually edit spec.md or tasks.md during handoff or implementation.

The Pure-TD Workflow

bash
# Start session
td usage --new-session

# Work on a task
td start <task-id>

# Track progress as you work
td log "Implemented feature X"
td log --decision "Chose approach Y because..."
td log --blocker "Blocked on Z - waiting for API"

# When done or pausing
td handoff <task-id> \
  --done "..." \
  --remaining "..." \
  --decision "..." \
  --uncertain "..."

# NEXT AGENT: Resume work
td context <task-id>  # Read full context
td start <task-id>    # Start working

# NO EDITING OF: spec.md, tasks.md, proposal.md, design.md
# These are auto-rendered from td by pre-commit hooks

Why This Works

  1. You work in td (source of truth for task state)
  2. Pre-commit hooks render documents from td state automatically
  3. Next agent uses td context to resume (no document parsing needed)
  4. Documents stay synchronized because they're generated, not manually maintained

What NOT to Do

❌ Don't edit tasks.md manually
❌ Don't update spec.md with your changes
❌ Don't create new sections in proposal.md
❌ Don't track your context in documents

What TO Do

✅ Log to td with td log
✅ Handoff with td handoff
✅ Retrieve context with td context
✅ Let pre-commit rendering keep documents synchronized

Example: Complete Handoff Without Document Edits

bash
# Session 1 (Agent A)
td start td-87cb57
# ... work on implementation ...
td log "Completed data extraction layer"
td log --blocker "API schema not finalized; using mock for now"
td log --decision "Used JSON export for testability"
td handoff td-87cb57 \
  --done "Implemented data extraction from td JSON" \
  --done "Created helper functions for tree traversal" \
  --remaining "Implement spec.md template rendering" \
  --blocker "API schema still not finalized"
# NO DOCUMENT EDITS NEEDED - just td commands

# Session 2 (Agent B)
td context td-87cb57  # Reads Agent A's handoff, blockers, history
# Sees: "API schema not finalized; using mock for now"
# Can decide: work around the blocker or move to different task
td start td-87cb57
# ... continue from Agent A's context ...
td handoff td-87cb57 --done "..." --remaining "..."
# Again, NO DOCUMENT EDITS

Acceptance Criteria

  • ✅ Complete handoff uses only td CLI commands
  • ✅ No manual editing of spec.md, tasks.md, proposal.md, design.md
  • ✅ Next agent can resume using only td context <task-id>
  • ✅ Documents remain auto-generated and synchronized
  • ✅ Handoff is task-oriented, not document-oriented

Requirement 4: Context SHALL Capture Implementation Blockers

Requirement ID: td-67b096

Status: ✅ IMPLEMENTED (td CLI supports blocker logging)

What You Need to Do

Document blockers as they arise, so next agent knows what's preventing progress:

bash
# Document a blocker
td log --blocker "Waiting on backend API schema from platform team"

# Check blockers in context
td context <task-id> | grep -i blocker

# Filter to work on non-blocked tasks
td list --parent <epic> --filter "not blocked"

Blocker Types

External Dependency:

bash
td log --blocker "Blocked on API schema finalization by backend team (ETA Feb 20)"

Design Decision Needed:

bash
td log --blocker "Blocked on architecture decision: should caching be in-memory or Redis? Waiting on platform team decision"

Missing Information:

bash
td log --blocker "Blocked: need acceptance criteria clarification. Current spec is ambiguous on pagination limits"

Performance Concern:

bash
td log --blocker "Blocked: performance profiling shows 500ms latency, need investigation before proceeding"

Example Blocker Scenario

bash
# Session 1: Discover blocker
td start td-87cb57
# ... implement feature ...
td log "Implemented core logic, now need to integrate with API"
td log --blocker "API schema not ready. Backend team says ETA Feb 18. Using mock API for now"
td handoff td-87cb57 \
  --done "Implemented core rendering logic" \
  --remaining "Integrate with actual API once schema is available" \
  --remaining "Add integration tests with real API endpoints"

# Session 2: Check context, see blocker
td context td-87cb57
# Output includes:
#   BLOCKERS:
#     - API schema not ready. Backend team says ETA Feb 18. Using mock API for now

# Agent B can now:
# Option 1: Wait for blocker to clear
# Option 2: Do unblocked work (write integration tests while API is pending)
# Option 3: Work on other tasks and come back when blocker clears

Acceptance Criteria

  • td log --blocker command documents impediments
  • ✅ Blockers are visible in td context output
  • ✅ Next agent knows what work is blocked vs. unblocked
  • ✅ Clear visibility into external dependencies
  • ✅ Agents can filter/sort to find unblocked work

Requirement 5: Session Management SHALL Track Work Continuity

Requirement ID: td-742214

Status: ✅ IMPLEMENTED (td CLI tracks sessions automatically)

What You Need to Do

Work naturally with td sessions - they're tracked automatically:

bash
# Start session (at beginning of work)
td usage --new-session

# Work normally
td start <task-id>
td log "..."
td handoff <task-id> ...

# The system automatically tracks:
# - Which session made changes
# - When the session happened
# - How long work took
# - Complete audit trail

Session Workflow

bash
# Day 1: Agent A
td usage --new-session  # Creates session (ses_abc123)
td start td-87cb57
td log "Implemented feature X"
td handoff td-87cb57 --done "X" --remaining "Y"

# Next day: Agent B (or same agent, new session)
td usage --new-session  # Creates session (ses_def456)
td context td-87cb57
# Output includes:
#   WORK HISTORY:
#     Session ses_abc123 (Agent A): Implemented feature X
#     Session ses_def456 (Agent B): <current work>

td start td-87cb57
td log "Continuing from previous session: X is done, now doing Y"

Session Context Information

When you run td context <task-id>, you see:

code
WORK HISTORY:
├─ ses_78f257 @ 2026-02-16 14:32 (2h 15m)
│  ├─ Implemented core feature
│  ├─ Added unit tests
│  ├─ Decision: Used async pattern
│  └─ Remaining: Integration tests
│
├─ ses_ac9ed8 @ 2026-02-16 16:47 (45m)
│  ├─ Added integration tests
│  ├─ Found blocker: API not ready
│  └─ Remaining: Performance testing
│
└─ <current session>

Session Commands

bash
# View current session
td ws current

# List all sessions for a task
td context <task-id> | grep -i session

# See session details
td show <task-id> --long

# Label current session (optional)
td session "Agent B - Phase 4 Implementation"

Example: Multi-Session Work

bash
# Session 1: Initial implementation
td usage --new-session
td start td-87cb57
td log "Analyzing requirements"
td log --decision "Using Jinja2 for templating"
td handoff td-87cb57 \
  --done "Analyzed data model" \
  --remaining "Implement rendering logic"
# Handoff includes: timestamp, session ID, duration

# Session 2: Someone else resumes
td usage --new-session
td context td-87cb57
# Shows: Previous work by session 1, when it happened, what they did
td start td-87cb57
td log "Resuming: implementing Jinja2 template rendering"
td handoff td-87cb57 \
  --done "Implemented template rendering" \
  --remaining "Test with edge cases"

# Session 3: Another agent continues
td context td-87cb57
# Complete chronology visible:
# - Session 1: analyzed, decided on Jinja2
# - Session 2: implemented rendering
# - Session 3: <your work>

Acceptance Criteria

  • ✅ Sessions are created automatically with td usage --new-session
  • ✅ Session information is included in handoffs
  • ✅ Work history shows which session did what work
  • ✅ Complete audit trail of progress across sessions
  • ✅ Timestamps and duration tracked for each session
  • ✅ Next agent understands complete work progression

Integration with OpenSpec Workflow

Complete End-to-End Example

bash
# PROJECT: Adding new feature to platform

# PHASE 1: Create change with openspec
/opsx-new agent-task-management  # Creates proposal, proposal feature in td

# PHASE 2: Create specs and requirements (in td)
/opsx-continue                   # Guides you to create spec features and requirement tasks in td

# PHASE 3: Implement requirements
for task in $(td list --parent <spec_feature> --filter "status=open"); do
  # Get context for task
  td context $task
  
  # Start work
  td start $task
  
  # Log progress
  td log "Implementing feature X"
  td log --decision "Chose approach Y"
  
  # If blocked, document it
  td log --blocker "Waiting on Z"
  
  # When done, handoff
  td handoff $task \
    --done "Implemented X" \
    --remaining "Test and document" \
    --decision "Used approach Y" \
    --uncertain "Does performance meet SLA?"
done

# PHASE 4: Archive change (only when all tasks are done)
/opsx-archive agent-task-management  # Verifies td state matches docs

Pure-TD During Implementation

Key point: Once openspec is set up (proposal, specs, requirements in td):

  • You work entirely in td (start, log, handoff)
  • Never edit spec files manually
  • Pre-commit hooks auto-render documents
  • Next agent uses td context to resume

This reduces:

  • Token consumption (no document parsing needed)
  • Cognitive overhead (work in one system, not juggling documents)
  • Synchronization issues (documents auto-generated)

Troubleshooting

"I lost context - what was I working on?"

bash
td current              # What you're currently working on
td context <task-id>    # Full context for any task

"Task is blocked - what should I do?"

bash
td context <task-id> | grep -i blocker  # See what's blocking it
td list --filter "not blocked"          # Find unblocked work

"How do I know if previous work is complete?"

bash
td context <task-id>    # Read their handoff
# Look at: --remaining section (what they left undone)

"Should I manually update spec.md?"

NO. Never manually edit spec files. Let pre-commit rendering handle it.

Instead:

bash
td log "..."            # Log your progress
td handoff <task-id>    # Capture state
# Pre-commit will auto-render spec.md from td

"How do I track my work across multiple sessions?"

bash
td handoff <task-id> --done "..." --remaining "..."  # Each session
td context <task-id>                                  # See full history

Best Practices

1. Context is Everything

Before starting: td context <task-id> to understand what's already been done

2. Log as You Go

Don't wait until the end to capture context:

bash
td log "Just implemented feature X"
td log --decision "Chose approach Y because of Z"

3. Handoff for Handoffs

When stopping work (even briefly):

bash
td handoff <task-id> --done "..." --remaining "..."

Even if only pausing for 30 minutes, capture state.

4. Block Documentation

Found a blocker? Document immediately:

bash
td log --blocker "Blocked on X - waiting on Y team"

Don't wait for handoff. Next agent needs to know ASAP.

5. Decisions Matter

Other agents will re-discover your decisions if not documented:

bash
td log --decision "Chose async/await over callbacks because of readability"

6. Never Touch Documents During Work

This is critical. Let pre-commit rendering keep documents in sync:

❌ Don't: Edit spec.md, tasks.md, proposal.md, design.md
✅ Do: Work in td, let pre-commit render documents


Summary

The agent context management system enables:

  • Clean handoffs: Use td commands, never manual document editing
  • Complete context: td context provides all information needed to resume
  • Blocker visibility: External dependencies are tracked and visible
  • Work continuity: Sessions and timestamps track progression
  • Token efficiency: No document parsing needed; td is source of truth

Key insight: Work in td, let pre-commit rendering keep documents synchronized. This reduces cognitive load and token consumption while maintaining complete audit trails.


Related Resources

  • Specification: openspec/changes/archive/2026-02-16-agent-task-management/specs/agent-context-management/spec.md
  • td Task Management: .opencode/skills/td-task-management/SKILL.md
  • OpenSpec Workflow: .opencode/skills/openspec-apply-change/SKILL.md
  • Command Reference: td --help, td handoff --help, td context --help, td log --help