Skip to content

Latest commit

 

History

History
3124 lines (2246 loc) · 96.7 KB

File metadata and controls

3124 lines (2246 loc) · 96.7 KB

Agent Baton CLI Reference

Complete command reference for the baton CLI. Every command, flag, and option is documented here with syntax, defaults, and usage examples.


Overview

The baton CLI is a flat-subcommand tool powered by argparse. All command modules live under agent_baton/cli/commands/ and are auto-discovered at startup. Each module exposes register(subparsers) and handler(args).

Commands are organized into functional groups:

Group Concern Commands
Execution Plan, execute, and manage orchestrated tasks plan, execute, status, daemon, async, decide
Manager Mode PMO planning overlay -- charter, team blueprint, scope contracts, knowledge-pack lifecycle plan --manager-mode, config, report, team, knowledge list/scan/show/audit/propose
Observe Traces, usage, dashboards, telemetry dashboard, trace, usage, telemetry, context-profile, retro, context, cleanup
Guardrails Risk, policy, compliance, validation classify, compliance, policy, escalations, validate, spec-check, detect
Improve Scoring, learning, patterns, budgets scores, learn, patterns, budget, changelog, anomalies
Knowledge Knowledge pack validation, search, briefing, lifecycle, effectiveness knowledge doctor, knowledge search, knowledge resolve, knowledge brief, knowledge harvest, knowledge stale, knowledge deprecate, knowledge retire, knowledge sweep, knowledge usage, knowledge effectiveness, knowledge ranking, knowledge ab
Distribute Packaging, publishing, installation package, publish, pull, install, transfer
Agents Agent discovery, routing, events agents, route, events, incident
PMO Portfolio management overlay pmo serve, pmo status, pmo add, pmo health
Sync Federated data sync sync, sync status
Query Project-local structured queries query
Cross-Project Query Cross-project SQL against central.db cquery
Source External work-item connections source add, source list, source sync, source remove, source map
Diagnostics Installation and workspace health checks doctor
API HTTP API server serve

Installation & Setup

# Install the package in editable mode with dev dependencies
pip install -e ".[dev]"

# Install with API server support (FastAPI + uvicorn)
pip install -e ".[api]"

# Deploy agent definitions to ~/.claude/agents/ and references
scripts/install.sh

# Or use the CLI installer
baton install --scope user --source /path/to/agent-baton-repo

After installation, the baton command is available globally via the console script entry point.


Execution Commands

baton plan

Create a data-driven execution plan for an orchestrated task.

baton plan SUMMARY [options]
Argument Required Default Description
SUMMARY Yes -- Natural-language task summary
--task-type TYPE No auto-detected Override task type: new-feature, bug-fix, refactor, data-analysis, documentation, migration, test
--agents LIST No auto-selected Comma-separated agent names; bypasses auto-selection
--project PATH No cwd Project root for stack detection
--json No false Output plan as JSON instead of markdown
--save No false Write plan.json and plan.md to .claude/team-context/
--explain No false Print explanation of plan choices
--manager-mode No false Post-process the plan into manager-mode PMO sidecar artifacts (project charter, scope map, team blueprint, role cards, knowledge plan, scope contracts, context bundles, manager brief) under .claude/team-context/executions/<task_id>/. Also enabled by manager_mode.enabled_by_default in .claude/baton.yaml. See Manager Mode Commands below.
--dry-run No false Preview the plan + cost/token forecast without saving. Mutually exclusive with --save (exits 2 if both are passed).
--gate-scope SCOPE No sentinel (unset) How broadly gate commands run: focused (scopes pytest to test files covering changed source paths), full (legacy unscoped pytest / pytest --cov), smoke (import-only / collect-only). When omitted, the planner's own default applies; in manager mode, an omitted flag lets gates.gate_scope from the manager config apply instead (see below).
--knowledge PATH No -- Attach a knowledge document file globally to all steps (repeatable)
--knowledge-pack PACK No -- Attach a knowledge pack by name globally to all steps (repeatable)
--intervention LEVEL No low Escalation threshold for knowledge gaps: low, medium, high
--goal CONDITION No -- Completion condition (G1). The engine evaluates the goal after each gate passes and uses amend_plan to round out gaps until met, exhausted, or the token ceiling is hit.
--max-amend-cycles N No 3 Goal round-out budget (meaningful only with --goal).

Manager mode:

--manager-mode sets plan.manager_mode = true regardless of --save/--dry-run, but the PMO artifacts (charter, scope map, blueprint, role cards, knowledge plan, scope contracts, context bundles, manager-brief.md) are only built when combined with one of those two flags:

  • --manager-mode --save: builds and writes the full artifact set to .claude/team-context/executions/<task_id>/, prints an Artifacts: path list after the normal save output. The PMO layer's PhasePolicyApplier (adversarial-review step injection, gate rescoping) runs before plan.json/plan.md are written, so the saved plan already reflects any injected review steps.
  • --manager-mode --dry-run: builds the same artifact set in memory only and prints it as a preview list (Manager Mode artifacts (preview only -- nothing written)) alongside the compact plan forecast; nothing touches disk. --json --dry-run --manager-mode includes the preview under a manager_mode_artifacts key.
  • --manager-mode alone (no --save, no --dry-run): prints markdown/JSON like a normal plan with manager_mode: true stamped on it, but builds no PMO artifacts.
  • --manager-mode --explain --save: appends a ## Manager Mode section (workstreams + owners, team roles, and the effective adversarial-review/handoff/gate-scope policy) to explanation.md.
  • --manager-mode + --gate-scope: an explicit --gate-scope always wins over the manager config's gates.gate_scope. Left unset, gates are rescoped to gates.gate_scope only when gates.mode (in .claude/baton.yaml) is project_configured (the default); other gates.mode values are recorded on the blueprint but do not change gate commands this increment.

A malformed .claude/baton.yaml manager section is a hard error only when --manager-mode was explicitly passed; otherwise it downgrades to a warning and manager mode stays off. See docs/internal/manager-mode-pmo-design.md for the full artifact schema.

Examples:

# Create and save a plan with explanation
baton plan "Add JWT authentication middleware and integration tests" --save --explain

# Create a plan with explicit agents
baton plan "Migrate database schema" --save --agents "backend-engineer--python,test-engineer"

# Create a plan with attached knowledge
baton plan "Implement payment processing" --save \
    --knowledge docs/payment-api.md \
    --knowledge-pack compliance-rules

# Output plan as JSON for programmatic consumption
baton plan "Add caching layer" --json

# Preview manager-mode PMO artifacts without writing anything
baton plan "Roll out multi-tenant billing" --manager-mode --dry-run

# Save a plan with the full manager-mode PMO layer
baton plan "Roll out multi-tenant billing" --manager-mode --save --explain

Related: baton execute start, baton classify, baton detect, baton config, baton report, baton team


baton goal

Plan against a completion condition and let the engine drive amend cycles until met (G1).

baton goal CONDITION [options]
Argument Required Default Description
CONDITION Yes -- A single quoted sentence describing what "done" means
--max-amend-cycles N No 3 Maximum goal-driven round-out cycles
--task-type TYPE No auto Passed through to baton plan
--complexity LEVEL No auto light / medium / heavy
--project PATH No cwd Project root
--knowledge PATH No -- Repeatable; passed through
--knowledge-pack PACK No -- Repeatable; passed through
--model NAME No -- Default model for dispatched agents
--gate-scope SCOPE No focused focused / full / smoke
--intervention LEVEL No low Knowledge-gap escalation aggressiveness
--explain No false Write an explanation.md alongside the saved plan
--verbose No false Print the full plan markdown after save
--no-execute No false Stop after planning; do not print "next: baton execute start"

Behavior: equivalent to baton plan CONDITION --save --goal CONDITION --max-amend-cycles N followed by guidance to run baton execute start. The engine evaluates the goal at every gate-pass boundary; if not met and budget remains, it inserts evaluator-suggested phases via amend_plan. Termination conditions: goal met, amend budget exhausted, or BATON_RUN_TOKEN_CEILING hit.

Evaluator selection (via BATON_GOAL_EVALUATOR env var):

  • stub — deterministic, no LLM (default fallback)
  • haiku (default when ANTHROPIC_API_KEY is set) — Claude Haiku 4.5
  • opus — Claude Opus 4.8

Safety rail: any evaluator that returns met=True is overridden to met=False unless the most-recent gate passed. This prevents premature claims.

Example:

baton goal "all four integration tests pass under load" --max-amend-cycles 5
baton execute start

See docs/internal/agent-teams-and-goal-design.md for the design rationale.


baton execute

Drive an orchestrated task through the execution engine. This is a command group with multiple subcommands.

For a plan saved with plan.manager_mode = true (see baton plan --manager-mode), dispatch prompts additionally carry a scope-contract and context-bundle section per step, and phase completion/final completion best-effort refresh the phase handoff and manager-report.md sidecars -- the action loop and _print_action() output shape are unchanged. When a dispatched agent reports a SCOPE_EXPANSION: <path> — <reason> signal, scoping.scope_expansion_policy (.claude/baton.yaml) routes it to one of three outcomes: allow_with_note (proceed, record a bead), queue_for_manager (create a manager decision packet, proceed), or block (the step fails immediately, pending a plan amendment to bring the work into scope).

baton execute start

Initialize execution state from a saved plan and return the first action.

baton execute start [--plan PATH] [--task-id ID]
Argument Required Default Description
--plan PATH No .claude/team-context/plan.json Path to plan.json
--task-id ID No auto Target a specific execution by task ID

Side effects:

  • Creates execution-state.json in the task-scoped directory
  • Starts an in-memory trace
  • Publishes a task.started event
  • Sets the active execution marker
  • Prints Session binding: export BATON_TASK_ID=<task-id>

