Commit Graph

47 Commits

Author SHA1 Message Date
Dhruv Sharma 6d48022c87
feat(cli): wire activity events into CLI commands and supervisor lifecycle (#1698)
* feat(cli): wire activity events into CLI commands and supervisor lifecycle (#1654)

Adds "cli" to ActivityEventSource and emits ~30 activity events across the CLI
surface so `ao events list --source cli` can answer RCA questions like:

- Did AO start cleanly? When? (cli.start_invoked / cli.start_failed)
- Was AO shut down gracefully or did it crash? (cli.shutdown_signal /
  cli.shutdown_completed / cli.shutdown_force_exit / cli.stale_running_pruned)
- Did ao spawn / ao update / ao stop / ao migrate-storage fail and why?
- Did the auto-restore prompt actually restore sessions?

Instrumented files:
- packages/core/src/activity-events.ts (cli source)
- packages/cli/src/lib/shutdown.ts (signal/completed/failed/force_exit/session_kill_failed)
- packages/cli/src/commands/start.ts (start_invoked/start_failed/restore_*/stop_*/daemon_*/last_stop_* /config_migrated)
- packages/cli/src/commands/spawn.ts (spawn_invoked/spawn_failed)
- packages/cli/src/commands/update.ts (update_invoked/update_failed)
- packages/cli/src/commands/setup.ts (setup_failed)
- packages/cli/src/commands/migrate-storage.ts (migration_completed/migration_failed)
- packages/cli/src/commands/project.ts (project_register_failed)
- packages/cli/src/lib/resolve-project.ts (project_resolve_failed/config_recovered/config_recovery_failed)
- packages/cli/src/lib/running-state.ts (lock_timeout/stale_running_pruned)
- packages/cli/src/lib/credential-resolver.ts (credential_load_failed)

All emits are sync, never wrapped in try/catch (recordActivityEvent never
throws), and put raw error text in data.errorMessage (not summary, which is
FTS-indexed and not credential-sanitized).

Tests:
- 16 new instrumentation tests across shutdown, migrate-storage, update,
  resolve-project, and start/stop action paths covering MUST emits.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: correct CLI activity event semantics

* fix(cli): emit migrate-storage invocation event

* fix(cli): record last-stop write failures

* fix(linear): retry transient API failures

* fix(cli): stabilize update instrumentation test

* fix(cli): stub process probes in stop instrumentation tests

* chore(ci): retrigger checks

* Fix CLI failure event review issues

* fix: bound linear integration cleanup

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: whoisasx <adil.business4064@gmail.com>
Co-authored-by: Adil Shaikh <106678504+whoisasx@users.noreply.github.com>
2026-05-18 21:04:25 +05:30
i-trytoohard 9bfd7656bb
fix(cli): refuse to spawn when daemon is not polling the project (#1460)
* fix(cli): refuse to spawn when daemon is not polling the project

`ao spawn` and `ao batch-spawn` used to print a stderr warning and then
create the session anyway when the running AO daemon did not include the
target project in its polling set (or when no daemon was running at all).
The resulting sessions got full worktrees and tmux panes but no
lifecycle reactions — CI-failure routing, review comments, revive
transitions, and the event log were silently dead.

Promote the warning to a hard error so sessions are never created in a
state where the lifecycle manager won't run for them. The error message
tells the user which `ao start` invocation will fix it.

Closes #1455

* test(cli): cover batch-spawn daemon-polling enforcement

`spawn` and `batch-spawn` share the `ensureAOPollingProject` helper, but
only `spawn` had tests for the new fail-fast behavior. Add matching
tests for `batch-spawn` so a future refactor that breaks its guard is
caught.

---------

Co-authored-by: Prateek <karnalprateek@gmail.com>
2026-05-08 18:13:42 +05:30
Adil Shaikh 1981d471ca
fix(core): deliver prompt inline via positional arg, remove post-launch polling (#1583)
Claude Code's positional [prompt] argument keeps it in interactive mode;
only -p/--print triggers headless one-shot exit. The entire post-launch
polling mechanism was built on the wrong assumption.

Changes:
- Claude Code plugin: pass prompt as positional arg in getLaunchCommand
- Core types: remove promptDelivery field from Agent interface
- Session manager: remove post-launch polling/retry block
- Prompt builder: clarify wording ("title, description, and labels"
  instead of "full issue details"), unify # format
- Tracker-github: match prompt wording update
- CLI spawn: remove dead-code promptDelivered warning

Closes #1582
2026-05-08 17:44:10 +05:30
Harshit Singh Bhandari caa7f60a4b
refactor(spawn): plugin-owned preflight + collapse project resolution (#1622)
* feat(core): add PreflightContext + optional preflight() to plugin interfaces

Foundation for PR 2 of the ao spawn refactor: lets plugins own their own
prerequisites instead of the CLI hardcoding 'if runtime === tmux check
tmux' / 'if tracker === github check gh auth' switches.

PreflightContext describes intent (willClaimExistingPR, role) rather
than CLI flag names, so plugins never learn about flags. New flags map
to new intent fields only when a plugin actually needs them.

Adds preflight?(ctx) as an optional method on Runtime, Agent, Workspace,
Tracker, SCM. Backwards-compatible: existing plugins keep working
unchanged. Subsequent commits move checkTmux into runtime-tmux and
checkGhAuth into the github plugins, then update spawn.ts to iterate
selected plugins instead of switching on plugin names.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(plugins): implement preflight() in runtime-tmux + tracker-github + scm-github

Each plugin now owns its own prerequisite checks (tmux binary, gh auth)
behind the optional PluginModule preflight() contract added in the
previous commit. The CLI no longer needs to know which plugin needs
which tool — it just iterates the selected plugins.

- runtime-tmux: checks 'tmux -V' and throws with platform-appropriate
  install hint (brew / apt / dnf / WSL)
- tracker-github: checks 'gh --version' and 'gh auth status'
  unconditionally (tracker is exercised on every spawn that has an
  issueId AND on lifecycle polling for issue closure)
- scm-github: same gh auth checks but only when the spawn will exercise
  PR-write paths — gates on context.intent.willClaimExistingPR

Subsequent commit refactors the CLI to iterate plugins instead of
hardcoded 'if runtime === tmux' switches.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(cli): make ao spawn iterate plugin preflight, collapse project resolution

Three small changes bundled because they all touch spawn.ts:

1. Plugin-iterating preflight: replaces the hardcoded
   'if runtime === tmux check tmux' / 'if tracker === github check gh
   auth' switches in runSpawnPreflight with a 4-line loop that walks the
   selected plugins and calls each one's optional preflight(). Plugin
   internals are no longer leaked into the CLI; new plugins only need to
   declare their own preflight.

2. Project-resolution collapse: the prefix/no-prefix and issue/no-issue
   paths previously had three near-duplicate code blocks each with its
   own try/catch around autoDetectProject. Replaced by one
   resolveProjectAndIssue() helper that uses resolveSpawnTarget's
   fallback parameter — caller wraps in a single try/catch.

3. Micro-deletes: drop the unused 'return session.id' in spawnSession
   (callers already ignore it; the SESSION=<id> stdout line is the
   scriptable contract). Drop checkTmux/checkGhAuth from lib/preflight.ts
   (now in their respective plugins) along with their orphaned tests.

LOC: roughly net-zero. Wins are structural — adding runtime-podman /
tracker-jira / scm-bitbucket no longer requires editing spawn.ts.

Pre-existing start.test.ts 'stop command' failures are unrelated (verified
on upstream/main bare).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* perf(plugins): dedupe gh-auth check across tracker-github + scm-github

Address greptile P2 on PR #1622: when a project has both tracker:
github and scm: github with --claim-pr, both plugin preflights ran
'gh --version' + 'gh auth status' independently — 4 execs where 2
suffice, and two identical error messages on failure.

Add memoizeAsync(key, fn) to core (process-scoped Promise cache) and
have both github plugins share the key 'gh-cli-auth'. Second caller
hits the in-flight (or resolved) promise — zero extra subprocess
overhead, one error on failure.

Caches both successes and rejections: failed checks should never
re-run within a process (cache dies with the CLI, user fixes the
underlying issue and re-invokes).

5 unit tests for memoizeAsync covering: single-fire dedup, value
identity, distinct keys, rejection caching, concurrent in-flight dedup.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(spawn): collect-all preflight + per-plugin tests + key-namespacing docs

Address self-review feedback on PR #1622:

1. **Collect-all preflight** (spawn.ts): runSpawnPreflight previously
   aborted at the first plugin's failure, so a user with multiple broken
   prereqs (tmux missing AND gh logged out) had to fix-and-retry to
   discover the second one. Now collects every plugin's error and
   reports them together ("2 preflight checks failed:\n  1. ...\n
   2. ..."). Single-failure path is unchanged — that error throws as-is
   without the wrapper. Test added: 'collects every plugin's preflight
   failure into one combined error'.

2. **Drop redundant workspace literal fallback** (spawn.ts):
   DefaultPluginsSchema in core/config.ts applies .default("worktree")
   to workspace, same as runtime/agent. The literal '?? "worktree"'
   was asymmetric defensive theater — dropped to match the runtime/agent
   form.

3. **memoizeAsync key-namespacing convention** (process-cache.ts):
   Added a JSDoc section documenting that two callers using the same
   key get shared state (intentional for cross-cutting checks like
   gh-cli-auth, dangerous for plugin-internal caching). Recommends
   namespacing plugin-internal keys as 'plugin-name:thing'.

4. **Per-plugin preflight unit tests**:
   - runtime-tmux: tmux-present resolves; tmux-missing throws with
     platform-specific install hint (verified per-platform branch)
   - tracker-github: happy path, gh-not-installed, gh-not-authenticated
   - scm-github: no-op when willClaimExistingPR=false (zero gh calls),
     full check when true, plus install/auth failure branches

   Process cache cleared in beforeEach so each test starts fresh.
   Required exporting _clearProcessCacheForTests from core/index.ts
   (matches existing _testUtils pattern in gh-trace.ts).

Pre-existing start.test.ts 'stop command' failures unchanged
(verified on bare upstream/main).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(test): collapse duplicate @aoagents/ao-core import in tracker-github test

eslint no-duplicate-imports caught it on CI — combined the value and
type-only imports into one statement.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 14:03:26 +05:30
Ashish Huddar e94ff28106
fix(cli): supervise lifecycle workers for active projects (#1600)
* Refine issue checklist for dynamic lifecycle supervisor

* Harden project supervisor reconcile handling

* fix(cli): surface supervisor startup failures

* fix(cli): allow missing global config on startup
2026-05-01 15:45:06 +05:30
yyovil 83640c8b56
fix(cli): hide legacy second positional from ao spawn help (#1491)
* fix(cli): hide legacy spawn second positional (#1490)

Keep ao spawn help aligned with the real interface by exposing a single optional issue positional and rejecting extra positional arguments with replacement usage before any spawn work starts.

* fix(cli): align spawn usage with optional issue (#1490)

Keep the arity error and its test aligned with the optional [issue] contract surfaced by ao spawn help so review-thread guidance and user-facing usage match exactly.
2026-04-25 02:16:32 +05:30
Harsh Batheja 616c56cea2
fix(cli): derive projectId from prefixed issue id on spawn (#1330)
* fix(cli): derive projectId from prefixed issue id on spawn

When `ao spawn <projectId>/<issue>` is used in a multi-project config,
route the spawn to the prefixed project and strip the prefix from the
issue id. Previously the projectId fell back to whichever project
`ao start` was running for, tagging cross-project sessions with the
wrong project (and session prefix).

Applies to both `ao spawn` and `ao batch-spawn`; batch-spawn errors
out if issues mix multiple project prefixes.

Fixes #1329

* refactor(core,cli): lift spawn target resolution into core

Move the issue-prefix → project routing from the CLI into a reusable
core utility, `resolveSpawnTarget(projects, issueRef, fallback?)`.

- Exposes routing to any spawn entry point (CLI, web API, programmatic).
- Accepts either a project id or sessionPrefix as the prefix; project id
  wins on collision.
- `ao batch-spawn` now groups issues by resolved project and preflights
  once per group instead of erroring on mixed prefixes.

Tests:
- 8 unit tests for `resolveSpawnTarget` in core.
- CLI spawn.test.ts: adds a sessionPrefix routing test (23 tests total).

Refs #1329

* test(cli): cover batch-spawn grouping; tighten resolveSpawnTarget API

Self-review found three gaps:

- `resolveSpawnTarget` accepted `undefined` issueRef and returned
  `{ issueId: "" }` with a fallback project. Dead path — both callers
  guard against undefined. Drop it and make issueRef required.
- No tests for `batch-spawn`. Added two:
  - routes cross-project prefixed issues to the correct project and
    lists each project's sessions separately
  - skips a prefixed issue when the target project already has an
    active session for it
- `spawn` and `batch-spawn` help text didn't document the
  `<projectId>/<issue>` or `<sessionPrefix>/<issue>` forms.

* fix(core): guard resolveSpawnTarget against prototype-key matches

Second review pass found a latent bug:

Plain JS objects inherit `__proto__`, `constructor`, `toString`,
`hasOwnProperty`, etc. from Object.prototype. The previous
`if (projects[prefix])` check entered the routing branch for any of
these keys, mis-routing a user typing `ao spawn __proto__/42` with
`projectId: "__proto__"`. Downstream session-manager would then receive
a junk project object (Object.prototype itself) and fail with a
non-obvious error.

Fix: use `Object.prototype.hasOwnProperty.call(projects, prefix)` so
only actual configured project ids match.

Also:
- Document the case-sensitive matching semantic explicitly.
- Lock in the batch-spawn grouping contract by asserting exact
  `list()` and `spawn()` call counts in the cross-project test.
2026-04-22 22:18:39 +05:30
Ashish Huddar f3ce113c4c
Add multi-project storage, resolution, and project settings support (#1343)
* feat: add content-addressed project storage keys

* Add per-project resolution and hardened project routing

* Fix storage-key test isolation

* feat(web): redesign Add Project modal with Finder-native layout

* feat: multi-project support with project sidebar, settings, and improved routing

Add per-project configuration in global-config, project-aware CLI commands
(start/spawn/open/session), workspace-worktree project resolution, redesigned
ProjectSidebar with settings modal, repair flow for degraded projects, project
detail page with loading state, reload API endpoint, and comprehensive tests.

* Fix legacy config storage keys and duplicate project flow

* Fix multi-project storage migration and collision handling

* Fix merge regressions in startup and config handling

* Externalize yaml and zod from the web server bundle

* Fix session prefix matching for hashed tmux names

* Fix multi-project migration regressions

* Ignore generated worktree files in ESLint

* Fallback reload config for local-only projects

* Speed up session refresh and redirect after kill

* Use fresh session lists for dashboard polling

* fix(web): remove unused direct terminal child state

* test(web): mock router in merge conflict actions coverage

* docs: call out filesystem browse rollout requirement

* Add portfolio tests and remove unused decomposer export
2026-04-21 17:45:55 +05:30
Harsh Batheja 95fbecc379
refactor(cli): remove lifecycle-worker subprocess, poll in-process (#1186)
* refactor(cli): remove lifecycle-worker subprocess model, run polling in-process

Replaces the per-project `ao lifecycle-worker` subprocess with an in-process
polling loop managed inside `lifecycle-service`. All registered projects are
now polled from the single long-lived `ao start` process.

- Drops the `lifecycle-worker` command and its registration.
- Rewrites `lifecycle-service` around a `Map<projectId, ActiveLoop>`,
  with SIGINT/SIGTERM/beforeExit graceful shutdown.
- Removes PID-file coordination (PID file, log file, status, etc.) —
  these only existed to track subprocess state.
- Per-project error isolation is preserved: the core lifecycle manager's
  `pollAll()` already catches per-cycle errors, and stop failures in one
  project can't prevent others from stopping.
- Updates `start`/`spawn` callers and tests to drop the PID/logFile shape.
- Adds `lifecycle-service.test.ts` covering idempotency, unknown projects,
  error isolation across projects, and graceful stop-all.

Closes #1185

* fix(cli): address bugbot review on lifecycle-service in-process refactor

- `ao spawn` / `ao batch-spawn` no longer call `ensureLifecycleWorker`.
  That call used to start `setInterval` polling in the one-shot spawn
  process, which (a) kept the CLI alive forever after the session spawned
  and (b) duplicated polling already running in `ao start`. Replaced with
  a `warnIfAONotRunning()` helper that checks `running.json` and prints a
  hint if the orchestrator isn't up.
- `ao stop` no longer calls `stopLifecycleWorker`. That call always ran
  against a fresh in-memory map (stop is a separate process from start),
  so it always returned false and printed "Lifecycle worker not running"
  misleadingly. SIGTERM to the `ao start` PID already triggers the shared
  shutdown handler in `lifecycle-service`, which stops every loop.
- Drop duplicated shutdown closure inside `registerSignalsOnce` — signal
  handlers now reference `stopAllLifecycleWorkers` directly.
- Update tests accordingly: spawn.test.ts mocks `running-state.getRunning`,
  start.test.ts drops `stopLifecycleWorker` expectations.

* fix(cli): drop SIGINT/SIGTERM listeners from lifecycle-service

Installing listeners for those signals removes Node.js's default
"exit on signal" behavior (per Node docs: "its default behavior will
be removed — Node.js will no longer exit"). Since the registered
listener doesn't call process.exit(), the `ao start` process would
hang on SIGTERM with the setInterval timer keeping the event loop
alive forever — effectively breaking `ao stop`.

Default signal handling terminates the process cleanly; the OS
reclaims the interval timer and dashboard child. `stopAllLifecycleWorkers`
stays exported for callers that want explicit cleanup before exit.

* fix(cli): project-scoped spawn warning + flush lifecycle health on exit

Addresses reviewer feedback on PR #1186:

- `warnIfAONotRunning` now takes a projectId and warns not only when no
  AO is running, but also when the running instance isn't polling the
  target project (e.g. `ao start A` then `ao spawn` in B left users
  silent about the fact that B wasn't being polled).
- `running.json` now records only the project this `ao start` actually
  polls, not every project in config. Previously this list was a lie —
  `ensureLifecycleWorker` is called for the selected project only.
- `ao start` installs SIGINT/SIGTERM handlers that call
  `stopAllLifecycleWorkers()` (flushing per-project "stopped" health
  state) and then `process.exit()`. Installing the handler safely
  requires an explicit exit because SIGINT/SIGTERM listeners remove
  Node's default exit behavior.

* fix(cli): remove dead stopLifecycleWorker, add missing test mock

Addresses bugbot comments on PR #1186:

- Delete `stopLifecycleWorker` from `lifecycle-service.ts`. It was only
  called from `ao stop` in the old subprocess model; in the in-process
  model, SIGTERM to the `ao start` pid + the shutdown handler in
  `start.ts` covers cleanup. No production caller remains.
- Add `stopAllLifecycleWorkers: vi.fn()` to `start.test.ts`'s
  `lifecycle-service.js` mock. Without it, `vi.mock` replaced the module
  and the named import resolved to undefined; the shutdown handler's
  try/catch would silently swallow the resulting TypeError, hiding any
  regression in how shutdown is wired.
- Update `lifecycle-service.test.ts` to drop references to the removed
  export (one test removed, one repurposed as a no-op smoke test for
  `stopAllLifecycleWorkers` against an empty active map).
2026-04-14 17:23:33 +05:30
Dhruv Sharma 663c61e16d fix: merge main and address review findings for prompt-driven spawn
- Merge main to pick up @composio/ao-core → @aoagents/ao-core rename
  and decomposer removal (#1104)
- Fix @composio/ao-core import in prompt-spawn.test.ts → @aoagents/ao-core
- Remove unreachable dead code in CLI spawn (empty-string guard after || undefined)
- Update format.ts JSDoc to document 8-item fallback chain including userPrompt
- Add clarifying comment on validation/sanitization separation in spawn route
- Integrate userPrompt display into redesigned SessionCard footer

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 21:44:57 +05:30
Dhruv Sharma b7464e5657 fix(spawn): persist userPrompt to metadata and prevent injection
writeMetadata() used a hard-coded field whitelist that silently dropped
userPrompt. The in-memory Session.metadata also never included it, so
the spawn response always returned null. Additionally, prompts containing
newlines could inject arbitrary key=value pairs into the flat-file
metadata format.

Fixes:
- Add userPrompt to writeMetadata() whitelist and readMetadata() return
- Populate session.metadata with userPrompt during spawn
- Strip newlines from prompts in both web API and CLI (defense-in-depth)
- Harden serializeMetadata() to replace newlines in all values
- Add prompt length validation (4096 max) in CLI to match web API

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 18:54:48 +05:30
Harsh Batheja 3fb2ddf06d refactor: remove --decompose feature entirely
The --decompose flag and supporting decomposer module had two
unfixable bugs (#1045): it crashed when ANTHROPIC_API_KEY was unset,
and it created multiple branches/PRs per issue, fragmenting history
and complicating review/merge. Removing the feature instead of
patching either bug.

- Delete packages/core/src/decomposer.ts and all re-exports
- Drop @anthropic-ai/sdk dependency from @composio/ao-core
- Remove --decompose / --max-depth options from ao spawn
- Remove decomposer field from ProjectConfig (zod default-strip
  silently ignores existing decomposer: blocks in user yaml)
- Remove lineage / siblings from SessionSpawnConfig and the
  prompt-builder Layer 4 block (only used by decomposer)
- Gut the matching backlog reactor branch in web/services.ts
  so the polling path no longer hits the same bugs
- Remove decompose parameter from openclaw-plugin ao_spawn tool
- Drop decomposer mocks from web services.test.ts
2026-04-10 13:02:52 +05:30
Prateek 967e864f5a chore: rename @composio scope to @aoagents across all packages
Renames all npm package scopes from @composio/* to @aoagents/* and
updates GitHub repo references from ComposioHQ/agent-orchestrator
to aoagents/ao throughout the codebase.

- All package.json names and dependencies
- README badges, links, and install instructions
- Documentation references
- Changeset config
- Source code imports and test files
2026-04-09 15:59:33 +00:00
Dhruv Sharma aa2177698a feat(spawn): support prompt-driven sessions without a tracker issue (#974)
- Add --prompt <text> flag to `ao spawn` CLI
- Accept prompt field in POST /api/spawn web route
- Persist userPrompt to session metadata on spawn
- Add userPrompt to DashboardSession type and serialize.ts mapping
- Show userPrompt in SessionCard footer for prompt-only sessions
- Include userPrompt in SessionDetail headline fallback chain
- Update orchestrator-prompt.ts with prompt-driven spawn examples

Closes #974
2026-04-09 18:43:55 +05:30
adil 2f4968c461 refactor(cli): extract DEFAULT_PORT constant to shared module (#947)
Replace hardcoded magic number 3000 across spawn.ts, session.ts,
open.ts, dashboard.ts, and start.ts with a shared DEFAULT_PORT
constant from lib/constants.ts. Fixes Bugbot review feedback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 03:40:25 +05:30
adil 24ecfc2926 fix(cli): replace all tmux attach output with dashboard URLs (#947)
Replace raw `tmux attach -t` commands in CLI output with web dashboard
URLs (`http://localhost:{port}/sessions/{sessionId}`) across all four
CLI commands: spawn, session restore, open, and start.

Add `stripHashPrefix` helper in session-utils to extract AO session IDs
from hash-prefixed tmux session names. Remove unused `tmuxTarget`
variable from start command.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 03:40:06 +05:30
adil 5322220f6e fix(cli): consolidate spawn output into single message, add dashboard caveat
Address review feedback:
- Remove duplicate created/spawned messages — use single spinner.succeed
- Add "(if running)" qualifier for dashboard mention since ao spawn
  does not start the dashboard itself
- Update test mock to expose spinner for output assertions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-08 03:40:06 +05:30
adil 5ad370e8d1 fix(cli): simplify spawn success message, use ao session attach (#947)
Replace verbose multi-line spawn output (worktree, branch, raw tmux
attach) with a single-line message that directs users to the dashboard
or `ao session attach <id>` instead of exposing internal tmux session
hashes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-08 03:40:06 +05:30
Your Name 9e78fe3b23 fix: resolve prompt delivery persistence and false warnings 2026-04-02 17:41:46 +05:30
Your Name feecc6f177 fix: robust prompt delivery with retries and CLI warnings 2026-04-02 17:27:53 +05:30
ChiragArora31 4d33d25126 fix: detect nested project directories in CLI auto-resolution 2026-04-01 18:28:57 +05:30
suraj-markup 716be0cb74 Fix Bugbot review comments: tilde expansion, duplicate names, cross-platform detect
- Fix autoDetectProject path matching: expand ~ before comparing project
  paths to cwd, so `path: ~/my-repo` matches `/Users/user/my-repo`
- Fix addProjectToConfig: detect duplicate directory names and auto-suffix
  instead of silently overwriting existing project entries
- Fix agent detect() in all 4 plugins: replace `which` (Unix-only) with
  direct `--version` invocation for cross-platform compatibility

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 18:27:01 +05:30
suraj-markup 511d2b7fb9 Resolve remaining PR review comments
- Remove redundant project-existence check after autoDetectProject
- Wrap SIGTERM in try/catch for restart flow (dead process case)
- Remove unused setCallerContext export from caller-context.ts
- Fix unused vi import lint error in init.test.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 15:51:02 +05:30
suraj-markup 030c669c37 Show friendly warning instead of hard error for old two-arg spawn syntax
When users run `ao spawn <project> <issue>`, show a yellow warning
explaining the new syntax (`ao spawn <issue>`) instead of Commander's
raw "too many arguments" error.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 14:32:35 +05:30
suraj-markup 44313f925d Remove two-arg support from ao spawn and batch-spawn
- spawn now takes only `[issue]` — project is always auto-detected
- batch-spawn now takes only `<issues...>` — no project prefix
- Commander rejects extra positional args automatically
- Update orchestrator prompt to remove projectId from spawn example
- Rewrite spawn tests to use auto-detected project (single project in config)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 14:29:14 +05:30
suraj-markup 0b1bd49940 Address PR review comments: unused import, stop orphan, docs accuracy
- Remove unused getCallerType import from start.ts
- Fix ao stop orphaning dashboard: always run stopDashboard via lsof
  after killing parent PID, since SIGTERM may not propagate to child
- Revert spawn single-project special case back to always matching
  project ID (backward compat)
- Update README: replace ao init --interactive and ao add-project
  references with ao start equivalents, update spawn syntax

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 13:44:29 +05:30
suraj-markup 630586f66c Fix medium issues: lockfile, SIGTERM wait, config overwrite, spawn ambiguity
- Add advisory lockfile (O_EXCL) to running-state.ts to prevent TOCTOU
  race when multiple ao start processes run concurrently
- Wait up to 5s for old process to exit after SIGTERM in Override menu,
  escalate to SIGKILL if needed — prevents port conflict on restart
- Guard autoCreateConfig against overwriting existing config files —
  returns existing config instead of silently replacing it
- Fix spawn single-arg disambiguation: in single-project configs, always
  treat the arg as an issue ID (user never needs to specify project)
- Clean up running.json by deleting file instead of writing "null"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 05:57:26 +05:30
suraj-markup f3f81dad84 Simplify onboarding: absorb init + add-project into ao start
Reduces onboarding to `npm install -g @composio/ao && ao start`.

- Absorb init and add-project logic into `ao start` with auto-config
  creation, environment detection, and project type detection
- Add single-instance tracking via running.json with already-running
  interactive menu (human) and info+exit (agent)
- Add caller context detection (human/orchestrator/agent) via TTY and
  AO_CALLER_TYPE env var
- Add plugin-based agent runtime detection — no hardcoded binary paths,
  each plugin exports detect() and displayName
- Simplify `ao spawn` to just `ao spawn <issue>` with auto-detected
  project (backward compat: `ao spawn <project> <issue>` still works)
- Set AO_CALLER_TYPE, AO_PROJECT_ID, AO_CONFIG_PATH, AO_PORT env vars
  on all spawned sessions (worker, orchestrator, restore)
- Add `ao config-help` subcommand for config schema reference
- Deprecate `ao init` to thin wrapper, fully remove `ao add-project`
- Register/unregister in running.json on start/stop

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 01:17:33 +05:30
Harsh Batheja 4edf19df32
feat: lifecycle manager, backlog auto-claim, task decomposition, and verification gate (#365)
* feat: wire lifecycle manager, backlog auto-claim, and dashboard overhaul

- Start LifecycleManager in dashboard server (30s polling) so reactions
  actually fire: CI failures, review comments, merge conflicts are now
  auto-forwarded to agents
- Add backlog auto-claim poller (60s interval) that watches for issues
  labeled `agent:backlog` and auto-spawns agent sessions up to max
  concurrent limit (5)
- Add tabbed dashboard UI: Board (kanban), Backlog (issue queue), PRs
- Add issue creation form in dashboard — creates GitHub issues with
  `agent:backlog` label for immediate agent pickup
- Add API routes: /api/backlog, /api/issues, /api/setup-labels
- Pass notifier config through plugin registry (slack webhook fix)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add task decomposition layer (classify → decompose → recurse)

Adds LLM-driven recursive task decomposition upstream of session spawning.
Complex issues are broken into atomic subtasks before agents start working.
Each agent receives lineage context (where it fits in the hierarchy) and
sibling awareness (what parallel agents are doing).

Core changes:
- New decomposer module (core/src/decomposer.ts) — classify, decompose,
  plan tree, lineage formatting, using Claude API
- Extended SessionSpawnConfig with lineage/siblings fields
- Prompt builder Layer 4: decomposition context (hierarchy + siblings)
- ProjectConfig.decomposer config section with Zod validation
- Tracker plugin: added removeLabels support for label management

CLI:
- `ao spawn <project> <issue> --decompose` flag
- `--max-depth <n>` option for decomposition depth
- Spawns multiple sessions with lineage context for composite tasks

Backlog poller:
- Respects project.decomposer.enabled for auto-decomposition
- Posts plan as issue comment when requireApproval=true
- Auto-spawns subtasks with lineage when requireApproval=false

Config example:
  projects:
    my-app:
      decomposer:
        enabled: true
        maxDepth: 3
        requireApproval: true

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add verification gate — issues stay open until human confirms fix

PR merge no longer auto-closes GitHub issues. Instead:

1. On PR merge: issue labeled `merged-unverified`, stays open
2. Human checks staging, then runs `ao verify <issue>` to close
3. Or `ao verify <issue> --fail` to flag verification failure

Changes:
- services.ts: labelIssuesForVerification() replaces closeIssuesForMergedSessions()
- New CLI command: `ao verify` (verify/fail/list modes)
- New API route: GET/POST /api/verify
- Dashboard: new Verify tab with one-click verify/fail buttons
- ao status: shows count of issues awaiting verification
- Idle session detection + auto-nudge reaction
- Use TERMINAL_STATUSES in batch-spawn dedup check

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: rename decomposerConfig to avoid variable shadowing

Addresses Bugbot medium severity issue where inner  variable
shadowed outer  from getServices().

* fix: update pnpm-lock.yaml for new @anthropic-ai/sdk dependency

* fix: resolve remaining merge conflicts and syntax errors

- Remove leftover conflict markers in types.ts
- Remove orphaned code in services.ts
- Fix semicolon to comma in config.ts
- Remove unused import in verify.ts

* fix: address final Bugbot issues

- requireApproval path now exits early with continue to prevent
  fall-through to in-progress label and session spawned comment
- remove packages/core/package-lock.json (pnpm workspace should only
  use root pnpm-lock.yaml)

* fix: idle sessions now transition back to working

When agent resumes activity after being idle, the status correctly
transitions to 'working' instead of remaining stuck in 'idle' state.

* fix(backlog): remove agent:backlog label when claiming issues

When claiming issues from the backlog, the poller now removes the
agent:backlog label in addition to adding agent:in-progress. This
prevents duplicate work if all spawned sessions reach terminal status
and the poller rediscovers the issue.

* fix(test): use Set for TERMINAL_STATUSES mock

The mock for TERMINAL_STATUSES was an array, but the real export is a
ReadonlySet. Changed to use a Set so tests with non-empty sessions won't
crash when calling .has().

* fix(web): resolve backlog/dashboard regressions after branch sync

* fix(web): align dashboard events hook and SSE test mocks

* fix(notifier-openclaw): apply exponential delay from retry index

* fix(integration-tests): align openclaw retry delay expectation

* fix(web): keep dashboard header stats in sync

* fix(openclaw): keep first retry at base delay

---------

Co-authored-by: Agent <agent@example.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Harsh <harsh@Ubuntu-24-Forrest.lan>
Co-authored-by: Harsh <harsh@example.com>
2026-03-10 12:31:25 +05:30
Harsh Batheja 650d3ad695
fix(core): enforce single-owner PR claim consolidation (#390)
* fix(core): enforce single-owner PR claim consolidation

* refactor: remove dead `takeover` option from claimPR

Since PR consolidation is now automatic (single-owner enforcement),
the `--takeover` flag became dead code. Users passing it got no
error but it had zero effect.

This commit:
- Removes takeover from ClaimPROptions interface
- Removes --takeover flag from spawn and session CLI commands
- Updates orchestrator-prompt.ts examples
- Updates tests to reflect automatic consolidation

Tests: ao-core 403 passing, ao-cli 189 passing (spawn+session)

* fix: remove stale --takeover from Quick Start example

Remove remaining --takeover reference in orchestrator prompt Quick Start section.

* feat(core): document and test asymmetric PR ownership model

- Add JSDoc to claimPR documenting RULE A (exclusive PR->Agent) and
  RULE B (Agent->Many PRs) ownership contract
- Add tests for:
  - Same session claiming multiple PRs sequentially (RULE B)
  - Idempotent re-claim by same owner
  - Stale/dead prior owner handoff
  - Exclusive PR ownership enforcement (RULE A)

139 tests passing

---------

Co-authored-by: Harsh <harsh@Ubuntu-24-Forrest.lan>
2026-03-10 11:54:26 +05:30
Jayesh Sharma 8801502871
feat: add PR claim flow for agent sessions (#326)
* feat: add PR claim flow for agent sessions

* feat: support PR claim during spawn

* fix: address PR review feedback

* feat: add lifecycle worker automation

* fix: prevent duplicate messages on unconfirmed delivery and deduplicate review prompt

sendWithConfirmation now treats unconfirmed delivery as a soft success
since the message was already sent, preventing the dispatch hash from
staying stale and causing duplicate sends on the next poll cycle.

review-check command now sources its prompt from the lifecycle reaction
config instead of hardcoding it, keeping both paths aligned.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: pass AO_CONFIG_PATH to spawned lifecycle worker and log duplicate-worker early exit

The spawned lifecycle worker now receives AO_CONFIG_PATH in its
environment so it finds the correct config regardless of CWD. Also
added a log message when exiting early due to an existing worker.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: prevent lifecycle worker from clearing metadata on SCM fetch failures

SCM methods (getPendingComments, getAutomatedComments) silently returned []
on error, causing maybeDispatchReviewBacklog to treat fetch failures as
"no comments" and clear all tracking metadata every poll cycle. The worker
appeared to do nothing because it kept resetting its own state.

- SCM methods now propagate errors instead of returning []
- maybeDispatchReviewBacklog distinguishes null (fetch failed, skip) from
  [] (confirmed empty, safe to clear)
- pollAll() logs errors instead of silently swallowing them
- Added heartbeat logging and stdout flush before process.exit

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add debug breadcrumbs when review comment fetch fails

Logs a console.debug message when getPendingComments or
getAutomatedComments fails, making it clear the lifecycle loop is
preserving metadata due to a fetch failure rather than genuinely
having no comments.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: scope lifecycle worker polling to its project and add missing test

pollAll() now passes the worker's projectId to sessionManager.list(),
so each per-project lifecycle worker only polls its own sessions. This
prevents duplicate SCM API calls and race conditions in multi-project
configs.

Also fixed misleading test name and added a test verifying that
--no-dashboard alone still starts the lifecycle worker.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove dead confirmation check and respect project-level reaction overrides

Removed the unreachable "could not be confirmed" guard from the retry
logic since sendWithConfirmation now returns silently on unconfirmed
delivery.

review-check now resolves the prompt per-session by checking
project-level reaction overrides before falling back to the global
config, matching lifecycle worker behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: close TOCTOU race in lifecycle worker spawn and unexport getRegistry

Write the child PID from the parent immediately after spawn, closing
the window where a concurrent ensureLifecycleWorker could pass the
"not running" check and spawn a duplicate worker.

Also removed the unnecessary export on getRegistry since it has no
external consumers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: always include ao base prompt on spawn

* fix: clear heartbeat on shutdown and add initial delay to confirmation loop

Clear the heartbeat interval in the shutdown handler to prevent it
firing during the stream-flush window after lifecycle.stop().

Move the sleep in sendWithConfirmation to before each check (including
the first), so the runtime has time to reflect the message before
the first confirmation attempt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve lint errors in lifecycle and session manager

- Replace dynamic delete with object reconstruction in lifecycle-manager
- Add { cause } to re-thrown errors in session-manager for preserve-caught-error rule

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 03:54:19 +05:30
suraj-markup 18dea011e7 fix: address review feedback and add preflight tests
- Consistent error formatting: single spawn now uses err.message like
  batch-spawn, avoiding redundant "Error:" prefix
- checkBuilt distinguishes missing node_modules ("pnpm install") from
  missing dist ("pnpm build") so users get the right guidance
- Add 13 preflight unit tests covering port, build, tmux, and gh checks
- Add 5 spawn integration tests covering runtime-aware tmux check,
  tracker-aware gh check, and error message formatting

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 03:05:00 +05:30
suraj-markup cb071e122d fix: wrap batch-spawn preflight in try-catch
Preflight errors in batch-spawn were unhandled, causing unformatted
rejection output. Now caught with chalk.red formatting and
process.exit(1), matching the single spawn handler.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 02:40:12 +05:30
suraj-markup 96c7ae534a fix: run spawn preflight checks once before batch loop
Extract preflight checks from spawnSession into runSpawnPreflight and
call it once upfront in both registerSpawn and registerBatchSpawn. A
missing prerequisite now fails fast with one clear error instead of
repeating N times across the batch.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 02:01:15 +05:30
suraj-markup c0b998a445 fix: scope pre-flight checks to when they are relevant
- Move port/build checks inside the `--no-dashboard` guard so they only
  run when the dashboard is actually being started
- Only check for tmux when the resolved runtime is "tmux", respecting
  per-project runtime overrides (e.g. "process")

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 20:47:02 +05:30
suraj-markup e40275b53c fix(setup): improve setup.sh with prereq validation and add ao start/spawn pre-flight checks
- Rewrite setup.sh with hard stops for Node<20 and git<2.25, soft warns
  with interactive fix for tmux/gh-auth/claude, corepack-based pnpm
  install, and PATH verification after npm link
- Add pre-flight checks to `ao start`: verify dashboard port is free and
  packages are built before proceeding
- Add pre-flight checks to `ao spawn`: verify tmux is installed and gh
  is authenticated (when using github tracker) before session creation
- Extract shared preflight utilities into packages/cli/src/lib/preflight.ts

Closes #245

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 19:39:29 +05:30
suraj-markup 71ee3a2144 feat(cli): add --agent flag to override agent plugin at spawn time
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>
2026-02-23 23:23:54 +05:30
prateek b75c6b04ea
refactor: delegate CLI commands to core SessionManager (#88)
* 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>
2026-02-18 14:30:17 +05:30
prateek 599710296d
fix: migrate to hash-based project isolation architecture
Complete migration to hash-based directory structure for project isolation. All bugbot issues resolved.
2026-02-18 00:19:55 +05:30
prateek eaea131af9
feat: seamless onboarding with enhanced documentation (#66)
* 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>
2026-02-16 22:22:13 +05:30
prateek dbeb8d9fb2
fix: increase delays in spawn prompt submission to ensure Enter is processed (#62)
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
2026-02-16 20:31:07 +05:30
Prateek a6866458ec fix: unset CLAUDECODE in spawned sessions to prevent nested session errors
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>
2026-02-16 05:51:05 +05:30
prateek 77323cb309
feat: implement ao start command for unified orchestrator startup (#42)
* 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>
2026-02-16 04:58:39 +05:30
prateek 1cd7c519af
feat: validate tracker issues on spawn with fail-fast behavior (#44)
* 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>
2026-02-16 04:45:38 +05:30
prateek 21335db8af
feat: publish to npm under @composio scope (#32)
* 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>
2026-02-15 04:28:57 +05:30
prateek 90111da18d
feat: layered prompt system for agent sessions (#27)
* 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>
2026-02-14 20:07:13 +05:30
prateek 06b5ec3267
feat: implement CLI with all commands (init, status, spawn, session, send, review-check, dashboard, open) (#6)
* 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>
2026-02-14 16:14:27 +05:30