Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

266 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Agent Trajectories

Capture the complete "train of thought" of agent work as first-class artifacts.

When an agent completes a task today, the only artifacts are code changes, commit messages, and PR descriptions. The rich context of how the work happened disappears: why approach A was chosen over B, what dead ends were explored, what assumptions were made.

Agent Trajectories captures this missing context as structured, searchable, portable records that travel with the code.

What is a Trajectory?

A trajectory is the complete story of agent work on a task:

  • Chapters - Logical segments of work (exploration, implementation, testing)
  • Events - Prompts, tool calls, decisions, messages between agents
  • Retrospective - Agent reflection on what was accomplished, challenges faced, and lessons learned
  • Artifacts - Links to commits, files changed, and external task references

Key Features

Platform Agnostic

Works with any task system: Beads, Linear, Jira, GitHub Issues, or standalone. Trajectories are a universal format—like Markdown for documentation.

Multiple Storage Backends

  • File system (default) - .agentworkforce/trajectories/ directory, git-friendly
  • SQLite - Local indexing and search
  • PostgreSQL/S3 - For teams and archival

Rich Export Formats

  • Markdown - Notion-style pages for documentation
  • Timeline - Linear-style chronological view
  • JSON - Full structured data for tooling

Native Multi-Agent Support

Trajectories is built for teams of agents working together:

  • Shared trajectory — Multiple agents collaborate on a single task record
  • Agent participation — Each agent logged as lead, contributor, or reviewer with timestamps
  • Chapter handoffs — When work moves between agents, chapters capture the context shift
  • Cross-agent messaging — Integrates with agent-relay to record inter-agent communication as trajectory events
  • Parallel coordination — Multiple agents working in parallel on related tasks can reference each other's trajectories

This is a key differentiator: no other tool in the AI dev stack tracks who (which agent, which model) made which decisions and why, across a coordinated multi-agent workflow.

Integration Ready

  • Complements claude-mem for observation-level memory
  • Integrates with agent-relay for multi-agent messaging
  • Agent Trace integration - Automatic code attribution following agent-trace.dev spec

Code Attribution (Agent Trace)

Trajectories automatically generate Agent Trace records that attribute code changes to AI agents:

trail start "Implement auth module"# ... agent writes code, makes commits ...
trail complete --summary "Added JWT auth" --confidence 0.85
# View trace attribution
trail show traj_abc123 --trace

What you get:

  • .trace.json files saved alongside each trajectory
  • Line-level attribution of which code was AI-generated
  • Model identification (Claude, GPT, etc.)
  • Git revision tracking for change history

Zero configuration required - traces are generated automatically when completing trajectories in a git repository.

See the full Agent Trace Integration Spec for details.

Use Cases

Code Review

Instead of guessing at intent from 500 changed lines, reviewers can:

  • Read the trajectory summary
  • See what alternatives were considered and rejected
  • Understand the agent's confidence level

Bug Diagnosis

When a bug surfaces months later:

  • Query the trajectory for the commit that introduced the code
  • See original requirements and edge cases considered
  • Understand the context that led to this implementation

Institutional Memory

Over time, trajectories become a searchable knowledge base:

  • "How have we solved caching problems before?"
  • "What libraries did we evaluate for X?"
  • "Why did we choose this architecture?"

Quick Start

CLI

# Run without installing globally
npx --yes agent-trajectories start "Implement auth module"# Or install globally if you prefer the short trail command
npm install -g agent-trajectories
trail start "Implement auth module"# Or install locally in a project
npm install agent-trajectories
npx --no-install trail start "Implement auth module"# or
npm exec -- trail start "Implement auth module"
# Start tracking a task
trail start "Implement auth module"# (for non-global installs, replace `trail` with# `npx --yes agent-trajectories`, `npx --no-install trail`, or `npm exec -- trail`)# View current status
trail status
# Record a decision (reasoning optional for minor decisions)
trail decision "Chose JWT over sessions" \
--reasoning "Stateless scaling requirements"# Complete with retrospective
trail complete --summary "Added JWT auth" --confidence 0.85
# List all trajectories (with optional search)
trail list
trail list --search "auth"# Export for documentation (markdown, json, timeline, or html)
trail export traj_abc123 --format markdown
trail export --format html --open # Opens in browser# Compact trajectories (consolidate similar decisions)
trail compact # Uncompacted trajectories (default)
trail compact --branch main # Trajectories with commits not in main
trail compact --commits abc1234,def5678 # Trajectories matching specific commit SHAs
trail compact --pr 123 # Trajectories mentioning PR #123
trail compact --since 7d # Last 7 days
trail compact --all # Everything (including previously compacted)
trail compact --pr 123 --discard-sources # Delete source trajectories after compaction