Example:

baton plan "Add API endpoints" --save --explain
baton execute start
# Copy the BATON_TASK_ID export from the output
export BATON_TASK_ID=task-abc123

baton execute next

Return the next action the orchestrator should perform.

baton execute next [--all] [--task-id ID]
Argument Required Default Description
--all No false Return all dispatchable actions as a JSON array (for parallel dispatch)
--task-id ID No auto Target a specific execution

Without --all, prints a single action in human-readable format. With --all, prints a JSON array of all steps whose dependencies are satisfied.

Action types returned: DISPATCH, GATE, APPROVAL, COMPLETE, FAILED, WAIT, TEAM_DISPATCH.


baton execute dispatched

Mark a step as in-flight (dispatched but not yet complete).

baton execute dispatched --step-id ID --agent NAME [--task-id ID]
Argument Required Description
--step-id ID Yes Step identifier, e.g. 1.1
--agent NAME Yes Agent name, e.g. backend-engineer--python

Output: {"status": "dispatched", "step_id": "1.1"}

Call this immediately after spawning a subagent, before baton execute record.


baton execute record

Record the outcome of a completed or failed step.

baton execute record --step-id ID --agent NAME [options] [--task-id ID]
Argument Required Default Description
--step-id ID Yes -- Step identifier, e.g. 1.1
--agent NAME Yes -- Agent name
--status STATUS No complete complete or failed (no other values accepted)
--outcome TEXT No "" Free-text summary of what the agent did
--files LIST No "" Comma-separated list of files changed
--commit HASH No "" Git commit hash
--tokens N No 0 Estimated token count
--duration N No 0.0 Duration in seconds (float)
--error TEXT No "" Error detail if --status failed

Example:

baton execute record \
    --step-id 1.1 \
    --agent backend-engineer--python \
    --status complete \
    --outcome "Added JWT middleware with login/logout endpoints" \
    --files "app/auth.py,app/routes.py" \
    --commit abc123f

baton execute gate

Record the result of a QA gate check.

baton execute gate --phase-id N --result pass|fail [--output TEXT] [--task-id ID]
Argument Required Description
--phase-id N Yes Integer phase ID (1-based)
--result Yes pass or fail
--output TEXT No Gate command output or reviewer notes

Example:

# Run the gate command, then record the result
pytest tests/ > /tmp/gate-output.txt 2>&1
baton execute gate --phase-id 1 --result pass --output "$(cat /tmp/gate-output.txt)"

baton execute approve

Record a human approval decision for a phase with approval_required=True.

baton execute approve --phase-id N --result DECISION [--feedback TEXT] [--task-id ID]
Argument Required Description
--phase-id N Yes Phase ID requiring approval
--result Yes approve, reject, or approve-with-feedback
--feedback TEXT No Feedback text (required for approve-with-feedback)

State transitions:

  • approve -- execution continues to gate or next phase
  • reject -- engine sets status to failed
  • approve-with-feedback -- inserts a remediation phase with the feedback injected

Example:

baton execute approve --phase-id 2 --result approve-with-feedback \
    --feedback "Add error handling for the edge case where token is expired"

baton execute amend

Amend the running plan by adding phases or steps during execution.

baton execute amend --description TEXT [options] [--task-id ID]
Argument Required Description
--description TEXT Yes Why this amendment is needed (audit log)
--add-phase NAME:AGENT No Add a phase (repeatable)
--after-phase N No Insert new phases after this phase ID (default: append)
--add-step PHASE_ID:AGENT:DESC No Add step to existing phase (repeatable)

Example:

# Add a security review phase after phase 2
baton execute amend \
    --description "Security review needed for auth changes" \
    --add-phase "security-review:security-reviewer" \
    --after-phase 2

# Add a step to an existing phase
baton execute amend \
    --description "Need migration script for schema change" \
    --add-step "1:backend-engineer--python:Write database migration script"

baton execute team-record

Record a team member completion within a team step.

baton execute team-record --step-id S --member-id M --agent NAME [options] [--task-id ID]
Argument Required Default Description
--step-id S Yes -- Parent team step ID, e.g. 2.1
--member-id M Yes -- Team member ID, e.g. 2.1.a
--agent NAME Yes -- Agent name
--status No complete complete or failed
--outcome TEXT No "" Summary of work done
--files F No "" Comma-separated files changed
--hook-source SOURCE No "" When invoked from an external Claude Code Agent Teams hook, set to claude-teams. Tags the team mailbox event with the source for audit. See A1.c in docs/internal/agent-teams-and-goal-design.md.

baton execute complete

Finalize a completed execution run.

baton execute complete [--task-id ID]

Side effects:

  • Sets execution state status = complete
  • Writes trace file to .claude/team-context/traces/
  • Writes usage record to usage-log.jsonl
  • Generates retrospective to retrospectives/
  • Publishes task.completed event
  • Auto-syncs to central.db (best-effort)

baton execute status

Show current execution state without advancing it.

baton execute status [--task-id ID]

Output:

Task:    abc123
Bound:   BATON_TASK_ID
Status:  running
Phase:   1
Steps:   2/4
Gates:   1 passed, 0 failed
Elapsed: 145s

baton execute resume

Resume execution after a crash or interrupted session.

baton execute resume [--task-id ID]

Loads execution-state.json from disk, reconnects the trace, and returns the next action. Steps in dispatched status will be re-dispatched.


baton execute export

Snapshot an execution's full state to a JSON file (read-only).

baton execute export [--task-id ID] [--to PATH]

Replaces the legacy FileStorage primary backend (removed from the factory in slice 15 of the SQLite-parity migration). The default output path is execution-state.json in the current working directory; the parent directory is created if it doesn't exist.

The exported JSON is state.to_dict() — exactly the on-disk shape the file backend used to write — so existing tooling that consumed execution-state.json continues to work against the export.

Storage-internal fields like the OCC version and the in-memory _loaded_version PrivateAttr are intentionally omitted.


baton execute list

List all executions (active and completed).

baton execute list

Output:

  TASK ID                                 STATUS              STEPS      PID  SUMMARY
------------------------------------------------------------------------------------------
* task-auth-abc                           running               2/4      -  Add JWT auth middleware...
  task-fix-xyz                            complete              3/3      -  Fix dashboard rendering...

Active execution is marked with *.


baton execute switch

Switch the active execution to a different task ID.

baton execute switch TASK_ID
Argument Required Description
TASK_ID Yes Task ID to switch to

baton status

Show team-context file status (which recovery files exist).

baton status

Output:

Team context status:
  + plan.json
  + execution-state.json
  - context.md
  + mission-log.md

Related: baton execute status


baton daemon

Background execution management. Runs the async worker (and optionally the HTTP API server) as a daemon process.

baton daemon start

