- Remove unused `createServer` import from web-dir.ts (only `Socket`
is used) — fixes the lint error in CI
- Mock `isPortAvailable` in the "uses port 3000" test so it doesn't
depend on port 3000 actually being free on the host machine
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
pnpm dev and Next.js listen on :: (dual-stack IPv6) which doesn't conflict
with a 127.0.0.1-only bind check, causing isPortAvailable to return true
even when the port is in use. Now checks both 127.0.0.1 and ::1.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
In interactive mode: "Port 3000 is busy — suggesting 3001 instead.
Press Enter to accept, or type a different port."
In auto mode: "Port 3000 is busy — using 3001 instead."
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Address review feedback: use the core utility `generateSessionPrefix`
which produces proper short-form prefixes (kebab-case initials,
CamelCase extraction, etc.) instead of `projectId.slice(0, 8)`.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add `sessionPrefix` (derived from projectId.slice(0, 8)) to project
config in both interactive and auto modes so session IDs are valid
instead of `undefined-1`
- Add `name` field to project config so `ao start` prints the actual
project name instead of "undefined"
- Mark `--smart` flag as "(coming soon)" in help text since it is a
no-op stub
- Return `null` from `findFreePort` when no port is available and warn
the user to set the port manually
Closes#236
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Allows starting sessions with a different agent without changing config:
ao spawn ao --agent codex
ao spawn ao --agent codex INT-1234
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
When port 3000 is occupied, `ao init` now scans upward (3001, 3002, ...)
until a free port is found. Applies to both interactive and --auto modes.
Uses the existing isPortAvailable() from web-dir.ts (now exported).
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: make terminal server ports configurable to fix multi-dashboard EADDRINUSE
When multiple ao dashboards run simultaneously (e.g., ao on port 3000,
integrator on port 3002), both try to start terminal WebSocket servers
on hardcoded ports 3001/3003, causing EADDRINUSE. Add terminalPort and
directTerminalPort to config schema so each instance can use unique ports.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use optional() instead of default() for terminal port schema
Zod .default() always fills in the value, making config.terminalPort
never undefined and the env var fallback in buildDashboardEnv dead code.
Switch to .optional() so the priority chain works correctly:
config value > TERMINAL_PORT env var > hardcoded default.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: move terminal server defaults from 3001/3003 to 14800/14801
The 3000-3009 range is the most contested in dev tooling (Next.js
auto-increments, BrowserSync, Grafana, Rails, Express all default to
3000+). Port 14800-14899 has zero IANA registrations, zero known dev
tool conflicts, and is safely below OS ephemeral ranges.
Updated all hardcoded fallbacks, .env.local.example, docker-compose
port mappings, and documentation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: auto-detect available terminal ports for zero-config multi-dashboard
When no terminal ports are configured (no config, no env vars),
buildDashboardEnv now probes for an available port pair starting at
14800. The second `ao start` automatically gets 14802/14803 (or the
next free pair), eliminating EADDRINUSE without any user configuration.
Port detection scans in steps of 2 to keep the pair consecutive.
Explicit config/env values bypass auto-detection entirely.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: update onboarding test to use new default terminal port (14801)
The onboarding integration test had port 3003 hardcoded for the
WebSocket health check. Updated to read from DIRECT_TERMINAL_PORT
env var with 14801 as the default, matching the new port defaults.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: implement session restore for crashed/exited agents
Add true in-place session restore: same session ID, same worktree, same
metadata — optionally resuming the Claude Code conversation via --resume.
Core changes:
- Add TERMINAL_STATUSES, TERMINAL_ACTIVITIES, NON_RESTORABLE_STATUSES sets
and isTerminalSession/isRestorable helpers to types.ts
- Add SessionNotRestorableError and WorkspaceMissingError error classes
- Add restore() to SessionManager with 9-step flow: find metadata →
validate restorability → check/recreate workspace → get restore or
launch command → create runtime → update metadata
- Add restoredAt field to Session and SessionMetadata
Plugin extensions:
- workspace-worktree: exists() + restore() (git worktree prune + re-add)
- workspace-clone: exists() + restore() (git clone + checkout)
- scm-github: branchExists() via git rev-parse
- agent-claude-code: getRestoreCommand() finds latest JSONL session file
and builds claude --resume command
CLI + Web:
- Add `ao session restore <id>` subcommand
- Web restore API route uses sessionManager.restore() instead of spawn()
- SessionCard uses centralized TERMINAL_STATUSES/TERMINAL_ACTIVITIES
- Web types re-export core constants with sync tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: add "merged" to TERMINAL_STATUSES
The old inline isTerminal check included "merged" but when refactored
to use the TERMINAL_STATUSES set, "merged" was omitted. This caused
merged sessions (whose activity is not "exited") to incorrectly show
the "terminal" link and "terminate session" button.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: enrich runtime state before restore check, remove dead branchExists
- Add enrichSessionWithRuntimeState() call before isRestorable() in
restore() so crashed sessions (status "working", agent exited) are
correctly detected as terminal and eligible for restore.
- Remove dead branchExists from SCM interface and scm-github plugin
(defined but never called anywhere in the codebase).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: allow restore of crashed working sessions
Remove "working" from NON_RESTORABLE_STATUSES. The isTerminalSession()
gate already prevents restoring truly active sessions (activity is not
"exited"). This fix allows crashed agents (status "working", activity
"exited") to be restored, aligning core behavior with the UI which
already shows the restore button for this case.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: distinguish missing branch from missing restore support
Split the compound condition so workspace restore gives an accurate
error message when branch metadata is null ("branch metadata is
missing") vs when the workspace plugin lacks a restore method.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: first-class orchestrator session + file-based system prompt
Make the orchestrator a first-class managed session that flows through
the same SessionManager pipeline as worker sessions, and fix a blocking
bug where long system prompts get truncated by tmux/zsh.
Changes:
- Add OrchestratorSpawnConfig type and spawnOrchestrator() to
SessionManager interface
- Implement spawnOrchestrator() in session-manager.ts: proper
hash-based tmuxName, runtimeHandle, plugin lifecycle — no workspace
creation (uses project.path directly)
- Refactor `ao start` to use SessionManager.spawnOrchestrator()
instead of manual tmux calls + metadata writes (~80 lines removed)
- Refactor `ao stop` to use SessionManager.kill() instead of manual
tmux kill + metadata delete
- Update `ao init` next steps: guide users to `ao start` before
`ao spawn`
- Add systemPromptFile to AgentLaunchConfig for file-based system
prompts (avoids tmux truncation of 2000+ char inline prompts)
- Update agent-claude-code, agent-codex, agent-aider plugins to use
shell command substitution "$(cat '/path')" when systemPromptFile
is set
- Update runtime-tmux create() to use load-buffer/paste-buffer for
launch commands >200 chars
- Add 8 tests for spawnOrchestrator
- Fix SessionManager mock in 8 test files (add spawnOrchestrator)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use hash-based tmux name in orchestrator attach hint
The tmux attach hint after `ao start` printed the user-facing session
ID (e.g. app-orchestrator) instead of the hash-based tmux session name
(e.g. a3b4c5d6e7f8-app-orchestrator), causing "session not found"
errors. Now captures the runtimeHandle.id from spawnOrchestrator's
return value for the correct tmux target.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1. No-issue spawn: use session/{sessionId} branch instead of defaultBranch
to avoid git worktree conflicts with the main repo's checked-out branch.
2. Plugin resolution: accept importFn parameter in loadBuiltins/loadFromConfig
so CLI can pass its own import() context for pnpm strict resolution. Added
all plugin packages as CLI workspace dependencies.
3. Ad-hoc issue IDs: gracefully handle IssueNotFoundError by continuing
without tracker context instead of throwing. Non-issue errors (auth,
network) still fail fast.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: config discovery, activity detection, and metadata port storage
- findConfigFile() checks AO_CONFIG_PATH env var (resolved to absolute path)
- loadConfig() delegates to findConfigFile() for consistent validation
- Pure Node.js readLastJsonlEntry (no external tail binary), safe for
multi-byte UTF-8 at chunk boundaries
- Added "ready" activity state to agent plugins
- Store dashboardPort, terminalWsPort, directTerminalWsPort in session
metadata so ao stop targets the correct processes
- Zod schema port default aligned with TypeScript interface
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: dashboard config discovery + CLI service layer refactoring
- Config discovery via AO_CONFIG_PATH env var
- Auto port detection with PortManager
- Activity detection with ready state, pure Node.js readLastLine
- 5 CLI services: ConfigService, PortManager, DashboardManager, MetadataService, ProcessManager
- Store all service ports in metadata for ao stop
- Set NEXT_PUBLIC_ env vars for frontend terminal components
- Multi-byte UTF-8 safe readLastJsonlEntry
- Tests for all new services and utils
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address bugbot review comments (port fallback + systemPrompt)
1. Align port fallback to 3000 everywhere (matching Zod schema default):
- start.ts: config.port ?? 3000
- dashboard.ts: config.port ?? 3000
- types.ts JSDoc: "defaults to 3000"
- orchestrator-prompt.ts: already correct at 3000
2. Add --append-system-prompt to Claude Code plugin's getLaunchCommand
so orchestrator context is actually passed to the Claude agent.
Previously systemPrompt was generated but silently dropped.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove dead ConfigService mock from status test
The vi.mock for ConfigService.js referenced a deleted module.
Config mocking is already handled by the @composio/ao-core mock.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: extract shared buildDashboardEnv to eliminate duplication
Dashboard env construction (AO_CONFIG_PATH, PORT, NEXT_PUBLIC_*) was
duplicated between start.ts and dashboard.ts. Extracted into
buildDashboardEnv() in web-dir.ts (already shared by both commands).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: delegate CLI commands to core SessionManager
Replace direct tmux/metadata manipulation in CLI commands with calls to
core's SessionManager (spawn, list, kill, cleanup, send). This removes
~700 lines of reimplemented session logic and makes the CLI a thin layer
over the core service.
- Add create-session-manager.ts factory (cached PluginRegistry + SM)
- spawn: delegate to sm.spawn() instead of manual worktree/tmux setup
- session ls/kill/cleanup: delegate to sm.list()/kill()/cleanup()
- status: use sm.list() for session discovery and activity from Session
- send: resolve tmux target from session.runtimeHandle
- review-check: use sm.list() for session discovery
- dashboard/start: add --rebuild flag for stale .next cache cleanup
- Update all tests to mock create-session-manager.js
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test: add regression tests for spawn delegation and dashboard stale cache
- spawn.test.ts: verify spawn delegates to sm.spawn() with correct args,
shows hash-based tmux name in attach hint (regression for flat-naming bug)
- dashboard.test.ts: verify stale .next cache detection patterns match the
actual error (Cannot find module vendor-chunks/xterm@5.3.0.js) and that
rebuildDashboard cleans .next directory
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: ao dashboard --rebuild properly kills and restarts running server
Before: --rebuild deleted .next under the running dev server, leaving it
in a broken state (500s, missing chunks). Couldn't recover without manual
intervention.
Now: --rebuild detects the running dashboard via lsof, kills it, cleans
.next, then starts a fresh dev server on the same port. Works correctly
from any worktree since findWebDir resolves to the same web package.
- Add findRunningDashboardPid/findProcessWebDir/waitForPortFree utilities
- Split cleanNextCache from rebuildDashboard (cache-only vs full rebuild)
- Update tests for new dashboard-rebuild exports
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address bugbot review comments on PR #88
1. Cleanup dry-run now delegates to sm.cleanup({dryRun: true}) instead
of checking local status fields — ensures dry-run uses same live
checks (PR state, runtime alive) as actual cleanup.
2. Remove module-level mutable config in status.ts — pass config as
parameter to gatherSessionInfo() to avoid stale state bugs.
3. Batch-spawn duplicate detection uses sm.list() instead of broken
findSessionForIssue() which relied on flat tmux naming incompatible
with hash-based architecture.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: remove dead exports getPluginRegistry and rebuildDashboard
Both functions were exported but never imported outside test mocks.
Clean up test mocks and unused imports accordingly.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: deduplicate config/session lookups in send, hoist sm.list() in batch-spawn
1. Send command: merge resolveTmuxTarget() and resolveAgentForSession()
into a single resolveSessionContext() that loads config and calls
sm.get() once instead of twice.
2. Batch-spawn: move sm.list() call before the loop and build a Map for
O(1) duplicate lookups, avoiding repeated metadata reads + runtime
enrichment on every iteration.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: remove unused project parameter from spawnSession
After delegating to sm.spawn(), the ProjectConfig parameter is no
longer referenced — sm.spawn() resolves it internally from the
projectId. Remove the parameter and simplify both callers.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: handle process.kill race, waitForPortFree timeout, dry-run errors
1. Wrap process.kill() in try-catch to handle ESRCH when the target
process exits between detection and kill (race condition).
2. waitForPortFree() now throws on timeout instead of silently
returning, preventing the dashboard from starting on a busy port.
3. Dry-run cleanup now displays errors from PR/issue checks, matching
the non-dry-run branch behavior.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: hoist session manager in cleanup, skip dead sessions in batch-spawn
1. Hoist getSessionManager() before the dry-run if/else in cleanup
since both branches create the same instance.
2. Batch-spawn duplicate detection now excludes dead/killed/exited
sessions so crashed sessions don't block respawning the same issue.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: lsof flags, dry-run error guard, remove unused --regenerate
1. Fix lsof flag from -Fn to -Ffn so findProcessWebDir() actually
gets the file descriptor field needed to match "fcwd" markers.
2. Dry-run cleanup now guards "no sessions" message with both
killed.length === 0 AND errors.length === 0, matching the
non-dry-run branch behavior.
3. Remove unused --regenerate CLI option from ao start (defined
but never referenced in the action body).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: cache registry promise and cap stderr buffer
- Cache the Promise instead of the resolved PluginRegistry to prevent
concurrent callers from racing past the null check and creating
multiple registries before loadFromConfig completes.
- Cap stderrChunks to 100 entries since only early startup errors
(stale build detection) are checked — unbounded growth wastes memory
for long-running dashboard processes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: overhaul orchestrator prompt with comprehensive CLI reference
The generated CLAUDE.orchestrator.md now teaches the orchestrator agent
everything it needs out of the box: identity/role, complete CLI reference
for every `ao` command with flags/options, behavioral guidelines (do/don't),
session lifecycle, workflows, and anti-patterns.
- Rewrite generateOrchestratorPrompt() with detailed CLI docs
- Add "Never Do" section (no legacy scripts, no raw tmux, no coding)
- Add session lifecycle ASCII diagram adapted to project config
- Document ao send flags (--no-wait, --timeout, -f) and mechanics
- Update static CLAUDE.orchestrator.md to use ao CLI exclusively
- Add 35 unit tests for orchestrator prompt generation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: move orchestrator prompt injection into Agent plugin interface
The orchestrator prompt was being injected by directly writing
CLAUDE.local.md and CLAUDE.orchestrator.md in start.ts — Claude Code-
specific logic that doesn't work for other agents (Codex, Aider, OpenCode).
- Add `injectSystemPrompt()` to the Agent interface in types.ts
- Implement in agent-claude-code: writes CLAUDE.{name}.md + @import
- Implement in agent-codex/opencode: writes AGENTS.md
- Implement in agent-aider: writes .aider.conventions.md
- Remove ensureOrchestratorPrompt/ensureOrchestratorImport from start.ts
- start.ts now calls agent.injectSystemPrompt() (agent-agnostic)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: pass orchestrator prompt via CLI flags instead of file injection
Replace the file-based injectSystemPrompt() approach with native agent CLI
flags. Each agent plugin now handles systemPrompt in getLaunchCommand():
- Claude Code: --append-system-prompt
- Codex: --system-prompt
- Aider: --system-prompt
- OpenCode: no flag yet (ignored)
This removes the need to write CLAUDE.orchestrator.md / CLAUDE.local.md /
AGENTS.md files, making the implementation truly agent-agnostic. Also removes
the unused --regenerate flag from `ao start`.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* fix: activity detection — fix path encoding, use tail -1 for JSONL
Two tightly coupled infrastructure fixes:
- Fix toClaudeProjectPath(): leading `/` becomes `-` (not stripped),
matching Claude Code's actual project directory naming convention.
- Replace manual 4KB buffer read in readLastJsonlEntry() with
`tail -1` + JSON.parse — handles any file size, any line length,
and eliminates the truncated-line edge case entirely.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: add "ready" state, return null when unknown, remove dead code
Behavioral changes to activity detection:
- Add "ready" to ActivityState — separates "alive at prompt" from
"idle/stale". Configurable via readyThresholdMs (default 5 min).
- Agent plugins return null when they can't determine activity
(no workspace, no JSONL, no per-session tracking). Session manager
preserves existing activity instead of overwriting with a guess.
- Remove isProcessing() from Agent interface — zero callers in
production code, fully superseded by getActivityState().
- Remove extractLastMessageType() from claude-code — the field it
populated (lastMessageType) was only consumed by the old inline
CLI mapping, which is now replaced by plugin delegation.
- CLI status delegates to agent.getActivityState() (single source
of truth) with metadata fallback when plugin returns null.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test: comprehensive activity detection coverage
- activity-detection.test.ts: 42+ tests covering path encoding,
getActivityState edge cases (exited/null/fallback), real Claude Code
JSONL types, agent interface spec types, staleness thresholds,
JSONL file selection, and realistic session sequences.
- status.test.ts: plugin delegation tests — verifies CLI uses
agent.getActivityState() as single source of truth, passes
readyThresholdMs from config, falls back to metadata on null/throw.
- Integration tests: updated type expectations for null returns from
codex, opencode, and aider; added "ready" to valid state lists.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: flaky Linear integration test + missing ready label in SessionDetail
Linear API has eventual consistency — updateIssue state changes don't
propagate instantly. Poll with retries instead of asserting immediately.
Also adds "ready" entry to SessionDetail activityLabel map (was missing,
causing fallback to dim/unstyled rendering).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: pure Node.js readLastJsonlEntry, use pollUntilEqual for Linear test
Replace `tail -1` with pure Node.js implementation that reads backwards
from end of file in 4KB chunks. No external binary dependency — works
on any platform.
Fix flaky Linear integration test by using the existing pollUntilEqual
helper instead of an inline retry loop. Linear API has eventual
consistency; pollUntilEqual retries for up to 5s with 500ms intervals.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use tail -1 for readLastJsonlEntry, add real-data integration test
Replace over-engineered pure Node.js backward-reading implementation with
simple `tail -1` via execFile. The codebase already shells out to tmux,
git, and ps everywhere — tail is no different.
Add integration test that validates toClaudeProjectPath() and
readLastJsonlEntry() against real ~/.claude/projects/ data on disk.
No API key needed — just requires Claude to have been run once.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: implement seamless onboarding with enhanced documentation
- Add comprehensive README.md (18KB) with quick start, core concepts, and FAQ
- Add detailed SETUP.md (16.5KB) with prerequisites, integration guides, and troubleshooting
- Add examples/ directory with 5 ready-to-use config templates:
- simple-github.yaml: Minimal GitHub setup
- linear-team.yaml: Linear integration
- multi-project.yaml: Multiple repos
- auto-merge.yaml: Aggressive automation
- codex-integration.yaml: Using Codex agent
- Add environment detection (git repo, remote, branch, auth status)
- Auto-fill prompts with smart defaults from detected environment
- Add prerequisite validation (git, tmux, gh CLI)
- Show actionable next steps and warnings
- Parse owner/repo from git remote automatically
- Detect LINEAR_API_KEY and SLACK_WEBHOOK_URL in environment
- Prompt for Linear team ID when Linear tracker selected
- Format all files with Prettier for consistency
Reduces onboarding time from 30+ minutes to ~5 minutes:
1. Install CLI: `npm install -g @composio/ao-cli`
2. Run init: `ao init` (auto-detects everything)
3. Spawn agent: `ao spawn my-project ISSUE-123`
Users no longer need to:
- Manually parse git remote URLs
- Look up current branch names
- Remember YAML syntax
- Search for Linear team IDs
- Debug missing prerequisites
- ✅ pnpm build - All packages compile
- ✅ pnpm typecheck - No TypeScript errors
- ✅ pnpm lint - No new linting issues
- ✅ pnpm format - All files formatted
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* docs: update installation instructions to reflect npm not yet published
Package is not published to npm yet, so users must build from source.
Updated README.md and SETUP.md to:
- Make 'build from source' the primary installation method
- Add note that npm publishing is coming soon
- Include pnpm as a prerequisite
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* feat: add ao init --auto --smart for zero-config setup
Implements intelligent config generation with project type detection.
## What's New
### ao init --auto
- Zero prompts - auto-generates config with smart defaults
- Detects: git repo, remote, branch, languages, frameworks, tools
- Generates project-specific agentRules based on detected tech stack
### Project Detection
- Languages: TypeScript, JavaScript, Python, Go, Rust
- Frameworks: React, Next.js, Vue, Express, FastAPI, Django, Flask
- Tools: pnpm workspaces, test frameworks
- Package managers: pnpm, yarn, npm
### Rule Templates
Created templates for:
- base.md - Universal best practices
- typescript.md - TS strict mode, ESM, type imports
- javascript.md - Modern ES6+ patterns
- react.md - Hooks, composition, best practices
- nextjs.md - App Router, Server Components
- python.md - Type hints, PEP 8
- go.md - Error handling, defer patterns
- pnpm-workspaces.md - Monorepo commands
### Example Output
```bash
ao init --auto
# Detects:
# ✓ TypeScript + pnpm workspaces
# ✓ React + Next.js
# ✓ Vitest
# Generates:
agentRules: |
Always run tests before pushing.
Use TypeScript strict mode.
Use ESM modules with .js extensions.
Use React best practices (hooks, composition).
Before pushing: pnpm build && pnpm typecheck && pnpm lint && pnpm test
```
## Benefits
- **5 seconds** instead of 5 minutes
- **Zero config knowledge** required
- **Context-aware rules** tailored to your stack
- **Still customizable** - edit the generated config
## Future: --smart (AI-powered)
Flag added but not yet implemented. Will use Claude Code to:
- Analyze CLAUDE.md, CONTRIBUTING.md
- Read CI/CD config
- Generate custom rules based on project patterns
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: detect repo default branch instead of current branch
Fixes Bugbot issue: "Current branch wrongly suggested as default base branch"
## Problem
detectEnvironment was using `git branch --show-current` to suggest
defaultBranch in the config. If a user ran `ao init` while on a feature
branch like `feat/my-work`, the wizard would suggest that feature branch
as the default, causing agents to branch from the wrong base.
## Solution
Added detectDefaultBranch() function with 3 fallback methods:
1. git symbolic-ref refs/remotes/origin/HEAD (most reliable)
2. GitHub API via gh CLI (if ownerRepo known)
3. Check common branch names: main, master, next, develop
Now EnvironmentInfo tracks both:
- currentBranch: The checked-out branch (for display only)
- defaultBranch: The repo's base branch (for config)
## Testing
Tested on feat/seamless-onboarding branch:
- Current branch: feat/seamless-onboarding (displayed)
- Default branch: main (correctly detected for config)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: prevent duplicate framework detection in Python projects
Fixes Bugbot issue: "Duplicate frameworks when multiple Python config files exist"
## Problem
When both requirements.txt and pyproject.toml exist and mention the same
framework (e.g., FastAPI), the detection loop added it to the frameworks
array twice, causing duplicate rules in the generated config.
## Solution
Added addFramework() helper that checks if framework already exists before
adding to the array. Also prevents pytest from being set multiple times as
testFramework.
## Testing
Verified with test repo containing both files with FastAPI:
- Before: Would add 'fastapi' twice
- After: Only adds 'fastapi' once ✓
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address Bugbot review comments
- Remove redundant conditional in --smart flag (both branches were identical)
- Include templates directory in npm package files
* fix: add existence check for base.md template file
Add existsSync guard before reading base.md to handle missing templates gracefully, consistent with other template file reads.
* fix: use direct tool invocation instead of which command
Replace 'which' with direct tool invocation (tmux -V, gh --version)
for better portability on minimal Linux systems where 'which' may
not be installed.
* fix: address Bugbot review comments
- Simplify gh auth status check to rely on exit code instead of output string
- Remove async from synchronous functions (detectProjectType, generateRulesFromTemplates)
* feat: add setup script for one-command installation
Add scripts/setup.sh that:
- Installs pnpm if not present
- Installs dependencies
- Builds all packages
- Links CLI globally
Updated README with simplified setup instructions using the script.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: correct npm link command in setup script
Remove incorrect -g flag from npm link command. The correct syntax is to cd into the package directory and run npm link without flags.
* fix: address Bugbot review comments on init command
- Validate --smart flag requires --auto (prevents silent ignore)
- Fix path validation to check user-specified path (not CWD)
These fixes address medium and low severity issues found by Cursor Bugbot
in PR #66 review.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* docs: add DirectTerminal troubleshooting and fix setup script
- Add TROUBLESHOOTING.md documenting node-pty posix_spawnp error
- Update setup.sh to rebuild node-pty from source (fixes DirectTerminal)
- Ensures seamless onboarding with working terminal out-of-the-box
Resolves DirectTerminal WebSocket failures from incompatible prebuilt binaries.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: resolve variable scope issue in init command validation
- Move path variable outside if block to fix TypeScript scope error
- Only validate path existence if projectId is provided
- Use inline tilde expansion instead of missing expandHome import
Fixes build error that prevented setup.sh from completing.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: automate node-pty rebuild to eliminate terminal issues
- Add postinstall hook to automatically rebuild node-pty after pnpm install
- Create scripts/rebuild-node-pty.js for automatic rebuild with error handling
- Remove manual node-pty rebuild from setup.sh (now automatic)
This ensures DirectTerminal works correctly on every installation without
manual intervention. Fixes posix_spawnp errors from incompatible prebuilt
binaries across different systems and installations.
Resolves issue where users would encounter blank terminals after setup.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* docs: update TROUBLESHOOTING with automatic node-pty rebuild
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* docs: add comprehensive README with quick start guide
- 3-line magical setup: clone → setup → init → start
- Architecture overview with plugin slots table
- Usage examples and auto-reaction configuration
- Links to detailed docs (SETUP.md, TROUBLESHOOTING.md, examples/)
- Philosophy: push not pull, amplify judgment
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: resolve ESLint errors in rebuild-node-pty script
- Add scripts directory configuration to eslint.config.js
- Configure Node.js globals (console, process) for scripts
- Remove unused error variable from catch block
Fixes lint CI failure.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: warn when auto mode uses placeholder repo value
- Detect when 'owner/repo' placeholder is used in --auto mode
- Show warning: 'Could not detect GitHub repository'
- Update next steps to emphasize editing config when placeholder used
- Prevents silent failures when spawning agents with invalid repo
Addresses Bugbot review comment about silent placeholder values.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
Fixes issue where spawned sessions would send the prompt text but the Enter
keystroke would not be submitted, requiring manual Enter press.
Changes:
- Increase delay after paste-buffer from 300ms to 1000ms in tmux.ts sendKeys()
to ensure tmux processes the paste before receiving Enter keystroke
- Add 100ms delay after Escape key to ensure it's processed before pasting
- Increase spawn wait time from 1s to 2s before sending initial prompt to
allow Claude to fully initialize (permission prompts, startup, etc.)
These longer delays account for:
1. tmux paste buffer processing time
2. Claude permission prompt interactions
3. Agent initialization and readiness
Closes: FIX-SPAWN-PROMPT-SUBMIT
The spawn command was creating tmux sessions without calling agent.getEnvironment(),
causing spawned sessions to inherit CLAUDECODE from the parent orchestrator session.
This caused Claude to refuse to start with "cannot launch inside another Claude Code
session" error.
Now properly calls agent.getEnvironment() and merges those env vars (including
CLAUDECODE="") into the tmux session creation.
Fixes sessions ao-22 through ao-25 which were spawned but never had Claude running.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* feat: implement ao start command for unified orchestrator startup
Adds `ao start` and `ao stop` commands to unify orchestrator and
dashboard startup. Key features:
- Generates CLAUDE.orchestrator.md with project-specific context
- Auto-imports orchestrator prompt via CLAUDE.local.md
- Creates orchestrator tmux session with agent
- Starts Next.js dashboard server
- Supports --no-dashboard, --no-orchestrator, --regenerate flags
- Idempotent operation (safe to run multiple times)
- Computes orchestrator ID from config (not session search)
- Dashboard button always visible for orchestrator terminal
Components:
- packages/core/src/orchestrator-prompt.ts: Prompt generator
- packages/cli/src/commands/start.ts: Start/stop commands
- Modified exports and dashboard UI for orchestrator support
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* feat: add automatic metadata updates via Claude Code hooks
CRITICAL: This makes the dashboard work by auto-updating metadata when
agents run git/gh commands. Without this, PRs created by agents never
appear on the dashboard.
Changes:
- packages/core/src/claude-hooks.ts: Setup Claude hooks (settings.json + metadata-updater.sh)
- ao start: Automatically configures Claude hooks in project directory
- ao spawn: Sets AO_SESSION and AO_DATA_DIR env vars for hook script
- metadata-updater.sh: Detects gh pr create, git checkout -b, gh pr merge
How it works:
1. PostToolUse hook fires after every Bash command
2. metadata-updater.sh receives JSON with command and output
3. Pattern matches git/gh commands and updates flat metadata files
4. Dashboard reads metadata files to show PR/branch/status
The .claude directory is symlinked from main repo to worktrees so all
sessions share the same hook config.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* refactor: move hook setup to Agent plugin interface
ARCHITECTURE: Hooks setup must go through the Agent plugin interface,
not be hardcoded for Claude Code. This allows other agents (Codex,
Aider, OpenCode) to implement their own metadata update mechanisms.
Changes:
- Added Agent.setupWorkspaceHooks() method to types.ts
- Added WorkspaceHooksConfig interface
- Implemented setupWorkspaceHooks() in Claude Code plugin
- ao start: calls agent.setupWorkspaceHooks() instead of direct setup
- ao spawn: calls agent.setupWorkspaceHooks() for new worktrees
- Uses $CLAUDE_PROJECT_DIR variable for hook path (works with symlinked .claude)
Each agent plugin now implements its own hook mechanism:
- Claude Code: .claude/settings.json with PostToolUse hook
- Future: Codex, Aider, OpenCode with their own config formats
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address Cursor Bugbot review comments
Fixes 3 issues identified by Cursor Bugbot:
1. HIGH: ao start is now truly idempotent - if orchestrator session exists,
it skips creating the session but still proceeds with dashboard startup
and hook configuration. This allows `ao start` to recover from dashboard
crashes without failing.
2. MEDIUM: Dashboard orchestrator button now finds the actual running
orchestrator session instead of always using the first project. Fallback
to first project ID if no orchestrator is running.
3. LOW: Deduplicated findWebDir() function by moving it to shared utility
lib/web-dir.ts. Now used by both dashboard.ts and start.ts.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: resolve ESLint errors
Fixes 4 ESLint errors identified in CI:
- Added { cause: err } to Error constructors (preserve-caught-error rule)
- Prefixed unused parameter 'config' with underscore in setupWorkspaceHooks
- Prefixed unused variable 'projectId' with underscore in stop command
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address bugbot review comments - markdown escaping and unused module
- Fix markdown code fence escaping in orchestrator-prompt.ts (change
`\\\`` to `\`` for proper markdown rendering)
- Remove unused claude-hooks.ts module (functionality moved to plugin)
- Clean up exports from core/src/index.ts
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address remaining bugbot issues - metadata path, duplication, summary
HIGH severity - Fix metadata path mismatch for worker sessions:
- Add AO_PROJECT_ID environment variable in spawn.ts
- Update metadata-updater hook script to construct correct path:
* Worker sessions: $AO_DATA_DIR/${AO_PROJECT_ID}-sessions/$AO_SESSION
* Orchestrator: $AO_DATA_DIR/$AO_SESSION (no project ID)
- Fixes silent hook failures where PRs/branches never appeared on dashboard
LOW severity - Remove code duplication in hook setup:
- Extract setupHookInWorkspace() helper function (90 lines)
- Refactor setupWorkspaceHooks() to use helper (from 80 lines to 4)
- Refactor postLaunchSetup() to use helper (from 82 lines to 6)
- Eliminates risk of methods drifting out of sync
LOW severity - Fix misleading summary output:
- Change "Orchestrator started" to "Startup complete" when components skipped
- Only show dashboard URL when --no-dashboard NOT used
- Only show session info when --no-orchestrator NOT used
- Show "already running" status when orchestrator exists
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address new bugbot issues - hook quoting, orchestrator link, pkill scope
HIGH severity - Fix Claude hook command quoting:
- Remove embedded double quotes from $CLAUDE_PROJECT_DIR path
- Change from '"$CLAUDE_PROJECT_DIR"/.claude/...' to '$CLAUDE_PROJECT_DIR/.claude/...'
- Prevents hook execution failures if runner treats command as literal path
MEDIUM severity - Fix orchestrator link pointing to nowhere:
- Only show "orchestrator terminal" link when session actually exists
- Remove fallback to computed/hardcoded "ao-orchestrator" ID
- Prevents 404s when user clicks link before starting orchestrator
MEDIUM severity - Fix stop command killing unrelated processes:
- Replace broad `pkill -f "next dev -p ${port}"` with targeted approach
- Use `lsof -ti :${port}` to find exact PID listening on port
- Only kill the specific process, not any process mentioning "next dev"
- Prevents accidentally killing unrelated Next.js dev servers
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: orchestrator metadata path and multi-pid dashboard stop
HIGH severity - Fix orchestrator AO_PROJECT_ID pollution:
- Orchestrator intentionally omits AO_PROJECT_ID (uses flat metadata path)
- agent.getEnvironment() adds AO_PROJECT_ID=project.name
- Object.assign() merged this in, breaking metadata hook path lookup
- Fix: delete environment.AO_PROJECT_ID after merge
- Ensures orchestrator metadata updates work correctly
MEDIUM severity - Fix stopDashboard with multiple PIDs:
- lsof -ti :PORT returns multiple PIDs (one per line) for parent+children
- Passing entire multi-line string to kill fails (can't parse newlines)
- Fix: split stdout by newlines, filter empty, pass PIDs as separate args
- Now correctly stops dashboard even when multiple Node processes exist
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: remove AO_PROJECT_ID from agent plugins to fix metadata path mismatch
The agent.getEnvironment() method was setting AO_PROJECT_ID to
config.projectConfig.name, but different callers have different metadata
path schemes:
- spawn.ts writes to project-specific directories (dataDir/{projectId}-sessions/)
- start.ts writes to flat directories for orchestrator (dataDir/)
- session-manager writes to flat directories (dataDir/)
Setting AO_PROJECT_ID in getEnvironment() caused the metadata updater hook
to look for files in the wrong location for orchestrator and session-manager
flows, breaking automatic metadata updates.
Fix: Remove AO_PROJECT_ID from all agent plugins' getEnvironment() methods
and make it the caller's responsibility to set when using project-specific
directories. Only spawn.ts sets it now.
Changes:
- Remove AO_PROJECT_ID assignment from getEnvironment() in all 4 agent plugins
(claude-code, aider, codex, opencode)
- Update corresponding tests to expect AO_PROJECT_ID to be undefined
- Remove delete environment.AO_PROJECT_ID statement from start.ts (no longer needed)
- Add comments explaining the metadata path scheme contract
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: only run orchestrator setup when actually starting orchestrator
The orchestrator-specific setup steps (generating CLAUDE.orchestrator.md,
configuring CLAUDE.local.md, and setting up agent hooks) were executing
unconditionally, even when --no-orchestrator was passed. This caused
`ao start --no-dashboard` to fail if hook setup had errors, because the
hook setup was fatal and blocked the dashboard from starting.
Fix: Move all orchestrator setup steps inside the `if (opts?.orchestrator !== false)`
guard, and specifically inside the `else` branch (when session doesn't already exist).
Now these steps only run when we're actually creating a new orchestrator session.
This allows:
- `ao start --no-orchestrator` to start only the dashboard
- Skipping setup when orchestrator session already exists
- Setup to be non-blocking for dashboard-only mode
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: eliminate redundant getAgent call by hoisting agent declaration
The agent instance was being created twice in the orchestrator setup block:
- Once at line 237 inside the hook setup try block
- Again at line 253 for getting the launch command
This creates duplicate agent instances unnecessarily. Fixed by declaring
the agent variable before the hook setup try block, allowing it to be
reused for both hook setup and launch command generation.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address resource leaks and undefined env variable
Fixed 4 Bugbot issues:
1. HIGH: Undefined $CLAUDE_PROJECT_DIR in hook script path
- Changed setupWorkspaceHooks to use absolute path instead of undefined
env variable
- Matches approach used in postLaunchSetup for consistency
2. HIGH: Orchestrator session leaks when metadata write fails
- Added try-catch around tmux session launch and metadata write
- Kills tmux session if metadata write or agent launch fails
- Prevents orphaned sessions from consuming resources
3. MEDIUM: Dashboard process leaks when orchestrator setup fails
- Wrapped orchestrator setup in try-catch block
- Kills dashboard child process if orchestrator setup fails
- Prevents orphaned Next.js server from blocking future starts
4. LOW: Inconsistent indentation (fixed as side effect of restructuring)
- Refactored error handling simplified indentation structure
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
* feat: validate tracker issues on spawn with fail-fast behavior
Implement issue validation in spawn flow to fail fast when issues don't exist,
preventing creation of sessions with broken issue references.
**Key Changes:**
- Add isIssueNotFoundError() helper to detect "not found" errors
- Validate issues BEFORE creating resources (workspace, runtime, session ID)
- Fail fast with clear error messages when issues don't exist
- Categorize batch spawn failures (not_found, auth_failed, other)
- Add comprehensive tests (4 new test cases, all 25 tests pass)
- Update documentation with new spawn flow
**Behavior:**
- Issue exists → spawn proceeds, reports success
- Issue not found → fail with "does not exist in tracker" message
- Auth/network error → fail with error details
- No issue provided → spawn ad-hoc session without issue tracking
**Benefits:**
- No wasted resources on invalid issues
- Clear, actionable error messages for orchestrators
- Maintains backwards compatibility (ad-hoc sessions still work)
- Separation of concerns (spawn validates, orchestrator creates issues)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address bugbot review comments - improve error detection and add CLI validation
**Issue 1: CLI validation was missing**
- CLI's spawnSession bypassed core session manager validation
- Added tracker plugin support to CLI (getTracker function)
- Validate issues in CLI before creating worktrees/tmux sessions
- Error categorization now matches actual tracker errors, not git/tmux errors
**Issue 2: Overly broad "not found" matching**
- Previous: matched any "not found" (including "API key not found", "Team not found")
- Fixed: Check for issue-specific patterns AND exclude infrastructure errors
- Now matches: "issue" + "not found", "no issue found", "could not find issue"
- Excludes: "api key", "team", "configuration", "workspace", "organization", "endpoint"
**Changes:**
- packages/core/src/types.ts: More specific isIssueNotFoundError logic
- packages/cli/src/commands/spawn.ts: Add validation before workspace creation
- packages/cli/src/lib/plugins.ts: Add tracker plugin support + getTracker
- packages/cli/package.json: Add tracker plugin dependencies
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: resolve CI lint and test failures
**Lint fixes:**
- Combine duplicate imports in session-manager.ts and spawn.ts
- Add error cause preservation in CLI error throws
**Test fixes:**
- Mock getIssue response in plugin-integration test for spawn validation
- Test now provides proper GitHub issue response for validation to pass
**Changes:**
- packages/core/src/session-manager.ts: Combine imports using inline type syntax
- packages/cli/src/commands/spawn.ts: Merge duplicate plugin imports, add error cause
- packages/core/src/__tests__/plugin-integration.test.ts: Add mockGh for issue validation
All lint checks pass (0 errors, 11 warnings - existing)
All tests pass (128 tests)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: address bugbot review comments - error categorization and CLI test mocking
- Fix case-sensitive auth check in batch-spawn (now catches 'Authentication' errors)
- Fix workspace exclusion in isIssueNotFoundError to not shadow valid issue errors
- Add missing tracker mock to CLI tests (fixes all 5 test failures)
* fix: address remaining bugbot comments - remove duplication and redundancy
- Remove redundant sessionId reassignment after reservation loop
- Remove duplicate suggestion message in CLI error handler
- Remove duplicate issue validation from CLI to avoid DRY violation
(validation remains in core SessionManager.spawn for programmatic use)
* fix: restore sessionId assignment needed for TypeScript flow analysis
The assignment after the loop is not logically redundant but is required
for TypeScript's definite assignment analysis. Without it, TS cannot
guarantee sessionId is assigned after the loop.
* fix: remove unused tracker plugin code from CLI
- Remove getTracker function (no longer used after removing CLI validation)
- Remove tracker plugin imports and dependencies
- Remove mockGetTracker from tests
- Reduces bundle size and dependency coupling
* chore: update pnpm lockfile after removing tracker dependencies
* fix: remove console output from core library
Core library should not have console.log/console.warn calls as it's
used by CLI, web dashboard, and tests. Console output couples the
library to a specific output mechanism and produces noise in non-CLI
contexts. Callers can handle output presentation as needed.
* fix: remove unused catch parameter to fix lint error
* fix: remove redundant success messages in CLI spawn command
spawnSession already outputs spinner.succeed/fail with details, so
additional success/failure messages in command handlers are redundant.
Keep batch-spawn error categorization for summary purposes.
* fix: remove unused catch parameter
* fix: simplify batch-spawn error reporting
Remove misleading error categorization from batch-spawn. Since spawn no
longer categorizes errors as "not_found" or "auth_failed", the batch-spawn
summary section was filtering on error types that were never set.
Simplified to just list all failed issues with their error messages.
Also fixed single spawn error handling to log the error message before
exiting.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: remove dead code from isIssueNotFoundError
The exclusion guard for infrastructure errors (lines 863-876) was
completely redundant. Every return pattern already requires "issue" to
be present in the message, so a message without "issue" would naturally
return false from the main return statement. The guard added no value
and created confusion for maintainers.
Simplified by removing the redundant guard entirely.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
* feat: add npm publishing support with @composio scope
Set up Changesets for version management, add publish metadata to all 20
packages under the @composio scope, create an unscoped wrapper package
(@composio/agent-orchestrator) for global install, and add a GitHub
Actions release workflow.
- Rename all packages from @agent-orchestrator/* to @composio/ao-*
- Add @composio/agent-orchestrator wrapper (bin shim → @composio/ao-cli)
- Add license, repository, homepage, bugs, files, engines to all packages
- Add .npmrc (access=public), MIT LICENSE file
- Add .changeset/ config with linked versioning for all packages
- Add .github/workflows/release.yml (changesets publish CI)
- Add changeset, version-packages, release scripts to root
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: exclude private web package from release build
The release script now filters out @composio/ao-web, matching the
workflow's existing exclusion and preventing a Next.js build failure
from blocking npm publishing.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
* feat: implement layered prompt system for agent sessions
Replace hardcoded spawn prompts with a 3-layer composition system:
- Layer 1: BASE_AGENT_PROMPT constant with session lifecycle, git workflow, PR handling
- Layer 2: Config-derived context (project, repo, tracker, issue details via generatePrompt())
- Layer 3: User-customizable rules via agentRules (inline) and agentRulesFile (path)
The session-manager path fetches issue context from the tracker plugin and passes
the composed prompt via AgentLaunchConfig.prompt. The CLI spawn path delivers it
via tmux send-keys to keep agents interactive for follow-up messages.
Returns null when nothing to compose (no issue, no rules), preserving backward
compatibility for bare launches.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use tmuxSendKeys for multi-line prompt delivery in CLI spawn
The buildPrompt() output contains newlines which tmux send-keys -l treats
as Enter keypresses, splitting the prompt into separate submissions. Use
the core tmuxSendKeys() helper which handles multi-line text via
load-buffer/paste-buffer.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
* fix: update spawn test to verify tmuxSendKeys usage
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: enrich `ao status` with PR, CI, review, threads, and activity columns
The status command now displays a rich table with branch, PR number, CI
status, review decision, pending review threads, and agent activity state.
Data is fetched from the SCM plugin (GitHub) in parallel for performance.
Closes INT-1348
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address Bugbot review — thread errors, PR fallback, activity mapping
- Thread errors: `.catch(() => null)` instead of `.catch(() => [])` so
failed getPendingComments shows `-` not `0`
- PR fallback: extract PR number from metadata URL when SCM lookup fails
- Activity fallback: use metadata `status` when agent introspection is
unavailable (working→active, idle→idle, stuck/errored→blocked)
- Activity mapping: treat `assistant`/`result` as idle, only `tool_use`
and `user` as active — avoids marking completed responses as working
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* feat: implement CLI with all commands (init, status, spawn, session, send, review-check, dashboard, open)
Implement the full `ao` CLI using Commander.js with 9 commands:
- ao init: Interactive setup wizard that creates agent-orchestrator.yaml
- ao status: Colored terminal table of all sessions (branch, activity, PR, CI)
- ao spawn <project> [issue]: Spawn single agent session (worktree + tmux + agent)
- ao batch-spawn <project> <issues...>: Batch spawn with duplicate detection
- ao session ls|kill|cleanup: Session management subcommands
- ao send <session> <message>: Smart message delivery with busy detection/retry
- ao review-check [project]: Scan PRs for review comments, trigger agent fixes
- ao dashboard: Start the Next.js web dashboard
- ao open [target]: Open session(s) in terminal tabs
Shared libraries:
- lib/shell.ts: Shell command helpers (tmux, git, gh wrappers)
- lib/metadata.ts: Flat metadata file read/write (backwards-compatible format)
- lib/format.ts: Terminal formatting (colors, tables, banners)
All commands code against core interfaces and flat metadata files,
matching the behavior of the reference bash scripts in scripts/.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address PR review — extract shared helpers, fix bugs, add tests
- Extract getTmuxSessions/getTmuxActivity to lib/shell.ts (was duplicated in 5 files)
- Fix readMetadata unsafe cast: return Partial<SessionMetadata> instead
- Fix dashboard webDir path: resolve from package root, not dist/
- Fix dashboard spawn error handling: add child.on("error")
- Fix getNextSessionNumber: escape regex metacharacters in prefix
- Fix fallback worktree creation: use existing branch name, not detached HEAD
- Fix post-create hooks: run before agent launch, not after
- Fix open --new-window: pass option through to openInTerminal
- Fix cleanup dry-run: separate summary message for dry-run mode
- Add Claude session introspection to status command (TTY→PID→CWD→JSONL)
- Add vitest test suite: 72 tests covering commands and lib utilities
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address all PR review issues, add lint/format compliance
Review fixes:
- Extract getTmuxSessions/getTmuxActivity to lib/shell.ts (was duped in 5 files)
- Fix readMetadata: return Partial<SessionMetadata> instead of unsafe cast
- Fix dashboard webDir: use createRequire + __dirname for ESM compat
- Fix dashboard spawn: add child.on("error") handler
- Fix getNextSessionNumber: escape regex metacharacters in prefix
- Fix fallback worktree: use existing branch name, not detached HEAD
- Fix post-create hooks: run before agent launch, not after
- Fix open --new-window: pass option through to openInTerminal
- Fix cleanup dry-run: separate summary message for dry-run mode
- Add Claude session introspection to status (TTY→PID→CWD→JSONL)
- Add port validation in init wizard
- Add clarifying comment for tmux C-u send-keys
Lint/format:
- Add no-console override for CLI package in eslint config
- Fix duplicate imports (node:fs, @agent-orchestrator/core)
- Fix unused variable in send test
- Apply prettier formatting across all files
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address codex review — fd leak, input validation, security hardening
- Wrap openSync/readSync in try/finally to prevent fd leak on error
- Add timeout NaN/<=0 guard in send command
- Add port validation (1-65535) in dashboard command
- Sanitize issueId for git-ref-safe branch names
- Add --project validation in session ls/cleanup
- Fix batch-spawn same-run duplicate detection
- Replace shell interpolation with safe ps + JS filtering
- Wrap temp file usage in try/finally for cleanup on error
- Read only tail of JSONL files to avoid large file loads
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address remaining PR review comments
- Use `=== null` instead of falsy check for git worktree result (spawn.ts)
- Wrap spinner in try/catch so it stops on error (spawn.ts)
- Use exact match instead of substring for issue duplicate detection (metadata.ts)
- Check git worktree remove result before printing success (session.ts)
- Skip banner/headers/footer when --json is passed (status.ts)
- Add error handler on browser-open spawn (dashboard.ts)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address bugbot review — interrupt before send, error resilience, worktree validation
- review-check: send C-c + C-u to interrupt busy agent and clear input before
delivering fix prompt, matching the reference bash script behavior
- review-check: wrap per-session send in try/catch so one failure doesn't abort
remaining sessions
- spawn: check worktree creation return value and throw on failure instead of
continuing with non-existent worktree path
- Update test mock for detached worktree to return success
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address 4 bugbot findings — status type, TTY match, retry safety, comment counting
- spawn: write status "spawning" (not "starting") to match SessionStatus type
- status: use column-based exact TTY match to prevent pts/1 matching pts/10
- send: use null-safe tmux() helper in retry loop instead of throwing exec()
- review-check: use GraphQL reviewThreads to count only unresolved comments,
preventing fix prompts on PRs with all threads resolved
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: GraphQL variable passing and env var name sanitization
- review-check: use -F flags for GraphQL variables instead of string
interpolation to prevent injection via repo config values
- spawn: sanitize env var name by replacing non-alphanumeric chars with
underscores (my-app → MY_APP_SESSION, not MY-APP_SESSION)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: add -l flag to tmux send-keys and remove dead activityIndicator code
- Add literal (-l) flag to send-keys so user text isn't interpreted as
tmux key names (e.g. "Enter", "Escape")
- Remove unused activityIndicator function from format.ts and its tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: move agent-specific logic from CLI into agent plugins
detectActivity, introspect, and getLaunchCommand now live in the agent
plugins (claude-code, codex, aider) instead of being hardcoded in the
CLI commands. The Agent interface's detectActivity takes a plain string
of terminal output instead of a Session object, making plugins trivially
unit-testable.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use -f for string GraphQL vars and -l flag for tmux send-keys
Addresses two bugbot findings in review-check.ts:
1. Use -f (string) instead of -F (typed) for owner/name GraphQL
variables to prevent numeric coercion of repo names.
2. Use -l (literal) flag with send-keys and separate Enter call,
matching the established tmux safety pattern in send.ts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: guard empty terminal output in lifecycle-manager and deduplicate send.ts
- lifecycle-manager: skip detectActivity when terminal output is empty
to prevent false "killed" state when runtime probe returns no data
- send.ts: collapse identical isBusy/isProcessing into single isActive
- tests: use non-empty mock terminal output so detectActivity is exercised
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: validate message before side effects, remove dead updateMetadataField
- send.ts: move message validation before idle-wait loop and C-u clear
so running `ao send session` with no message exits immediately without
touching the tmux session
- metadata.ts: remove exported updateMetadataField (unused in production)
- metadata.test.ts: remove corresponding tests
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: add -l flag and separate Enter for spawn prompt send-keys
Use literal flag (-l) when sending the initial prompt via tmux
send-keys in spawn.ts, and send Enter as a separate call. This
matches the pattern used in send.ts and review-check.ts and prevents
tmux from interpreting special characters in the issue ID.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: strict session prefix matching and validate project before use
- session-utils: add matchesPrefix() using regex ^prefix-\d+$ to prevent
cross-project misattribution with overlapping prefixes (e.g. "app" vs
"app-v2")
- Replace all startsWith(`${prefix}-`) calls across status.ts,
review-check.ts, session.ts, and open.ts with matchesPrefix()
- status.ts, review-check.ts: move project validation before the
projects map construction so invalid project IDs exit before any
access to undefined config
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: deduplicate escapeRegex and add -l flag to spawn send-keys
- Export escapeRegex from session-utils.ts, remove duplicate from spawn.ts
- Add -l (literal) flag to tmux send-keys for postCreate hooks and
launch command, with Enter sent separately
- Prevents tmux from interpreting key names in user config or agent
commands
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: update detectActivity to sync string signature across all plugins
After rebase on main, all agent plugins and their tests still had the
old async detectActivity(session: Session) signature. Updated to the
new sync detectActivity(terminalOutput: string): ActivityState across:
- agent-claude-code, agent-codex, agent-aider, agent-opencode plugins
- All plugin unit tests (test terminal output patterns, not process state)
- All integration tests (capture tmux pane output before calling)
- status.ts: use getSessionInfo() instead of nonexistent introspect()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: integration tests expect idle (not exited) from detectActivity after process exit
detectActivity is a pure terminal-text classifier that returns "idle" for
empty/shell-prompt output. Process exit detection is handled by isProcessRunning.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: check last-line prompt before historical activity patterns in detectActivity
Reorder classifyTerminalOutput to check the last line for a prompt
character before scanning the full buffer for activity indicators like
"Reading" or "Thinking". This prevents historical output in the capture
buffer from causing false "active" results when the agent is idle.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: update pnpm-lock.yaml for web dashboard dependencies
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: preserve state on getOutput failure, check permission prompts before activity indicators
- lifecycle-manager: remove .catch(() => "") from getOutput so failures
reach the outer catch block that preserves stuck/needs_input states
- classifyTerminalOutput: check waiting_input prompts against bottom of
buffer before full-buffer active indicators, preventing historical
"Thinking"/"Reading" text from overriding current permission prompts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: detect agent exit via isProcessRunning, remove redundant active checks
- lifecycle-manager: replace dead "exited"/"blocked" branches with
isProcessRunning check when detectActivity returns "idle" — correctly
detects agent process exit inside a still-alive tmux session
- classifyTerminalOutput: remove redundant explicit active-indicator
checks that returned the same "active" as the unconditional default
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: wrap killSession in try-catch so cleanup loop continues on failure
One session's kill failure (e.g. archiveMetadata fs error) no longer
aborts the entire cleanup loop, matching the pattern used by batch-spawn
and review-check.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* test: add comprehensive unit and integration tests for CLI
Unit tests (6 new files, 61 tests):
- session-utils: escapeRegex, matchesPrefix, findProjectForSession
- plugins: getAgent, getAgentByName lookup and error cases
- shell: exec, execSilent, tmux, git, gh, getTmuxSessions, getTmuxActivity
- review-check: GraphQL review checking, dry-run, fix prompt delivery
- open: target resolution (all/project/session), fallback, --new-window
- init: rejects existing config file
Integration tests (2 new files, 8 tests):
- spawn-send-kill: real tmux session create, send-keys, kill, graceful re-kill
- session-ls: multi-session listing, per-session capture, activity timestamps
CLI vitest config updated with explicit thread pool parallelization.
Total CLI tests: 68 → 129. Total integration tests: 20 → 28.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address 5 bugbot findings — symlink type, timeout cleanup, file validation, repo format
- spawn.ts: pass `type` param to symlinkSync based on lstat (dir vs file)
- spawn.ts: document TOCTOU gap in getNextSessionNumber (tmux rejects dupes)
- dashboard.ts: store browser timeout and clear it on child exit
- send.ts: wrap file read in try-catch with user-friendly error
- review-check.ts: validate owner/name split before GraphQL query
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Phase 0 complete. Establishes:
- pnpm workspace with 18 packages (core, cli, web, 15 plugins)
- Complete type definitions in packages/core/src/types.ts defining
all 8 plugin slot interfaces (Runtime, Agent, Workspace, Tracker,
SCM, Notifier, Terminal) + core service interfaces
- YAML config loader with Zod validation and sensible defaults
- Plugin registry with built-in discovery
- CLAUDE.md with conventions for spawned agents
All agents can now branch from main and implement their assigned
packages against the interfaces defined in types.ts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>