Automatic Compaction (GitHub Action)

Add these steps to any workflow that runs on PR merge (e.g., your release or publish flow). Requires ref: ${{ github.event.pull_request.base.ref }} and fetch-depth: 0 on checkout, plus contents: write permission.

Use --discard-sources when the compacted summary should replace the raw source trajectories. This removes the source JSON/Markdown/trace files, reducing future list/search noise.

 - name: Compact trajectoriesrun: | PR_COMMITS=$(git log ${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }} --format=%H | paste -sd, -) OUTPUT=".agentworkforce/trajectories/compacted/pr-${{ github.event.pull_request.number }}.json" if [ -n "$PR_COMMITS" ]; then npx agent-trajectories compact --commits "$PR_COMMITS" --output "$OUTPUT" --discard-sources else npx agent-trajectories compact --pr ${{ github.event.pull_request.number }} --output "$OUTPUT" --discard-sources fi - name: Commit compacted trajectoriesrun: | git add .agentworkforce/trajectories/ || true git diff --cached --quiet || \ (git commit -m "chore: compact trajectories for PR #${{ github.event.pull_request.number }}" && git push)

SDK

For programmatic usage, install the package and use the SDK:

npm install agent-trajectories

Using the Client (with storage):

import{TrajectoryClient}from'agent-trajectories';constclient=newTrajectoryClient({defaultAgent: 'my-agent'});awaitclient.init();// Start a new trajectoryconstsession=awaitclient.start('Implement auth module');// Record work in chaptersawaitsession.chapter('Research');awaitsession.note('Found existing auth patterns');awaitsession.finding('Current system uses sessions');// Record decisionsawaitsession.decide('JWT vs Sessions?','JWT','Better for horizontal scaling');// Complete with retrospectiveawaitsession.done('Implemented JWT-based authentication',0.9);awaitclient.close();

Using the Builder (in-memory, no storage):

import{trajectory}from'agent-trajectories';constresult=trajectory('Fix login bug').withSource({system: 'github',id: 'GH#456'}).chapter('Investigation','claude').finding('Null pointer in session handler').decide('Fix approach','Add null check','Minimal change').chapter('Implementation','claude').note('Added validation').done('Fixed null pointer exception',0.95);// Export the trajectoryconsole.log(result);// Full trajectory object

SDK Features:

  • Auto-save: Changes persist automatically with the client
  • Fluent API: Chain operations naturally
  • Resume support: Pick up where you left off with client.resume()
  • Multiple exports: Markdown, JSON, timeline, PR summary

Why "Trail"?

Trajectory = the complete path an agent takes through a task Trail = what's left behind for others to follow

You don't see the whole trajectory in real-time, but you can always follow the trail.

The CLI is called trail because that's what you're doing—leaving a trail of breadcrumbs through your work. Future agents and humans can follow this trail to understand not just what was built, but why it was built that way.

Who Uses Trail?

Both agents and humans—but differently.

Agents: Write the Trail

Agents use trail commands to record their work as they go:

# Agent starts work on a task
trail start "Add rate limiting to API"# Agent records key decisions as it works
trail decision "Token bucket algorithm" \
--reasoning "Better burst handling than fixed window"# Agent completes with reflection
trail complete --summary "Added rate limiting" --confidence 0.9

This can be invoked programmatically by AI coding tools, or agents can learn to call trail as part of their workflow.

Humans: Read the Trail

Humans use trail commands to understand and review agent work:

# List and search past work
trail list --search "authentication"# See trajectory details and decisions
trail show traj_abc123 --decisions
# View in browser
trail export traj_abc123 --format html --open
# Export for code review
trail export traj_abc123 --format markdown

The Handoff

The trail bridges the gap between agent work and human understanding:

Agent works → Records decisions → Completes trajectory
↓
Human reviews → Follows the trail → Understands the "why"