baton daemon start --plan FILE [options]
Argument Required Default Description
--plan FILE Yes* -- Path to MachinePlan JSON file (*required unless --resume)
--max-parallel N No 3 Maximum parallel agents
--dry-run No false Use DryRunLauncher (no real agent calls)
--foreground No false Run in foreground (don't daemonize)
--resume No false Resume from saved execution state
--project-dir DIR No cwd Project directory for execution
--serve No false Also start HTTP API server in the same process
--port PORT No 8741 Port for API server (with --serve)
--host HOST No 127.0.0.1 Bind address for API server (with --serve)
--token TOKEN No -- Bearer token for API auth (with --serve)
--task-id ID No -- Namespace this daemon under a specific task ID

Example:

# Start background daemon with API server
baton daemon start --plan .claude/team-context/plan.json \
    --serve --port 8741 --max-parallel 4

# Dry-run in foreground for testing
baton daemon start --plan plan.json --dry-run --foreground

# Resume a crashed daemon
baton daemon start --resume --task-id task-abc123

baton daemon status

baton daemon status [--task-id ID]

Shows whether the daemon is running, its PID, task ID, phase, step progress, gates, and elapsed time.


baton daemon stop

baton daemon stop [--task-id ID]

Sends a stop signal to the running daemon process.


baton daemon list

baton daemon list [--project-dir DIR]

Lists all daemon workers with their task IDs, PIDs, and liveness status.


baton async

Dispatch and track asynchronous tasks.

baton async [options]
Argument Required Description
--dispatch COMMAND No Dispatch a new async task
--show ID No Show a specific task's status
--pending No List only pending tasks
--task-id ID No Task ID for --dispatch (auto-generated if omitted)
--type TYPE No Dispatch type: shell, script, or manual (default: shell)

Without flags, lists all async tasks with their status.

Examples:

# Dispatch a shell command
baton async --dispatch "pytest tests/ -x" --task-id my-test-run

# Check status
baton async --show my-test-run

# List pending tasks
baton async --pending

baton decide

Manage human decision requests generated during daemon/async execution.

baton decide [options]
Argument Required Description
--list No List pending decision requests (default action)
--all No List all decision requests regardless of status
--show ID No Show full details of a single decision request
--resolve ID No Resolve a pending decision request
--option OPTION No Chosen option when using --resolve (required)
--rationale TEXT No Optional rationale for the decision

Examples:

# List pending decisions
baton decide

# Show details of a decision request
baton decide --show req-abc123

# Resolve a decision
baton decide --resolve req-abc123 --option "approve" --rationale "Looks good after review"

Manager Mode Commands

Commands for the manager-mode PMO layer: config profile, status reporting, and the knowledge-pack lifecycle. See baton plan --manager-mode to opt a plan into this layer, and docs/internal/manager-mode-pmo-design.md for the full artifact schema and locked design decisions.

baton config

Inspect, validate, or scaffold the project's baton.yaml config. Every subcommand accepts --profile {project,manager} (default project); both profiles read/write the same baton.yaml file and each ignores the other's top-level keys.

baton config show [--start-dir DIR] [--profile {project,manager}]
baton config validate [PATH] [--profile {project,manager}]
baton config init [--path PATH] [--force] [--profile {project,manager}]
Subcommand Description
show Print the discovered baton.yaml path and the effective merged config (JSON for --profile project, YAML for --profile manager).
validate Parse and validate a baton.yaml file; exits non-zero on failure. --profile manager errors name the offending key/value/valid-options.
init Write a starter baton.yaml to the target path. --profile project writes ./baton.yaml (the default_agents/default_gates/... template); --profile manager writes ./.claude/baton.yaml (the full manager_mode/team/scoping/context/knowledge_packs/policies/gates/reporting template from the PRD).
Argument Applies to Description
--start-dir DIR show Directory to start the upward config search from (default: cwd)
PATH validate Optional explicit file path (defaults to discovery from cwd)
--path PATH init Output path (default per profile, see above)
--force init Overwrite an existing file at the target path
--profile {project,manager} all Which config surface to operate on (default project)

Exit codes: 0 success (including calling baton config with no subcommand, which prints a usage hint); 1 file missing/unreadable, or --profile project parse error; 2 --profile manager parse error (ManagerConfigError).

Examples:

# Scaffold the manager-mode config template
baton config init --profile manager

# Validate it after editing
baton config validate --profile manager

# Show the effective merged manager config (defaults < user < project)
baton config show --profile manager

baton report

Manager-mode status report for a task: brief (post-planning) or progress report (during/after execution). Degrades gracefully when execution hasn't started -- a plan saved with --manager-mode --save alone still produces a report from the scope-map/team-blueprint/ knowledge-plan sidecars and plan.json.

baton report [--task-id TASK_ID] [--json]
Argument Required Default Description
--task-id TASK_ID No active task Target a specific execution by task ID (resolution ladder: --task-id -> BATON_TASK_ID -> active-task marker)
--json No false Emit machine-readable JSON instead of Markdown

Output: prints the rendered report and (best-effort) writes/refreshes manager-report.md under .claude/team-context/executions/<task_id>/.

Example:

baton plan "Roll out multi-tenant billing" --manager-mode --save
baton report

baton team

Ad-hoc team status and role cards for a manager-mode task. Requires a team blueprint (team-blueprint.json) written by baton plan --manager-mode --save.

baton team status [--task-id TASK_ID]
baton team show [--task-id TASK_ID]
Subcommand Description
status Team purpose, roles (with owned-workstream counts), workstream ownership, completed handoffs, open knowledge gaps, open scope changes, and manager decisions needed.
show Everything status shows, plus each role's full role-card content.
Argument Description
--task-id TASK_ID Target a specific execution by task ID (defaults to the active task)

Workstream ownership is always read from TeamBlueprint.workstream_assignments -- a role that owns zero workstreams is listed under Roles only, never as a workstream's owner.

Example:

baton team status
baton team show --task-id 2026-07-02-billing-rollout-ab12cd34

baton knowledge list / show / scan / audit / propose

Knowledge-pack lifecycle verbs on the shared baton knowledge cooperative parser (see baton knowledge --help for the full subcommand list, including the pre-existing brief/effectiveness/ harvest/stale/deprecate/retire/sweep/usage/ranking/ab verbs not covered here). These five read/write the existing knowledge.yaml manifest -- there is no separate pack.yaml.

baton knowledge list [--root ROOT]
baton knowledge show PACK_NAME [--root ROOT]
baton knowledge scan [--root ROOT]
baton knowledge audit [--root ROOT]
baton knowledge propose [--root ROOT]
Subcommand Description
list List discovered knowledge packs with status, confidence, doc count, and token estimate.
show PACK_NAME Show one pack's status, confidence, description, source path/files, target agents, last-reviewed date, stale-after window, and documents.
scan Discover knowledge packs and candidate docs; writes knowledge-scan.json under .claude/team-context/.
audit Audit packs for invalid status, staleness, and missing metadata against the loaded ManagerConfig. Prints Knowledge audit: no issues found. and exits 0 when clean; otherwise lists each issue and exits 1.
propose Propose new knowledge packs from repeated knowledge-gap signals recorded under .claude/team-context/; writes each proposal to .claude/team-context/knowledge-proposals/<slug>.md when any are found.
Argument Description
--root ROOT Project root to scan/discover packs from (default: cwd)
PACK_NAME (positional, show only) Pack name to display

Exit codes: 0 success (including "no issues"/"nothing to propose"); 1 audit found issues, or show was given an unknown pack name.

Example:

baton knowledge scan
baton knowledge audit || echo "fix the packs above before shipping"

Observe Commands

baton dashboard

Generate or display the usage dashboard.

baton dashboard [--write]
Argument Required Description
--write No Write dashboard to disk instead of printing to stdout

baton trace

List and inspect structured task execution traces.

baton trace [TASK_ID] [options]
Argument Required Description
TASK_ID No Show timeline for a specific task
--last No Show timeline for the most recent task
--summary TASK_ID No Show compact summary for a specific task
--count N No Number of recent traces to list (default: 10)

Examples:

# List recent traces
baton trace

# Show timeline for most recent task
baton trace --last

# Show timeline for a specific task
baton trace task-abc123

# Show compact summary
baton trace --summary task-abc123

baton usage

Show usage statistics from the usage log.

baton usage [options]
Argument Required Description
--recent N No Show the N most recent records
--agent NAME No Show stats for a specific agent

Without flags, prints an aggregate usage summary including total tasks, agents used, tokens consumed, outcomes, and top agents.

Examples:

# Summary view
baton usage

# Last 5 usage records
baton usage --recent 5

# Stats for a specific agent
baton usage --agent backend-engineer--python

baton telemetry

Show or clear agent telemetry events.

baton telemetry [options]
Argument Required Description
--agent NAME No Show events for a specific agent
--recent N No Show the N most recent events
--clear No Clear the telemetry log

Without flags, prints a telemetry summary grouped by agent and event type, with file read/write counts.


baton context-profile

List and inspect agent context efficiency profiles.

baton context-profile [TASK_ID] [options]
Argument Required Description
TASK_ID No Show context profile for a specific task
--agent NAME No Show aggregate context stats for a specific agent
--generate TASK_ID No Generate and save a context profile from trace data
--report No Print a full markdown context efficiency report
--count N No Number of recent profiles to list (default: 10)

Examples:

# Generate a profile from trace data
baton context-profile --generate task-abc123

# View a generated profile
baton context-profile task-abc123

# Agent-level aggregate stats
baton context-profile --agent backend-engineer--python

# Full report
baton context-profile --report

baton retro

Show retrospectives generated after task completion.

baton retro [options]
Argument Required Description
--task-id ID No Show a specific retrospective
--search KEYWORD No Search retrospectives by keyword
--recommendations No Extract roster recommendations from all retrospectives
--count N No Number of recent retrospectives to list (default: 10)

Examples:

# List recent retrospectives
baton retro

# View a specific retrospective
baton retro --task-id task-abc123

# Search for retrospectives mentioning "auth"
baton retro --search auth

# Extract roster recommendations
baton retro --recommendations

baton context

Situational awareness for Claude agents. Queries baton.db for current task state, agent briefings, and knowledge gaps.

baton context current

baton context current [--db PATH] [--central] [--json]

Shows what task, phase, step, and agent are currently active.

baton context briefing

baton context briefing AGENT [--db PATH] [--central] [--json]
Argument Required Description
AGENT Yes Agent name to brief (e.g. backend-engineer--python)

Prints a performance briefing for an agent about to be dispatched.

baton context gaps

baton context gaps [--min-frequency N] [--agent NAME] [--db PATH] [--central] [--json]
Argument Required Default Description
--min-frequency N No 1 Minimum occurrence count to include a gap
--agent NAME No -- Filter gaps to a specific agent

Shows knowledge gaps identified across recent retrospectives.

Shared flags (all context subcommands):

Flag Description
--db PATH Explicit path to baton.db
--central Query central database at ~/.baton/central.db
--json Machine-readable JSON output

baton cleanup

Remove old execution artifacts (traces, events, retrospectives).

baton cleanup [options]
Argument Required Default Description
--retention-days N No 90 Keep files newer than this many days
--dry-run No false Show what would be removed without deleting
--team-context PATH No .claude/team-context Path to team-context directory

Example:

# Preview what would be cleaned up
baton cleanup --dry-run --retention-days 30

# Actually clean up files older than 60 days
baton cleanup --retention-days 60

baton migrate-storage (deprecated)

Deprecated. Use baton sync --migrate-storage instead. The shim still works and prints a DEPRECATED: warning to stderr.


Guardrails Commands

baton classify

Classify task sensitivity and select a guardrail preset.

baton classify DESCRIPTION [--files FILE...]
Argument Required Description
DESCRIPTION Yes Task description to classify
--files FILE... No File paths affected (elevates risk from path patterns)

Output:

Risk Level: MEDIUM
Preset: regulated-data
Confidence: 0.82
Signals: payment, user-data
Explanation: Task touches payment processing and user PII fields.

Risk levels: LOW, MEDIUM, HIGH, CRITICAL

Example:

baton classify "Update user payment processing logic" \
    --files app/payments.py app/models/user.py

baton classify --activate

Write .claude/active-policy.json after classifying a task, so that the baton policy-check hook uses the correct guardrail preset for the session.

baton classify DESCRIPTION [--files FILE...] --activate
Argument Required Description
DESCRIPTION Yes Task description to classify
--files FILE... No File paths affected (elevates risk from path patterns)
--activate No Write .claude/active-policy.json with the resolved preset key

Written file (.claude/active-policy.json):

{
  "preset": "standard_dev",
  "preset_display_name": "Standard Development",
  "risk_level": "LOW",
  "confidence": "high",
  "signals": [],
  "activated_at": "2026-01-15T12:00:00+00:00",
  "activated_by": "baton classify --activate",
  "task_hint": "first 120 chars of the description"
}

Preset keys: standard_dev, data_analysis, infrastructure, regulated, security.

Example:

baton classify "Add JWT auth middleware" --activate
# → Active policy written to .claude/active-policy.json (preset: security)

Related: baton policy-check, baton comply-record


baton policy-check

Claude Code PreToolUse hook: evaluate a tool call against the active guardrail policy and emit a deny decision when a blocking rule is triggered.

Reads a PreToolUse JSON payload from stdin and prints a deny JSON to stdout when a path_block or tool_restrict rule with severity=="block" matches. Exits 0 in all cases (fail-open); set BATON_POLICY_FAIL_CLOSED=1 to exit 2 on errors.

baton policy-check [--agent NAME] [--cwd DIR]
Argument Required Description
--agent NAME No Agent name (overrides $CLAUDE_AGENT_NAME)
--cwd DIR No Project root for policy resolution (default: cwd)

Stdin format (Claude Code PreToolUse payload):

{"tool_name": "Write", "tool_input": {"file_path": "/project/.env"}, "session_id": "..."}

Deny output (stdout, exit 0):

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "standard_dev rule block_env_files (path_block): Block writes to .env files. Matched: /project/.env against pattern '**/.env'."
  }
}

Policy resolution order:

  1. .claude/active-policy.jsonpreset key
  2. .claude/team-context/plan.jsonrisk_level (LOW/MEDIUM → standard_dev; HIGH/CRITICAL → regulated)
  3. Fallback: standard_dev

Environment variables:

Variable Effect
BATON_POLICY_FAIL_CLOSED 1 → exit 2 on errors (stdin errors, unreadable policy)
CLAUDE_AGENT_NAME Agent name used for scope-based rule matching

Example (hook configuration in settings.json):

{"matcher": "Bash|Write|Edit|MultiEdit",
 "hooks": [{"type": "command", "command": "baton policy-check", "timeout": 10}]}

Related: baton classify --activate, baton comply-record


baton packs

Manage Assurance Packs — org-authored domain governance units stored under .claude/packs/<name>/.

baton packs init

Scaffold a new pack directory with all required files from a minimal valid template.

baton packs init NAME [--dir DIR]
Argument Required Default Description
NAME Yes -- Pack name (becomes the directory name under .claude/packs/)
--dir DIR No cwd Project root containing .claude/

Behaviour:

  • Creates .claude/packs/<NAME>/ with pack.json, policy.json, signals.json, rubric.md, gates.json, evidence.json, and knowledge/overview.md.
  • Substitutes all [YOUR_PACK_NAME] placeholders with NAME.
  • Refuses if the directory already exists (exit 1).
  • Prints a next-steps hint on success.

Example:

baton packs init phi-hipaa
# → Scaffolded pack 'phi-hipaa' at .claude/packs/phi-hipaa/
# Next steps: ...

baton packs validate

Validate one or all packs against all 7 spec checks. Exits 2 if any error is found.

baton packs validate [NAME] [--dir DIR]
Argument Required Default Description
NAME No all packs Pack name to validate
--dir DIR No cwd Project root containing .claude/

Exit codes:

Code Meaning
0 All packs valid
2 One or more validation errors found

Validation checks:

  1. Required files exist (pack.json, policy.json, signals.json, rubric.md).
  2. pack.json has name, version, description; name matches directory.
  3. policy.json parses as PolicySet with name == "pack:<dirname>".
  4. signals.json categories ⊆ {regulated, pii, security, infrastructure, database}; path_patterns is a list; preset_name present.
  5. rubric.md has ≥1 ## heading and ≥1 - [ ] checkbox.
  6. gates.json entries each have id, description, command.
  7. evidence.json required_artifacts each have id, description.

Output:

[OK] phi-hipaa
[OK] secure-coding-owasp
All packs valid.

# On error:
[ERROR] my-pack/policy.json: PolicySet name 'pack:wrong' must be 'pack:my-pack'

baton packs list

List all packs with key metadata. Invalid packs are shown with [INVALID] prefix.

baton packs list [--dir DIR]
Argument Required Default Description
--dir DIR No cwd Project root containing .claude/

Output:

NAME                      VERSION    DOMAIN               RISK       DESCRIPTION
------------------------------------------------------------------------------------------
phi-hipaa                 1.0.0      healthcare           HIGH       HIPAA PHI handling guardrails...
secure-coding-owasp       1.0.0      security             HIGH       OWASP Top-10 secure coding guardrails...

Related: baton classify --activate, baton policy-check


baton comply-record

Claude Code PostToolUse and Stop hook: append a hash-chained entry to the compliance audit log.

Reads a PostToolUse or Stop JSON payload from stdin and appends an entry via ComplianceChainWriter to .claude/team-context/compliance-audit.jsonl. Always exits 0 (fail-open); BATON_COMPLIANCE_FAIL_CLOSED=1 exits 1 on write errors. Malformed stdin is silently ignored.

baton comply-record [--event-type TYPE] [--log PATH] [--cwd DIR]
Argument Required Default Description
--event-type TYPE No hook_tool_use Event type label in the audit entry
--log PATH No .claude/team-context/compliance-audit.jsonl Audit log path
--cwd DIR No cwd Project root for log path resolution

Event types: hook_tool_use (PostToolUse), session_stop (Stop hooks).

Log entry fields: event_type, tool_name, file_paths, session_id, agent_name, timestamp, prev_hash, entry_hash.

Environment variables:

Variable Effect
BATON_COMPLIANCE_FAIL_CLOSED 1 → exit 1 on write errors
CLAUDE_AGENT_NAME Agent name recorded in the log entry

Example (Stop hook configuration):

{"hooks": [{"type": "command",
            "command": "baton comply-record --event-type session_stop",
            "timeout": 5}]}

Related: baton compliance verify, baton compliance rechain, baton policy-check


baton compliance

Show compliance reports generated during task execution.

baton compliance [options]
Argument Required Default Description
--task-id ID No -- Show a specific compliance report
--count N No 5 Number of recent reports to list

baton policy

List, show, or evaluate guardrail policy presets.

baton policy [options]
Argument Required Description
--show NAME No Show rules of a named policy preset
--check AGENT No Agent name to evaluate (use with --preset)
--preset NAME No Policy preset name to evaluate against (use with --check)
--paths PATHS No Comma-separated allowed file paths (use with --check)
--tools TOOLS No Comma-separated tools available (use with --check)

Without flags, lists all available policy presets.

Examples:

# List all presets
baton policy

# Show a specific preset's rules
baton policy --show regulated-data

# Check an agent against a preset
baton policy --check backend-engineer--python \
    --preset regulated-data \
    --paths "app/,tests/" \
    --tools "Bash,Read,Edit"

baton escalations

Show, resolve, or clear agent escalations.

baton escalations [options]
Argument Required Description
--all No Show all escalations, including resolved
--resolve AGENT ANSWER No Resolve the oldest pending escalation for AGENT with ANSWER
--clear No Remove all resolved escalations

Without flags, shows only pending escalations.

Example:

# Resolve an escalation
baton escalations --resolve backend-engineer--python "Use the v2 API endpoint instead"

baton validate

Validate agent definition .md files for correct structure and YAML frontmatter.

baton validate PATHS... [--strict]
Argument Required Description
PATHS... Yes File or directory paths to validate
--strict No Treat warnings as errors (exit code 1 if any warnings)

Example:

# Validate all agents in a directory
baton validate agents/

# Validate a specific file in strict mode
baton validate agents/backend-engineer.md --strict

Exit code: 1 if any errors found (or warnings in strict mode).


baton spec-check

Validate agent output against a spec (JSON schema, file structure, or module exports).

baton spec-check [options]
Argument Required Description
--json DATA_FILE No JSON data file to validate
--files ROOT No Directory root to check for expected files
--exports MODULE No Python module file to check for expected exports
--schema SCHEMA_FILE No JSON Schema file (use with --json)
--expect NAMES No Comma-separated expected files or names (use with --files/--exports)

One of three modes must be specified:

# Validate JSON against a schema
baton spec-check --json output.json --schema schema.json

# Check file structure
baton spec-check --files src/ --expect "models.py,routes.py,tests/"

# Check module exports
baton spec-check --exports app/models.py --expect "User,Session,Token"

Exit code: 1 if validation fails.


baton detect

Detect the project stack (language and framework) from config files.

baton detect [--path PATH]
Argument Required Default Description
--path PATH No cwd Project root path

Output:

Language:  python
Framework: fastapi
Signals:   pyproject.toml, requirements.txt

baton evidence

Build and verify per-task evidence bundles (007 Phase H). A bundle is a self-contained directory (or .tar.gz) of verifiable artifacts that prove what ran, what was approved, and that nothing was tampered with after the fact.

baton evidence bundle

baton evidence bundle <task_id>
                      [--output DIR]
                      [--sign]
                      [--tar]
                      [--db PATH]
                      [--compliance-log PATH]
                      [--packs-dir PATH]
                      [--soul-db PATH]
Argument Required Default Description
<task_id> Yes -- Task ID to bundle evidence for
--output DIR No .claude/team-context/ Root directory; bundle lands at <DIR>/evidence/<task-id>/
--sign No false Sign the manifest with a soul key (requires BATON_SOULS_ENABLED=1)
--tar No false Package bundle as .tar.gz and remove the directory
--db PATH No .claude/team-context/baton.db Override baton.db location
--compliance-log PATH No auto Override compliance-audit.jsonl path
--packs-dir PATH No .claude/packs/ Override assurance packs directory
--soul-db PATH No ~/.baton/central.db Override central.db for soul signing