Without the trail, humans see only the code. With it, they see the reasoning.

Agent Workspace

Trajectories power a broader vision: a knowledge workspace for agents—like Notion, but for AI.

┌─────────────────────────────────────────────────────────────────┐
│ AGENT WORKSPACE │
├─────────────────────────────────────────────────────────────────┤
│ 📚 Knowledge Base 🛤️ Trajectories │
│ ├── Architecture docs ├── Active work │
│ ├── Code patterns ├── Recent history │
│ └── Conventions └── Searchable archive │
│ │
│ 🧠 Decision Log 📋 Pattern Library │
│ └── Why things are └── How to do things │
└─────────────────────────────────────────────────────────────────┘

When an agent starts a new task, it can query the workspace for:

  • Relevant past trajectories
  • Applicable patterns and conventions
  • Related decisions
  • Potential gotchas from retrospectives

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES (Layer 3) │
│ Task narratives, decisions, retrospectives │
│ ▲ │
│ │ aggregates │
│ CLAUDE-MEM (Layer 2) │
│ Tool observations, semantic concepts │
│ ▲ │
│ │ captures │
│ AGENT-RELAY (Layer 1) │
│ Real-time messaging, message persistence │
└─────────────────────────────────────────────────────────────────┘

Each layer is independent and can be used alone, but together they form a complete agent memory stack.

The Narrative Layer in Your AI Stack

Trajectories sits at the top of an emerging ecosystem of AI development tools. Each layer answers a different question:

┌─────────────────────────────────────────────────────────────────┐
│ AGENT-TRAJECTORIES │
│ "Why was this built this way?" │
│ Narrative, decisions, retrospectives, institutional memory │
│ ▲ │
│ │ gives meaning to │
│ ENTIRE (entireio/cli) │
│ "What happened in this session?" │
│ Raw session capture, transcripts, recovery, rewind │
│ ▲ │
│ │ attributes │
│ AGENT-TRACE (agent-trace.dev) │
│ "Who wrote this line of code?" │
│ Line-level code attribution, model identification │
└─────────────────────────────────────────────────────────────────┘

Agent Trace (agent-trace.dev) is the attribution spec — trajectories implements it automatically, generating .trace.json files that comply with the spec on every trail complete.

Entire (entireio/cli) captures raw session transcripts via git hooks — a complementary layer focused on recovery and rewind.

Trajectories is the narrative layer: structured meaning on top of raw events. Where entire captures what happened, trajectories captures why decisions were made and what was learned. Where agent-trace says who wrote the code, trajectories explains why this approach was chosen.

Used together, these tools give you a complete audit trail of AI-assisted development from attribution through narrative.

The Trajectory Format

{
"id": "traj_abc123",
"task": {
"title": "Implement user authentication",
"source": { "system": "linear", "id": "ENG-456" }
},
"status": "completed",
"chapters": [...],
"retrospective": {
"summary": "Implemented JWT-based auth with refresh tokens",
"decisions": [...],
"confidence": 0.85
}
}

Trajectories are stored as .trajectory.json files (machine-readable) with auto-generated .trajectory.md summaries (human-readable).

Why Trajectories Matter

"The trajectory is as valuable as the code."

As AI agents write more code faster than ever before, a critical gap emerges: we're shipping code without understanding. Trajectories close this gap.

The Health of Your Codebase

Without trajectories, agent-generated code becomes a black box:

ProblemImpactHow Trajectories Help
Silent assumptionsBugs hide in undocumented edge casesDecisions and reasoning are captured explicitly
Inconsistent patternsEach agent reinvents approachesPast solutions are queryable, patterns emerge
Lost contextNobody knows why code existsThe "why" lives alongside the "what"
Review theaterPRs approved without real understandingReviewers see the full decision history
Debugging blindHours spent reverse-engineering intentOriginal context is one query away

The Flywheel Effect

Trajectories create a virtuous cycle that compounds over time:

More trajectories → More extracted knowledge → Better agent context →
Better decisions → Better retrospectives → Richer trajectories → ...

Each completed task makes future tasks easier:

  • Agents make fewer mistakes by learning from past gotchas
  • Decisions are more consistent across the codebase
  • Onboarding new agents (or humans) becomes instant
  • Institutional memory persists even as team members change