Output: Evidence bundle written to: <path>

Bundle contents:

File What it proves
manifest.json Inventory of all files with SHA-256 hashes; optional soul signature
aibom.json AI Bill of Materials — models, agents, gates, knowledge
aibom.md Human-readable AIBOM
compliance-segment.jsonl Task-scoped compliance-audit entries (omitted if no log exists)
gates.json Full gate_results dump for this task
verdicts.json Auditor/reviewer step verdicts with extracted AuditorVerdict
approvals.json approval_results + pending approval request if present
packs.json Assurance packs + active-policy snapshot (omitted if none found)

Example:

baton evidence bundle task-abc123 --output /tmp/bundles --tar
# → /tmp/bundles/evidence/task-abc123.tar.gz

baton evidence bundle task-abc123 --sign
# → .claude/team-context/evidence/task-abc123/ (signed manifest)

baton evidence verify

baton evidence verify <path> [--strict]
Argument Required Default Description
<path> Yes -- Path to bundle directory or .tar.gz
--strict No false Exit on the first failure (default: report all)

Exit codes:

Code Meaning
0 All checks passed (warnings are OK)
1 One or more integrity failures
2 Bundle is unusable (manifest missing or unparseable)

Checks performed:

  • manifest.json present and valid JSON
  • Per-file SHA-256 matches manifest
  • compliance-segment.jsonl internal chain consistency
  • AIBOM chain_anchor vs segment tail (WARNING on mismatch, not failure)
  • Soul signature verification when soul_signature is present

Example:

# CI-runnable, no network or database needed
baton evidence verify .claude/team-context/evidence/task-abc123/
# → Bundle OK — all checks passed.

baton evidence verify /tmp/bundles/task-abc123.tar.gz
# → Bundle OK — all checks passed.

Related: baton govern aibom, baton compliance


Improve Commands

baton scores

Show agent performance scorecards.

baton scores [options]
Argument Required Description
--agent NAME No Show scorecard for a specific agent
--write No Write scorecard report to disk
--trends No Show performance trends for all agents

Without flags, prints the full scorecard report to stdout.

Example:

# View trends for all agents
baton scores --trends

# Specific agent scorecard
baton scores --agent backend-engineer--python

baton evolve (deprecated)

Deprecated. Prompt-evolution proposals are now produced by the unified learning loop. Use baton learn run-cycle instead. The shim still works and prints a DEPRECATED: warning to stderr.


baton patterns

Display and refresh learned orchestration patterns.

baton patterns [options]
Argument Required Default Description
--refresh No false Re-analyse the usage log and update learned-patterns.json
--task-type TYPE No -- Show patterns for a specific task type
--min-confidence N No 0.0 Filter patterns by minimum confidence (0.0-1.0)
--recommendations No false Show sequencing recommendations for each task type

Examples:

# Refresh patterns from usage log
baton patterns --refresh

# View high-confidence patterns only
baton patterns --min-confidence 0.8

# Sequencing recommendations
baton patterns --recommendations

baton budget

Show or refresh budget tier recommendations based on usage history.

baton budget [options]
Argument Required Description
--recommend No Re-analyse the usage log and display fresh recommendations
--save No Save recommendations to budget-recommendations.json
--auto-apply No Show only auto-applicable (downgrade) recommendations above 80% confidence

Without flags, shows previously saved recommendations.

Example:

# Generate and save budget recommendations
baton budget --recommend --save

# View auto-applicable downgrades
baton budget --auto-apply

baton changelog

Show agent changelog entries or list backup files.

baton changelog [options]
Argument Required Description
--agent NAME No Show history for a specific agent
--backups [NAME] No List backup files. With a name: filter to that agent. Without: all backups.

Examples:

# Show full changelog
baton changelog

# Show changelog for one agent
baton changelog --agent backend-engineer--python

# List all backup files
baton changelog --backups

# List backups for a specific agent
baton changelog --backups backend-engineer--python

baton anomalies

Detect and display system anomalies.

baton anomalies [--watch]
Argument Required Description
--watch No Show anomaly detection status and trigger readiness

Without flags, detects and displays current anomalies with severity, agent, metric, current value, threshold, and evidence.


baton experiment (deprecated)

Deprecated. Experiment tracking is folded into the unified learning loop. Use baton learn run-cycle (which handles auto-apply, escalate, and experiment rollback automatically) instead. The shim still works and prints a DEPRECATED: warning to stderr.


baton improve (deprecated)

Deprecated. Use baton learn improve instead. The shim still works and prints a DEPRECATED: warning to stderr.


baton learn

Learning automation — track, analyze, propose, and apply fixes for recurring issues. This is a command group with subcommands.

baton learn [SUBCOMMAND] [options]
Subcommand Description
status Dashboard: open issues by type/severity, auto-apply stats
issues List learning issues (filterable by --type, --severity, --status)
analyze Run analysis: compute confidence, mark auto-apply candidates
apply Apply a specific fix (--issue ID) or all proposed (--all-safe)
interview Interactive structured dialogue for human-directed decisions
history Show resolution history (--limit N, default 20)
reset Reopen an issue and rollback its applied override (--issue ID)
run-cycle Instantiate the learning-cycle plan template (and optionally execute it)
improve Run the improvement loop or view reports (formerly baton improve)

baton learn run-cycle

Instantiate the learning-cycle plan template. The cycle collects execution data, analyzes patterns, proposes improvements, requires human approval, applies changes, and documents outcomes.

baton learn run-cycle [--run] [--dry-run] [--template PATH]
Flag Default Description
--run false Execute the cycle immediately via baton execute run after creating the plan
--dry-run false Print the baton execute run command that would be invoked, without executing
--template PATH bundled Path to a custom learning-cycle plan template JSON file

baton learn improve

Run a full improvement cycle (formerly baton improve). Detects anomalies, generates recommendations, auto-applies safe changes, escalates risky ones, and starts experiments.

baton learn improve [--run | --force | --report | --experiments | --history] [--min-tasks N] [--interval N]
Flag Description
--run Run a full improvement cycle
--force Force-run a cycle bypassing the data-threshold check
--report Show the latest improvement report
--experiments Show active experiments
--history Show all improvement reports
--min-tasks N Minimum total tasks before analysis fires (overrides BATON_MIN_TASKS)
--interval N Re-analyze every N new tasks (overrides BATON_ANALYSIS_INTERVAL)

Examples:

# Dashboard
baton learn status

# List high-severity issues
baton learn issues --severity high

# Analyze and auto-apply safe fixes
baton learn analyze
baton learn apply --all-safe

# Run a full improvement cycle
baton learn improve --run

# Instantiate and execute the learning cycle
baton learn run-cycle --run

Knowledge Commands

baton knowledge

Knowledge utilities: validate packs, search metadata, simulate resolver attachments, generate codebase briefings, harvest knowledge from existing artefacts, manage item lifecycle, and report effectiveness. This is a command group with subcommands.

baton knowledge SUBCOMMAND [options]
Subcommand Description
doctor Validate knowledge packs and print actionable warnings
search Search knowledge metadata with the registry TF-IDF index
resolve Simulate knowledge attachments for an agent and task
brief Generate a concise codebase briefing for new agents
harvest Harvest knowledge entries from existing artefacts (ADRs, PR reviews)
stale List active knowledge items that look stale
deprecate Flag a knowledge item as deprecated
retire Retire a knowledge item immediately (skips grace window)
sweep Auto-retire deprecated items whose grace period has elapsed
usage Show usage count and last-used time for a single item
effectiveness Show per-doc effectiveness + ROI scores
ranking Show all known docs ranked by historical effectiveness
ab Manage knowledge A/B experiments

baton knowledge doctor

Validate knowledge packs and print actionable warnings (missing or invalid knowledge.yaml, declared documents that don't exist, empty descriptions, duplicate document names, documents too large for inline delivery, or a pack/root directory that can't be listed or read). Runtime loading tolerates these issues; doctor reports them as actionable edits without changing loading semantics.

A declared document with a known non-Markdown extension (.json, .yaml, .yml, .txt, .py, .toml, .csv) must exist under that exact name — it is not satisfied by a same-named .md shadow file (e.g. a manifest declaring config.json is not satisfied by config.json.md). Only genuinely extensionless declared names fall back to a .md suffix.

A pack directory (or the root itself) that raises an OS-level error when listed or read is reported as an unreadable-pack issue and skipped, so one bad directory (permissions, a cloud-sync placeholder, etc.) doesn't abort the rest of the run. Repeated --knowledge-root arguments that resolve to the same (non-existent) directory now report a single missing-root issue instead of one per repetition.

baton knowledge doctor [--knowledge-root DIR ...] [--format text|json] [--json] [--strict]
Flag Default Description
--knowledge-root DIR global + project Knowledge root to validate; repeatable and de-duplicated after resolving to an absolute path (default: ~/.claude/knowledge and ./.claude/knowledge)
--format FORMAT text Output format: text or json
--json -- Alias for --format json
--strict false Exit non-zero when any warning is found

baton knowledge search

Search knowledge metadata with the registry TF-IDF index.

baton knowledge search QUERY... [options]
Argument Required Default Description
QUERY Yes -- Search query text (one or more words)
--knowledge-root DIR No global + project Knowledge root to search; repeatable
--limit N No 10 Maximum results to return
--format FORMAT No table Output format: table or json
--json No -- Alias for --format json

baton knowledge resolve

Simulate the knowledge attachments the resolver would produce for an agent and task, without dispatching anything.

baton knowledge resolve --agent NAME --task TEXT [options]
Flag Required Default Description
--agent NAME Yes -- Agent name
--task TEXT Yes -- Task description
--knowledge-root DIR No global + project Knowledge root to load; repeatable
--task-type TYPE No -- Optional task type used by resolver keyword extraction
--risk LEVEL No LOW Risk level passed through to resolver simulation
--knowledge-pack PACK No -- Explicit pack to include; repeatable
--knowledge PATH No -- Explicit document path to include; repeatable
--format FORMAT No table Output format: table or json
--json No -- Alias for --format json

baton knowledge brief

Generate a concise codebase briefing (stack, layout, entry points, conventions, tests, health snapshot) that dispatched agents can read instead of re-discovering the basics every run.

baton knowledge brief [--project DIR] [--save] [--format markdown|json]
Flag Default Description
--project DIR cwd Project directory to brief
--save false Write to .claude/team-context/codebase-brief.md (or codebase-brief.json with --format json) instead of stdout
--format FORMAT markdown Output format: markdown or json

baton knowledge harvest

Convert existing artefacts into knowledge entries. Both harvesters are idempotent: re-running on unchanged input is a no-op.

baton knowledge harvest adrs [--source-dir DIR] [--target-pack PACK] [--knowledge-root DIR]
baton knowledge harvest reviews --pr N [--repo OWNER/NAME] [--knowledge-root DIR]

adrs walks a docs tree for Architecture Decision Records and converts each into a knowledge document:

Flag Default Description
--source-dir DIR docs/ Root to walk for ADR markdown files
--target-pack PACK decisions Knowledge pack name to write into
--knowledge-root DIR .claude/knowledge Override the knowledge root

reviews pulls PR review comments via the gh CLI and distils salient ones into a lessons document:

Flag Required Default Description
--pr N Yes -- Pull-request number to harvest
--repo OWNER/NAME No auto-detect via gh Repository slug
--knowledge-root DIR No .claude/knowledge Override the knowledge root

baton knowledge stale

List active knowledge items that look stale. Lifecycle subcommands (stale, deprecate, retire, sweep, usage) operate on the project database at .claude/team-context/baton.db.

baton knowledge stale [--days N] [--max-usage N]
Flag Default Description
--days N 90 Days since last use threshold
--max-usage N 5 Items with a usage count below this are eligible

baton knowledge deprecate

Flag a knowledge item as deprecated; schedules retirement after the grace period elapses.

baton knowledge deprecate KNOWLEDGE_ID [--grace N] [--reason TEXT]
Argument Required Default Description
KNOWLEDGE_ID Yes -- Item ID in the form <pack_name>/<doc_name>
--grace N No 30 Grace period in days before auto-retirement
--reason TEXT No -- Optional human-readable reason recorded with the deprecation

baton knowledge retire

Retire a knowledge item immediately, skipping the grace window.

baton knowledge retire KNOWLEDGE_ID

baton knowledge sweep

Auto-retire deprecated items whose grace period has elapsed. Safe to schedule (e.g. in a daily cron) — it only retires items the operator has already deprecated.

baton knowledge sweep

baton knowledge usage

Show lifecycle state, usage count, last-used time, and staleness for a single item.

baton knowledge usage KNOWLEDGE_ID

baton knowledge effectiveness

Show per-doc effectiveness + ROI scores as a sorted Markdown table or JSON document.

baton knowledge effectiveness [--pack PACK] [--since-days N] [--format markdown|json] [--stale] [--threshold-days N]
Flag Default Description
--pack PACK all packs Restrict the report to a single knowledge pack
--since-days N 30 Rolling window in days for the effectiveness rollup (0 = all time)
--format FORMAT markdown Output format: markdown or json
--stale false Show only stale candidates
--threshold-days N 90 Stale-by-age threshold in days (used with --stale)

baton knowledge ranking

Show all known docs ranked by historical effectiveness. Reads v_knowledge_effectiveness from the central database.

baton knowledge ranking [--output table|json] [--db PATH]
Flag Default Description
--output FORMAT table Output format: table or json
--db PATH ~/.baton/central.db Path to the SQLite database

baton knowledge ab

Manage knowledge A/B experiments.

baton knowledge ab list
baton knowledge ab create --kid KNOWLEDGE_ID --a PATH_A --b PATH_B [--ratio RATIO]
baton knowledge ab results EXPERIMENT_ID
baton knowledge ab stop EXPERIMENT_ID

create flags:

Flag Required Default Description
--kid KNOWLEDGE_ID Yes -- Canonical pack/doc id (e.g. security/owasp.md)
--a PATH_A Yes -- Relative path to the variant A document
--b PATH_B Yes -- Relative path to the variant B document
--ratio RATIO No 0.5 Fraction routed to variant A (between 0.0 and 1.0)

Examples:

# Validate knowledge packs, failing CI on warnings
baton knowledge doctor --strict

# Search the knowledge index
baton knowledge search payment idempotency --limit 5

# Preview what the resolver would attach for a dispatch
baton knowledge resolve --agent backend-engineer--python \
    --task "Add JWT authentication middleware" --risk MEDIUM

# Generate and save a codebase brief
baton knowledge brief --save

# Harvest ADRs into the decisions pack
baton knowledge harvest adrs --source-dir docs

# Lifecycle: deprecate with a 14-day grace period, then sweep later
baton knowledge deprecate security/owasp --grace 14 --reason "superseded"
baton knowledge sweep

Related: baton plan --knowledge / --knowledge-pack, baton learn


Distribute Commands

baton package

Create, inspect, or install agent-baton package archives.

baton package [options]
Argument Required Description
--name NAME No Create a package archive with this name
--info ARCHIVE No Show manifest of an existing .tar.gz package
--install ARCHIVE No Install an agent-baton package
--version VER No Package version (default: 1.0.0)
--description TEXT No Package description
--include-knowledge No Include knowledge packs in the package
--no-agents No Exclude agents from the package
--no-references No Exclude references from the package
--output-dir DIR No Directory to write the archive to (default: cwd)
--scope SCOPE No Install scope: user or project (default: project)
--force No Overwrite existing files when installing
--project ROOT No Source project root (default: cwd)

Examples:

# Create a package
baton package --name my-agents --version 2.0.0 \
    --description "Custom agent definitions" --include-knowledge

# Inspect a package
baton package --info my-agents-2.0.0.tar.gz

# Install a package to user scope
baton package --install my-agents-2.0.0.tar.gz --scope user --force

baton publish

Publish a package archive to a local registry directory, or initialize a new registry.

baton publish ARCHIVE --registry PATH
baton publish --init PATH
Argument Required Description
ARCHIVE Yes* Path to the .tar.gz archive (*unless using --init)
--registry PATH Yes* Path to the local registry directory (*required when publishing)
--init PATH No Initialize a new empty registry at PATH

Examples:

# Initialize a registry
baton publish --init /shared/baton-registry

# Publish a package
baton publish my-agents-2.0.0.tar.gz --registry /shared/baton-registry

baton pull

Install a package from a local registry directory.

baton pull [NAME] --registry PATH [options]
Argument Required Description
NAME No Name of the package to install
--registry PATH Yes Path to the local registry directory
--version VERSION No Specific version to install (default: latest)
--scope SCOPE No Install scope: project or user (default: project)
--force No Overwrite existing files
--list No List all available packages in the registry
--search QUERY No Search packages by name substring

Examples:

# List available packages
baton pull --list --registry /shared/baton-registry

# Search for packages
baton pull --search "auth" --registry /shared/baton-registry

# Install a specific version
baton pull my-agents --registry /shared/baton-registry --version 2.0.0 --scope user

baton verify-package (deprecated)

Deprecated. Use baton sync --verify ARCHIVE instead. The shim still works and prints a DEPRECATED: warning to stderr.


baton install

Install agents and references from the agent-baton repo to user or project scope.

baton install --scope SCOPE [options]
Argument Required Default Description
--scope SCOPE Yes -- user (~/.claude/) or project (.claude/)
--source PATH No . Path to the agent-baton repo root
--force No false Overwrite ALL existing files
--upgrade No false Overwrite agents + references but preserve settings, CLAUDE.md, knowledge, team-context
--verify No false Run post-install verification checks

Upgrade mode merges hooks into settings.json (preserving user keys) while overwriting agents and references. CLAUDE.md and knowledge packs are preserved.

Examples:

# Fresh install to user scope
baton install --scope user --source /path/to/agent-baton

# Upgrade agents + references, preserve settings
baton install --scope project --upgrade --verify

# Force overwrite everything
baton install --scope user --force --verify

baton transfer

Transfer agents, knowledge, and references between projects.

baton transfer [options]
Argument Required Description
--discover No Show what is available to transfer from this project
--export TARGET No Export items to a target project root
--import SOURCE No Import items from another project root
--project ROOT No Source project root (default: cwd)
--agents NAMES No Comma-separated agent names or filenames
--knowledge PACKS No Comma-separated knowledge pack directory names
--references NAMES No Comma-separated reference filenames
--all No Transfer all discoverable items
--min-score RATE No Minimum first-pass rate for --discover (0.0-1.0)
--force No Overwrite existing files at the destination

Examples:

# Discover transferable items
baton transfer --discover

# Export specific agents to another project
baton transfer --export /path/to/other-project \
    --agents "backend-engineer,test-engineer" \
    --knowledge "api-patterns"

# Import everything from another project
baton transfer --import /path/to/source-project --all --force

Agent Commands

baton agents

List all available agents grouped by category.

baton agents

Output:

engineering:
  backend-engineer                    [sonnet]
  backend-engineer--python            [sonnet]   (flavor: python)
  frontend-engineer                   [sonnet]

governance:
  auditor                             [opus]
  code-reviewer                       [sonnet]

19 agents loaded.

baton route

Route base agent role names to their stack-specific flavored variants.

baton route [ROLES...] [--path PATH]
Argument Required Default Description
ROLES No backend-engineer frontend-engineer Base role names to route
--path PATH No cwd Project root for stack detection

Output:

Stack: python/fastapi

  backend-engineer               -> backend-engineer--python *
  frontend-engineer              -> frontend-engineer

Entries marked with * were remapped to a flavored variant.


baton events

Query the event log for a task.

baton events [options]
Argument Required Description
--task TASK_ID No Task ID to query events for
--topic PATTERN No Filter events by topic pattern (glob, e.g. step.*)
--last N No Show only the last N events
--json No Output events as JSON
--summary No Show a projected summary view instead of raw events
--list-tasks No List all task IDs that have event logs

Without flags, lists all tasks with event logs.

Examples:

# List tasks with events
baton events --list-tasks

# View events for a task
baton events --task task-abc123

# Filter by topic
baton events --task task-abc123 --topic "step.*" --last 10

# Summary view
baton events --task task-abc123 --summary

# JSON output
baton events --task task-abc123 --json

baton incident

Manage incident response workflows.

baton incident [options]
Argument Required Description
--templates No Show all built-in incident templates
--show ID No Show a specific incident document
--create ID No Create an incident document with the given ID
--severity LEVEL No Severity level for --create: P1, P2, P3, P4
--desc TEXT No Description for --create

Without flags, lists all incidents.

Example:

# Show available templates
baton incident --templates

# Create an incident
baton incident --create INC-2024-001 --severity P2 --desc "API latency spike"

# View an incident
baton incident --show INC-2024-001

PMO Commands

baton pmo serve

Start the PMO HTTP server (requires pip install agent-baton[api]).

baton pmo serve [--port PORT] [--host HOST]
Argument Required Default Description
--port PORT No 8741 Port to listen on
--host HOST No 127.0.0.1 Host to bind to

baton pmo status

Print a terminal Kanban board summary of all registered projects.

baton pmo status

Shows per-project progress bars and a cards table with execution status.


baton pmo add

Register a project with the PMO.

baton pmo add --id ID --name NAME --path PATH --program PROGRAM [--color COLOR]
Argument Required Description
--id ID Yes Project slug identifier (e.g. nds)
--name NAME Yes Human-readable project name
--path PATH Yes Absolute filesystem path to the project root
--program PROGRAM Yes Program this project belongs to (e.g. NDS, ATL)
--color COLOR No Optional display color

Example:

baton pmo add --id nds --name "NDS Platform" \
    --path /home/user/projects/nds --program NDS --color blue

baton pmo health

Print program health bar summary showing completion percentage and task status across all programs.

baton pmo health

Output:

Program Health

  NDS       ████████████████████    85%     (3 active, 12 complete)
  ATL       ██████████░░░░░░░░░░    50%     (2 active, 1 blocked, 5 complete)

Sync Commands

baton sync

Sync project data from project-local baton.db to ~/.baton/central.db. Also hosts two utilities folded in from removed top-level commands: --migrate-storage (formerly baton migrate-storage) and --verify (formerly baton verify-package).

baton sync [SUBCOMMAND] [options]
Argument Required Default Description
SUBCOMMAND No -- status (or omit for default sync)
--all No false Sync all registered projects
--project ID No -- Sync a specific project by ID
--rebuild No false Full rebuild (delete all central rows then re-sync)
--migrate-storage No false Migrate JSON/JSONL flat files to SQLite (baton.db). Formerly baton migrate-storage.
--dry-run No false (with --migrate-storage) Show what would be migrated without writing
--keep-files No true (with --migrate-storage) Keep originals after migration
--remove-files No false (with --migrate-storage) Archive originals to pre-sqlite-backup/
--team-context PATH No .claude/team-context (with --migrate-storage) Path to team-context directory
--migrate-verify No false (with --migrate-storage) Verify row counts after migration
--verify [ARCHIVE] No -- Validate a .tar.gz agent-baton package. Formerly baton verify-package.
--checksums No false (with --verify) Display per-file SHA-256 checksums

Default behavior (no flags): syncs the current project by auto-detecting from the working directory.

Examples:

# Sync current project
baton sync

# Sync all registered projects
baton sync --all

# Sync a specific project
baton sync --project nds

# Full rebuild
baton sync --rebuild

# Show sync watermarks
baton sync status

# Migrate JSON/JSONL flat files to SQLite (replaces 'baton migrate-storage')
baton sync --migrate-storage --dry-run
baton sync --migrate-storage --migrate-verify
baton sync --migrate-storage --remove-files --migrate-verify

# Validate a package archive (replaces 'baton verify-package')
baton sync --verify my-agents-2.0.0.tar.gz --checksums

Exit code: 1 if --verify validation fails or sync errors occur.


Query Commands

baton query

Query execution history, agent performance, and cross-project data from the project-local baton.db.

baton query [SUBCOMMAND] [ARG] [options]

Predefined queries (subcommands):

Subcommand Description Argument
agent-reliability Agent success rates and token costs --
agent-history NAME Recent step results for a specific agent Agent name
tasks Recent task list --
task-detail TASK_ID Full breakdown for one task Task ID
knowledge-gaps Recurring knowledge gaps across tasks --
roster-recommendations Consensus roster recommendations --
gate-stats Gate pass rates by type --
cost-by-type Token costs grouped by task type --
cost-by-agent Token costs grouped by agent --
current What is running right now --
patterns Learned patterns with confidence scores --

Shared options:

Flag Default Description
--format FORMAT table Output format: table, json, csv
--days N 30 Days window for time-bounded queries
--limit N 20 Maximum rows for list queries
--status STATUS -- Filter tasks by status (for tasks subcommand)
--min-frequency N 1 Minimum occurrence for knowledge-gaps
--db PATH -- Explicit path to baton.db
--central false Query ~/.baton/central.db instead

Ad-hoc SQL:

baton query --sql "SELECT agent_name, COUNT(*) FROM step_results GROUP BY agent_name"

Examples:

# Agent reliability report
baton query agent-reliability --format json

# Task detail
baton query task-detail task-abc123

# Cost analysis
baton query cost-by-agent --days 90

# Cross-project query
baton query tasks --central --limit 50

baton cquery

Cross-project SQL queries exclusively against ~/.baton/central.db.

baton cquery [QUERY] [options]
Argument Required Description
QUERY No SQL statement or shortcut name
--format FORMAT No Output format: table (default), json, csv
--tables No List all tables and views in central.db
--table TABLE No Describe a specific table's columns
--db PATH No Override path to central.db

Shortcuts:

Name Query
agents SELECT * FROM v_agent_reliability
costs SELECT * FROM v_cost_by_task_type
gaps SELECT * FROM v_recurring_knowledge_gaps
failures SELECT * FROM v_project_failure_rate
mapping SELECT * FROM v_external_plan_mapping

Examples:

# Use a shortcut
baton cquery agents

# Custom SQL
baton cquery "SELECT * FROM executions LIMIT 10" --format json

# Schema introspection
baton cquery --tables
baton cquery --table executions

Source Commands

baton source

Manage external work-item source connections. Adapters: ado, github, jira, linear, and beads. The beads adapter is local interop — it reads an external Beads project's exported .beads/issues.jsonl interchange file (no bd Go binary or Dolt dependency).

baton source add

baton source add TYPE --name NAME [options]
Argument Required Description
TYPE Yes Source type: ado, github, jira, linear, beads
--name NAME Yes Display name for this source
--org ORG No Organization or account name (ADO/GitHub; email for Jira)
--project PROJECT No Project name within the source (ADO/Jira/Linear)
--pat-env ENV_VAR No Environment variable name holding the PAT/token
--url URL No Base URL for self-hosted instances
--config JSON No Extra adapter config as a JSON object, merged into the stored config. The beads adapter uses {"beads_dir": ".beads"}

Examples:

# Azure DevOps
baton source add ado --name "Team Board" \
    --org contoso --project "Data Platform" --pat-env ADO_PAT

# Local Beads project (reads .beads/issues.jsonl; run `bd export` first)
baton source add beads --name "Local Beads" \
    --config '{"beads_dir": ".beads"}'
baton source sync beads-beads

baton source list

baton source list

Lists all registered external sources with type, name, enabled status, and last sync time.

baton source sync

baton source sync [SOURCE_ID] [--all]
Argument Required Description
SOURCE_ID No Source ID to sync (see baton source list)
--all No Sync all registered sources

baton source remove

baton source remove SOURCE_ID

Removes a registered external source from central.db.

baton source map

baton source map SOURCE_ID EXTERNAL_ID PROJECT_ID TASK_ID [--type TYPE]
Argument Required Default Description
SOURCE_ID Yes -- Source ID
EXTERNAL_ID Yes -- External item ID (e.g. ADO work item number)
PROJECT_ID Yes -- Baton project ID
TASK_ID Yes -- Baton task/execution ID
--type TYPE No implements Relationship type: implements, blocks, related

Example:

baton source map ado-contoso-platform 12345 nds task-abc123 --type implements

Diagnostics Commands

baton doctor

Read-only installation and workspace health report: Python and package versions, bundled and project agents, knowledge packs, assurance packs, PMO UI assets, package resources, optional CLIs (bd, claude), the .beads workspace, git and git-worktree status, .claude/team-context writability, saved-plan (planner) validation, and terminology. Makes no changes to the project.

baton doctor [--json]
Flag Default Description
--json false Emit the report as JSON (schema-versioned) instead of the human-readable summary

Exits non-zero (1) if any check reports error status.

Planner validation check

The planner_validation check validates the most relevant saved plan.json with the same rules as baton plan-validate. Doctor picks which plan to validate by resolving an active task the same way the rest of the CLI does — BATON_TASK_ID env var, then the active-task marker in the project's SQLite store (honoring BATON_DB_PATH if set), then the .claude/team-context/active-task-id.txt file marker — and reports which path it took in the check's details.plan_selection field:

plan_selection Meaning
active-task An active task resolved; its plan.json was validated
fallback-first-found No active task resolved; doctor validated the first saved plan found, in fixed order: .claude/team-context/plan.json, project-root plan.json, then each executions/*/plan.json (sorted)

When plan_selection is fallback-first-found and a plan was actually found, the human-readable message adds a caveat: (caveat: no active task resolved; validating the first saved plan found, not necessarily the current one). No caveat is added when no plan was found at all — that case is reported separately as No saved plan is available to validate, not a guess.


API Server

baton serve

Start the HTTP API server (requires pip install agent-baton[api]).

baton serve [options]
Argument Required Default Description
--port PORT No 8741 Port to listen on
--host HOST No 127.0.0.1 Host to bind to
--token TOKEN No -- API token for authentication (also reads BATON_API_TOKEN env var)
--team-context DIR No .claude/team-context Path to the team-context root directory

Example:

baton serve --port 9000 --host 0.0.0.0 --token my-secret-token

Common Workflows

Full Orchestrated Task (Sequential)

# 1. Create a plan
baton plan "Add JWT auth middleware and integration tests" --save --explain

# 2. Create a feature branch
git checkout -b feat/jwt-auth

# 3. Start execution
baton execute start
export BATON_TASK_ID=<task-id-from-output>

# 4. Loop through actions
baton execute next
# -> DISPATCH: spawn subagent, then record
baton execute dispatched --step-id 1.1 --agent backend-engineer--python
# (subagent does work)
baton execute record --step-id 1.1 --agent backend-engineer--python \
    --status complete --outcome "Added JWT middleware" --files "app/auth.py"

baton execute next
# -> GATE: run the gate command
baton execute gate --phase-id 1 --result pass --output "All tests passed"

baton execute next
# -> COMPLETE
baton execute complete

Background Daemon with API

# 1. Create a plan
baton plan "Refactor data pipeline" --save

# 2. Start daemon with API server
baton daemon start --plan .claude/team-context/plan.json \
    --serve --port 8741 --max-parallel 3

# 3. Monitor progress
baton daemon status
baton execute list

# 4. Check for decisions that need human input
baton decide
baton decide --resolve req-123 --option approve

Cross-Project Analysis

# 1. Register projects with PMO
baton pmo add --id nds --name "NDS Platform" --path /home/user/nds --program NDS
baton pmo add --id atl --name "ATL Service" --path /home/user/atl --program ATL

# 2. Sync all projects to central.db
baton sync --all

# 3. Query across projects
baton cquery agents
baton cquery "SELECT project_id, COUNT(*) as tasks FROM executions GROUP BY project_id"

# 4. View portfolio health
baton pmo health

Improvement Cycle

# 1. Check for anomalies
baton anomalies

# 2. Run improvement cycle
baton learn improve --run

# 3. Review recommendations
baton budget --recommend
baton learn run-cycle

# 4. Refresh learned patterns
baton patterns --refresh

# 5. Check experiment status (folded into the learn loop)
baton learn improve --experiments

Package Distribution

# 1. Create a package
baton package --name my-agents --version 1.0.0 \
    --description "Custom agent set" --include-knowledge

# 2. Verify the package
baton sync --verify my-agents-1.0.0.tar.gz --checksums

# 3. Initialize a registry and publish
baton publish --init /shared/registry
baton publish my-agents-1.0.0.tar.gz --registry /shared/registry

# 4. Pull from registry on another machine
baton pull my-agents --registry /shared/registry --scope user

Environment Variables

The full list of Baton environment variables. The same table is mirrored in references/baton-engine.md.

Variable Purpose Default
BATON_TASK_ID Bind a shell session to a specific execution. Set after baton execute start to scope all subsequent commands. auto-detected
BATON_DB_PATH Override the project baton.db location. CLI walks upward from cwd if unset. discovered
BATON_APPROVAL_MODE PMO approval policy: local (self-approve) or team (different reviewer required). local
BATON_RUN_TOKEN_CEILING Per-run cumulative spend cap (USD float). Read fresh on every check; restored on baton execute resume. The immune system respects it; main Executor.dispatch() only warns at HIGH/CRITICAL run start (bd-3f80). unset
BATON_SOULS_ENABLED Wave 6.1 Part B persistent agent souls (signing + revocation). 0
BATON_BD_BACKEND ADR-13b WP-G bead backend. bd is the only supported value — SQLite fallback removed. Other values log a deprecation warning and BdNotAvailable is raised if bd is missing. bd
BATON_BD_ENABLED Kept for backward compatibility; has no effect after WP-G — bd is always required. 1
BATON_BD_BIN bd binary path/name. bd
BATON_BD_PREFIX Issue prefix for bd init (matches baton's bd-<hash> IDs). bd
BATON_IMMUNE_ENABLED Immune-system monitoring loop. 0
BATON_EXEC_BEADS_ENABLED Wave 6.1 Part C executable beads. Sandbox is process-level only — see references/baton-patterns.md trust-boundary section before extending to external-origin input. 0
BATON_GATE_RETRY Enable single gate-retry: on first gate failure, re-dispatch the failing step once with gate output appended to the prompt. Second failure is terminal. Writes gate_retry_dispatched or gate_failed_terminal to compliance-audit.jsonl. 0
BATON_WORKTREE_STALE_HOURS Worktree GC stale threshold in hours; legacy alias BATON_WORKTREE_GC_HOURS. GC runs on every baton execute complete. 4
BATON_API_TOKEN Bearer token for the FastAPI server (baton serve). CLI --token flag takes precedence. unset
ANTHROPIC_API_KEY Required for AI risk classification and the Haiku planner classifier. unset

Task-ID Resolution Order

Every baton execute subcommand resolves the target execution through this priority chain:

--task-id flag  ->  BATON_TASK_ID env var  ->  active-task-id.txt  ->  None
Mechanism Scope Notes
--task-id FLAG Single invocation Highest priority
BATON_TASK_ID Shell session Set with export; persists for session lifetime
active-task-id.txt Repository Updated by baton execute switch; single-execution fallback

For agentic callers (Claude Code's orchestrator): env vars do not persist across independent Bash tool calls. Pass --task-id explicitly on every CLI call when driving concurrent executions from an agent context.


Exit Codes

Code Meaning
0 Success
1 Error: missing prerequisites, validation failure, failed gate, or invalid arguments
2 Experimental feature not opted in (feature flag required but not set)

Commands that exit with code 1:

  • baton execute start -- plan file not found
  • baton validate -- errors found (or warnings in --strict mode)
  • baton spec-check -- validation failed
  • baton sync --verify -- package validation failed (formerly baton verify-package)
  • baton sync -- sync failures
  • baton source -- source not found or connection failed

Troubleshooting

"status must be one of: complete, failed, dispatched"

Cause: baton execute record --status pass (or done, success).

Fix: Use only complete or failed:

# Wrong
baton execute record --step-id 1.1 --agent foo --status pass

# Correct
baton execute record --step-id 1.1 --agent foo --status complete

"No active execution state found"

Cause: baton execute next or baton execute record was called before baton execute start, or execution-state.json was deleted.

Fix: Run baton execute start (or baton execute resume if state exists from a previous session).

Stack detection returns unknown

Cause: baton plan or baton detect cannot find config files in the current directory.

Fix: Pass --project PATH pointing to the directory containing pyproject.toml, package.json, go.mod, etc.

baton plan "..." --save --project /path/to/project/root

Plan has generic descriptions

Cause: The planner received a vague task summary.

Fix: Pass a richer description:

# Too vague
baton plan "auth" --save

# Better
baton plan "Add JWT authentication middleware to the FastAPI app, including login/logout endpoints and test coverage" --save

"API dependencies not installed"

Cause: baton serve or baton pmo serve requires FastAPI + uvicorn.

Fix:

pip install -e ".[api]"

Concurrent executions interfere with each other

Cause: Multiple executions without proper session binding.

Fix: After each baton execute start, set the BATON_TASK_ID environment variable from the printed session binding:

export BATON_TASK_ID=<task-id-from-output>

Or pass --task-id explicitly on every command.

"No sync watermarks found"

Cause: No projects have been synced to central.db yet.

Fix: Register a project with baton pmo add, then run baton sync.

"No adapter implemented for source type"

Cause: Only the ADO adapter is currently implemented.

Fix: For other sources, implement ExternalSourceAdapter in agent_baton/core/storage/adapters/<type>.py.


File Layout Reference

All engine files live under .claude/team-context/ relative to the project root:

.claude/team-context/
+-- plan.json                  Machine-readable execution plan
+-- plan.md                    Human-readable plan
+-- execution-state.json       Live engine state (crash recovery)
+-- context.md                 Shared project context
+-- mission-log.md             Structured log of agent completions
+-- usage-log.jsonl            Token and cost records per task
+-- baton.db                   SQLite database (project-local)
+-- active-task-id.txt         Active execution marker
+-- executions/
|   +-- <task-id>/
|       +-- execution-state.json
|       +-- plan.json
|       +-- plan.md
+-- traces/
|   +-- <task-id>.json         Full execution trace
+-- retrospectives/
|   +-- <task-id>.md           Post-execution analysis
+-- events/
|   +-- <task-id>.jsonl        Event log per task
+-- evolution-proposals/       Prompt improvement proposals
+-- context-profiles/          Agent context efficiency profiles
+-- learned-patterns.json      Learned orchestration patterns
+-- budget-recommendations.json

Central database: ~/.baton/central.db (cross-project data, PMO state).