Future-Proofing Your Project

As agent usage scales, trajectories become essential infrastructure:

Today (1-2 agents):

  • Nice to have for code review
  • Helpful for debugging

Tomorrow (5-10 agents working in parallel):

  • Critical for coordination
  • Required for understanding who did what and why
  • Enables agents to learn from each other

Long-term (agents as primary contributors):

  • The authoritative record of how the system evolved
  • Training data for project-specific agent improvements
  • Audit trail for compliance and security review

Trust Through Transparency

Agent-generated code faces a trust problem. Developers hesitate to ship code they don't understand. Trajectories solve this by making agent reasoning transparent:

  • Confidence scores tell you when to scrutinize more carefully
  • Decision logs show trade-offs were considered
  • Retrospectives surface known limitations and risks
  • Challenge documentation reveals what was hard (and might break)

The result: teams can ship agent code with the same confidence as human-written code—because they understand it just as well.

Installation

npm install agent-trajectories

The package provides:

  • CLI (trail command) - For command-line usage
  • SDK - For programmatic integration
// Main import (includes SDK)import{TrajectoryClient,trajectory}from'agent-trajectories';// Or import from SDK subpathimport{TrajectoryClient,TrajectoryBuilder}from'agent-trajectories/sdk';

SDK Reference

TrajectoryClient

The client manages trajectories with persistent storage.

constclient=newTrajectoryClient({defaultAgent: 'my-agent',// Default agent namedataDir: '.',// Base directory; stores under .agentworkforce/trajectoriesautoSave: true,// Auto-save after operations});awaitclient.init();// Required before use// Lifecycleconstsession=awaitclient.start('Task title');constsession=awaitclient.resume();// Resume active trajectoryconsttraj=awaitclient.get('traj_xxx');// Get by ID// Queryconstlist=awaitclient.list({status: 'completed'});constresults=awaitclient.search('auth');// Exportconstmd=awaitclient.exportMarkdown('traj_xxx');constjson=awaitclient.exportJSON('traj_xxx');awaitclient.close();

TrajectorySession

Sessions provide chainable operations on active trajectories.

constsession=awaitclient.start('Task');// Chapters organize work phasesawaitsession.chapter('Research');awaitsession.chapter('Implementation');// Events record what happenedawaitsession.note('Observation or note');awaitsession.finding('Important discovery');awaitsession.error('Something went wrong');// Decisions capture choicesawaitsession.decide('Question?','Choice','Reasoning');// Complete or abandonawaitsession.done('Summary of work',0.9);awaitsession.abandon('Reason for abandoning');

TrajectoryBuilder

The builder creates trajectories in memory without storage.

import{trajectory,TrajectoryBuilder}from'agent-trajectories';// Shorthand functionconstt=trajectory('Task title').chapter('Work','agent-name').note('Did something').done('Completed',0.9);// Or use the class directlyconstt=TrajectoryBuilder.create('Task').withDescription('Detailed description').withSource({system: 'linear',id: 'ENG-123'}).withTags('feature','auth').chapter('Phase 1','claude').complete({summary: 'What was done',approach: 'How it was done',confidence: 0.85,challenges: ['What was hard'],learnings: ['What was learned'],});

Roadmap

This project is in early development. See PROPOSAL-trajectories.md for the full design document.

v1.0 (current)

  • File-based storage (.agentworkforce/trajectories/)
  • Core CLI commands (start, decision, complete, list, show, export)
  • Agent Trace spec compliance (.trace.json generation)
  • Multi-agent participation tracking
  • Rich export formats (Markdown, JSON, Timeline, HTML)

v1.1 (next)

  • MCP server — Real-time bidirectional queries so Claude Code, Cursor, and other tools can read and write trajectories directly within agent sessions
  • Claude Code hooks — Auto-capture on PostToolUse and session boundaries
  • SQLite storage — Full-text search across all trajectories
  • Git hook integration — Auto-start/complete trajectories on commit events
  • CLAUDE.md generation — Extract patterns from trajectories into reusable context files

Future

  • Workspace knowledge base (decisions, patterns, conventions as queryable memory)
  • PostgreSQL/S3 storage for teams
  • Training data export for project-specific model fine-tuning

License

MIT

About

Document layer for agent work

Resources

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages