Commit Graph

51 Commits

Author SHA1 Message Date
i-trytoohard 89ad185195
fix(agent-plugins,lifecycle): distinguish indeterminate probe from "not found" + bump ps timeout (closes #1838) (#1839)
* fix(agent-plugins): preserve sessions on indeterminate probes

* fix(core): gate recovery activity on successful process probe

* refactor(core): centralize process probe indeterminate handling

---------

Co-authored-by: i-trytoohard <193449657+i-trytoohard@users.noreply.github.com>
2026-05-14 21:50:39 +05:30
github-actions[bot] ee2f4256f4
chore: version packages (#1812)
* chore: version packages

* ci: nudge — trigger required checks on bot PR

* test(agent-codex): drop self-defeating hardcoded version assertion

Same file as the earlier fix on this branch — changesets/action regenerated from main, bringing the bad test back. This deletion will land on main when this Version PR merges, so future Version PR regenerations won't re-introduce it.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: suraj-markup <sk9261712674@gmail.com>
2026-05-13 03:50:07 +05:30
suraj_markup 7c46dc92a4
feat(release): weekly release train — channels, onboarding, dashboard banner, cron (#1781)
* feat(release): weekly release train — channels, onboarding, dashboard banner, cron

Implements the full release pipeline described in release-process.html
(supersedes #1525, which only had the workflow scaffolding).

A. Release infrastructure — .github/workflows/canary.yml triggers on a cron
   ('30 17 * * 5,6,0,1,2', i.e. 23:00 IST Fri–Tue) plus workflow_dispatch,
   without the stale-SHA guard or the merged-PR-comment step from #1525
   (cron has no merged-PR context). release.yml uses changesets/action.
   .changeset/config.json adds the snapshot template and moves the private
   @aoagents/ao-web to ignore[].

B. Channel awareness (packages/cli/src/lib/update-check.ts) — new
   updateChannel field in the global-config Zod schema (stable | nightly
   | manual; defaults to manual so existing users see no surprise installs).
   fetchLatestVersion now reads dist-tags[channel] from the registry;
   isVersionOutdated compares prerelease segments numerically + lexically
   so SHA-suffixed nightlies sort correctly. maybeShowUpdateNotice and
   scheduleBackgroundRefresh skip entirely on manual.

C. Active-session guard (packages/cli/src/commands/update.ts) — before
   any handle*Update proceeds, sm.list() filters for working/idle/
   needs_input/stuck and refuses with `N session(s) active. Run
   `ao stop` first.` instead of auto-stopping (per the design doc:
   surprise-killing user work is worse than refusing).

D. Soft auto-install + onboarding — handleNpmUpdate skips the confirm
   prompt on stable/nightly. New packages/cli/src/lib/update-channel-
   onboarding.ts prompts once on the first `ao start` after this lands;
   ask-once gate keyed on the absence of updateChannel in the global
   config; dismissal persists `manual`. New `ao config set updateChannel
   <value>` command (also handles installMethod).

E. Dashboard banner — packages/web/src/app/api/version/route.ts reads
   the same cache file the CLI writes (~/.cache/ao/update-check.json,
   XDG-aware) and rejects cache entries from a different channel.
   packages/web/src/app/api/update/route.ts duplicates the active-session
   guard so the dashboard can return a structured 409. New UpdateBanner
   component wired into Dashboard.tsx — Tailwind only, var(--color-*)
   tokens, dismissible per-version via localStorage, deferred fetch so
   it doesn't shift the call order in existing dashboard tests.

F. Bun + Homebrew detection (update-check.ts) — new classifiers for
   ~/.bun/install/global/ (auto-installs `bun add -g @aoagents/ao@<channel>`)
   and /Cellar/ao/ (notice-only — `brew upgrade ao`, never auto-install
   because brew owns the symlinks). New installMethod override field in
   the global config to pin detection when path heuristics fail.

Tests: +155 (B/C/F unit, onboarding ask-once gate, /api/version + /api/update,
UpdateBanner visibility/dismiss/click). pnpm test, pnpm typecheck, pnpm lint
all green for the changes; the same 10 pre-existing test failures observed
on main are still present (all environment-dependent: ~/.cache/ao state, codex
binary install, /private path canonicalization on macOS).

Closes #1525

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): CI failures + Greptile review feedback

CI fixes:
- Web /api/update spawn ENOENT — attach `child.on("error", ...)` so the
  asynchronous spawn-error event from a missing `ao` binary doesn't bubble
  up as an unhandled error and crash vitest. The route already returns 202
  before the error fires; on real installs the user sees "no version change"
  if the install fails.
- start.test.ts pollution — runStartup calls `maybePromptForUpdateChannel`,
  which (with isHumanCaller mocked to true) writes to the real
  ~/.agent-orchestrator/config.yaml on the CI runner via persistUpdateChannel.
  Subsequent tests then load that newly-created (empty-projects) config and
  report "No projects configured" instead of the expected "project not found".
  Fix: stub `update-channel-onboarding.js` in start.test.ts so runStartup
  is a no-op for the channel prompt.

Review feedback:
- (P1) `runtime: "tmux"` hardcoded default in `persistUpdateChannel` and
  `loadOrInit` would lock Windows users into a non-functional tmux config
  when they dismiss the channel prompt. Both now use `getDefaultRuntime()`,
  matching `makeEmptyGlobalConfig` in core's global-config.ts.
- (P2) `hasChosenUpdateChannel` JSDoc inverted — the second "True when"
  bullet actually described the False case. Rewritten with separate
  True/False sections that match the implementation.
- (P2) `isVersionOutdated` was duplicated between the CLI and the dashboard
  /api/version route. Moved to a new shared module
  `packages/core/src/version-compare.ts`, exported from `@aoagents/ao-core`,
  consumed by both CLI (re-exports as `isVersionOutdated`) and the web route
  directly. Added 14 unit tests in core for the canonical implementation.

Defensive: `maybePromptForUpdateChannel` now validates the prompt result via
`UpdateChannelSchema.safeParse` before persisting — never writes `undefined`
or an unrecognized string to disk.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): Windows spawn + dismiss-while-blocked review feedback

- (P1) `ao update` silently never ran on Windows because `spawn("ao", ...)`
  doesn't consult PATHEXT, so npm's `ao.cmd` shim wasn't found and the
  async ENOENT was swallowed by the error handler. Add `shell: isWindows()`
  + `windowsHide: true` per the cross-platform guide.
- (P1) Dismiss button was inert when the banner was in the `blocked` (409)
  or `error` phase — `setDismissedFor` set the localStorage flag but the
  hide condition required `phase === "idle"`, so the banner stayed pinned
  until reload. `handleDismiss` now resets phase to idle (and clears the
  error message) so the existing condition fires. Added a regression test
  covering dismiss from the 409 path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): runNpmInstall on Windows — shell:true so PATHEXT resolves npm.cmd

(P1) The dashboard /api/update spawn got `shell: isWindows()` + `windowsHide:
true` in 9f29131d, but `runNpmInstall` in the CLI's `ao update` command was
still missing the same fix. On Windows, `spawn("npm", ...)` without a shell
wrapper doesn't consult PATHEXT, so npm/pnpm/bun's `*.cmd` shims never
resolve and the install silently ENOENTs.

Mirror the fix into runNpmInstall — it's the single spawn site behind every
non-git, non-homebrew install path (npm-global, pnpm-global, bun-global,
unknown), so this one change covers all four install methods.

Tests:
- Mock `isWindows` from @aoagents/ao-core so the spawn options can be
  inspected per-platform.
- Assert `shell: true, windowsHide: true, stdio: "inherit"` on Windows.
- Assert `shell: false` on macOS / Linux.
- Parametrize over pnpm-global / bun-global to confirm the same options flow
  through every npm-style install command.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): /api/version reads cached.isOutdated for git installs

(P1) The dashboard banner never appeared for git-installed users because
`/api/version` ran `isVersionOutdated(current, "origin/main")`, and
`parseVersion("origin/main")` produces NaN parts that the early-exit guard
catches with `return false`. Git installs cache `latestVersion` as a git
ref (not a semver) and a precomputed `isOutdated` flag from `git fetch +
merge-base`; the CLI special-cases this in `update-check.ts`. Mirror the
same pattern here:

  cached.installMethod === "git"
    ? cached.isOutdated === true
    : isVersionOutdated(current, latest)

Also extend the local CacheData with `installMethod?: string` and
`isOutdated?: boolean` so the new branch type-checks. Kept as `string`
rather than importing the CLI's `InstallMethod` type — the literal "git"
compare is the only thing that matters here, and the web package shouldn't
take a dep on @aoagents/ao-cli.

Two new tests cover the git-install path: one asserts isOutdated=true is
trusted from the cache, the other asserts isOutdated=false (current with
origin) is trusted too.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): must-fix #3+#4 — global-config layout + git-only flag guard

#3 — ensureNoActiveSessions now consults loadGlobalConfig() first as a quick
"any projects registered?" check, then routes through loadConfig(globalPath)
only when the registry actually has projects (loadConfig dispatches to
buildEffectiveConfigFromGlobalConfigPath when given the canonical global path
— see packages/core/src/config.ts). Defends against AO_GLOBAL_CONFIG override
to a non-canonical path. Three new tests cover: registered-projects path
fires the guard correctly; empty registry returns early without building a
SessionManager; missing global file returns early without even reading it.

#4 — Restored the rejection of git-only flags on non-git installs. Users
copy/pasting `ao update --skip-smoke` from older docs would silently no-op
on npm/pnpm/bun installs. Now exits non-zero with:
"--skip-smoke only applies to git installs (current install: npm-global)."
Test it.each across npm/pnpm/bun/homebrew/unknown plus a positive test that
git installs still accept the flag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): #2 should-fix — channel-switch prompt

When a stable user runs `ao config set updateChannel nightly` and then
`ao update`, isVersionOutdated(0.5.0, 0.5.0-nightly-abc) returns false (per
semver, prerelease < stable on equal base). The old code printed "Already
on latest nightly" and exited without installing — confusing, because the
install command we'd run is genuinely a different dist-tag.

Fix: snapshot the previously-cached channel BEFORE forcing a refresh, then
detect a switch via `previousChannel !== activeChannel && !info.isOutdated`.
On switch:
  - Don't take the "already on latest" early-return.
  - Print a yellow "Channel switch detected: was X, now Y." notice.
  - Force a confirm prompt regardless of stable/nightly soft-install,
    defaulting to "no" (channel-switch should be explicit). Manual users
    still see their normal prompt.

Onboarding copy now includes one line about channel switches: "switching
later prompts before installing the other channel's build."

4 new tests: explicit switch fires the prompt + installs on yes; declines
on no; same-channel doesn't fire (back to "Already on latest"); first-ever
update with no previous cache doesn't fire either.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(release-train): polish — drop setTimeout, dedup defaults, share cache, dedup export

#5 — UpdateBanner no longer wraps its mount fetch in setTimeout(0). Production
code shouldn't bend to test mock ordering. Instead, the two brittle Dashboard
tests that relied on `mockImplementationOnce` queue ordering now route by URL
via `mockImplementation`, and the cadence test asserts "no other endpoints
were touched" instead of "no fetch was touched at all". Also added a
deliberate "no interval / re-fetch" comment per #6.

#7 — Promoted core's `makeEmptyGlobalConfig` to the public
`createDefaultGlobalConfig` (kept the internal alias for back-compat). Both
the CLI's `persistUpdateChannel` and `loadOrInit` (in `ao config`) now call
it instead of inlining the same defaults block. Single source of truth.

#8 — New `packages/core/src/update-cache.ts` exports
`getUpdateCheckCachePath`, `readUpdateCheckCacheRaw`, and
`getInstalledAoVersion`. The CLI's `update-check.ts` keeps its richer
install-method/channel/git-rev validation but now delegates path resolution
and version lookup to core. The dashboard's `/api/version` route drops its
duplicated `getCachePath`/`readCache`/`getCurrentVersion` and consumes from
core directly. Cache layout is one file, not two.

#9 — Removed the duplicate `export { isManualOnlyInstall }` from
`update.ts` (also dropped the unused import). The canonical export lives in
`update-check.ts`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(release-train): cosmetic — workflow rename note, design tokens, changeset trim

#1  release.yml: added a comment above `workflows: [CI]` warning that GitHub
    matches by name (not filename) and silently no-ops on mismatch — so a
    rename of ci.yml's `name:` field would mean releases stop triggering.

#10 UpdateBanner: replaced text-[13px] / text-[12px] with text-sm / text-xs
    to match the dashboard's chrome scale.

#6  Banner refresh: noted in the existing useEffect comment that we don't
    re-fetch — re-evaluate if "user kept tab open for days, missed an
    update" becomes a real complaint.

#11 .changeset/release-train.md: dropped @aoagents/ao-web from the version
    bump list. The package is `private: true` and in changeset's ignore[],
    so listing it was cosmetic and would just clutter the eventual release
    notes with a non-published artifact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): illegalcall review — global guard, channel scoping, publishable web

(#1, PRRT_kwDORPZUAc6BHFDf) — `ensureNoActiveSessions` now ALWAYS loads
from the canonical global config, never from project-local. The previous
code preferred `loadConfig()` (local search-upward) when run inside a repo,
which made `sm.list()` enumerate only that project's sessions — active work
in other registered projects would be missed and the install would proceed.
New regression test asserts that a session in `other-project` blocks the
update even when invoked from `this-project`'s cwd. Existing global-config
tests retained.

(#2, PRRT_kwDORPZUAc6BHFOl) + (#4, PRRT_kwDORPZUAc6BHFon) — Reverted the
`private: true` on @aoagents/ao-web. Because @aoagents/ao-cli has a
workspace:* runtime dep on it (for `findWebDir()`/dashboard files), pnpm
rewrites the dep on publish to a literal version — keeping ao-web private
would make `npm install -g @aoagents/ao` fail. Restored ao-web to the
changeset linked group, removed it from `ignore[]`, restored the release-
train changeset entry, added publishConfig + repository metadata.

New `scripts/check-publishable-deps.mjs` walks every package and asserts
that no publishable package has a workspace:* runtime dep on a `private:
true` package. Wired into both release.yml and canary.yml before the
publish step so any future regression is caught at CI rather than at the
user's `npm install`. Verified the script catches the inverse condition.

(#3, PRRT_kwDORPZUAc6BHFaV) — `readCachedUpdateInfo` now treats a missing
`data.channel` as a miss when an explicit channel is provided. Previous
logic only rejected when both data.channel and channel were set AND
differed, so a legacy cache entry (pre-channel-scoping) could keep returning
stale stable state to a user who had since switched to nightly until the
24h TTL expired. Existing fixtures bumped to include `channel` where the
test exercises the checkForUpdate / maybeShowUpdateNotice path; new
regression test exercises the legacy-no-channel case.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): SHA-suffix nightly compare — never miss a banner

(P1, PRRT_kwDORPZUAc6BJLrW) Git SHAs are uniformly-random hex, so the old
`comparePrereleaseSegments` lexical fallback gave the wrong answer ~50% of
the time on snapshot tags. Concretely: user installs `0.5.0-nightly-f00d123`,
CI publishes `0.5.0-nightly-0dead01`, and `'f' < '0'` returns false → banner
never shows.

Fix: when two prerelease segments are both non-numeric and differ, treat the
left side as older (return -1). The cache layer always carries the registry's
CURRENT dist-tag, so any non-numeric mismatch on the same base means the
installed copy is behind by construction. Numeric ordering (`rc.1 < rc.2`)
and numeric-vs-non-numeric (`0.5.0-1 < 0.5.0-alpha`) are unchanged.

Tradeoff: a user who manually installed `0.5.0-beta` while the registry only
publishes `0.5.0-alpha` would see a spurious banner. AO's release pipeline
only emits SHA-suffixed nightly prereleases, so the scenario doesn't occur in
practice — documented in the function's JSDoc.

Updated two misleadingly-named tests ("orders SHA-suffixed nightlies
lexically") that had been asserting the buggy behavior; new tests cover the
specific case from the review (`nightly-f00d123` vs `nightly-0dead01`) and
preserve the numeric-ordering invariant.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(release-train): multi-project active-session proof + changeset note

(#1, PRRT_kwDORPZUAc6BHFDf follow-up) Dhruv asked for proof — not a comment —
that loadConfig(globalPath) actually enumerates across all registered
projects, not just the cwd's. New test in update.test.ts seeds proj-a and
proj-b in the global config, places one active session in each (one
"working", one "needs_input"), and asserts the refusal stderr lists BOTH
session ids AND the total count says "2 sessions active". The test is
specifically named so it shows up in `vitest run -t "Dhruv proof"`.

Verified `pnpm changeset version` locally — @aoagents/ao-web, ao-cli,
and ao all bump to 0.7.0 together via the linked group, confirming the
install-404 class of bug is gone.

Also updated the release-train changeset to drop the stale "moves the
private @aoagents/ao-web to ignore" line — that contradicts the current
state (ao-web is publishable and in the linked group).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): Ashish P1+P2 — dashboard banner now actually installs

P1 — Dashboard banner click was a no-op for npm users.
POST /api/update spawns `ao update` with `stdio: "ignore"`, which makes
`isTTY()` return false in the child. The old handleNpmUpdate hit the
non-TTY branch ("Run: ...") and exited without installing. Banner returned
202 "started"; nothing actually happened.

Fix (Ashish's option c, with an env-var bridge):
- /api/update spawns with `AO_NON_INTERACTIVE_INSTALL=1` on the env.
- handleNpmUpdate computes `interactive = isTTY() && !isApiInvoked()`.
- Restructured so the early-return only fires for non-TTY + non-API
  (piped output): we still print "Run: ..." for that case, matching the
  old contract. API-invoked path now actually runs runNpmInstall, skipping
  the confirm prompt (would hang the detached child forever).

Three new CLI tests:
- AO_NON_INTERACTIVE_INSTALL=1 → spawn invoked even with isTTY=false.
- The piped-output case (no env var, no TTY) still prints "Run: ...".
- Active-session guard still fires in the API-invoked path (defense in
  depth — the route's own guard isn't single point of trust).

P2 — First nightly opt-in stuck on "Already on latest stable".
Repro: user on stable 0.5.0, runs `ao config set updateChannel nightly`,
runs `ao update`. previousChannel was undefined, isOutdated was false
(semver: prerelease < stable on equal base), so the early return fired
and the install never ran.

Fix: new `isFirstChannelOptIn` branch — `previousChannel === undefined
&& info.currentVersion !== info.latestVersion && !info.isOutdated`. Force
the same prompt path the channel-switch case uses (default=no, explicit
consent). Confirmed install path covered by a new test that mirrors the
repro exactly.

The pre-existing "no previous cache → no prompt" test asserted the OLD
buggy behavior; rewritten to assert the canonical case (no prior cache
AND versions match → still "Already on latest", no prompt).

P2 — Dashboard /api/version legacy cache.
Same class as Dhruv #3, this time on the web side. Old code:
  const cacheMatchesChannel = !cache?.channel || cache.channel === channel;
A legacy entry without `channel` would short-circuit `!cache?.channel`
and serve stale latestVersion. Fixed to require `cache.channel === channel`
explicitly. New regression test seeds a no-channel entry and asserts
{ latest: null, isOutdated: false, checkedAt: null }.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(release-train): Dhruv edge-case — running.json is the live source of truth

(PRRT_kwDORPZUAc6BUIUK) The active-session guard previously short-circuited
on empty global config, which missed the case where:

  - User runs `ao start` from a repo with a local agent-orchestrator.yaml
    and no global registration.
  - running.json lists that project as currently being polled.
  - Sessions live on disk under ~/.agent-orchestrator/{hash}-{projectId}/.

In that state, `loadGlobalConfig().projects` is empty so the old early
return fired and `ao update` would proceed while a daemon was actively
supervising the user's in-flight work.

Fix: consult `getRunning()` BEFORE falling back to the global registry.
When running.json reports projects, trust its configPath (could be a local
project yaml OR the canonical global path — `loadConfig` dispatches on
shape) and build the SessionManager from there. The global fallback is now
the no-daemon-running case, where on-disk sessions get reconciled by
SessionManager enrichment.

Three new tests in update.test.ts:
- `refuses when sessions exist in a locally-registered project not in
  global config (Dhruv edge-case)` — seeds running.json with a local-only
  project + working session, asserts refusal + that loadConfig was called
  with running.configPath (NOT the global path).
- `returns true (allows update) when running.json is gone and global is
  empty` — covers the genuinely-safe case.
- `trusts running.json over an inconsistent global config` — when both
  signals exist, the live one (running.json) wins and loadGlobalConfig is
  never consulted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(release-train): shift canary cron 23:00 → 23:30 IST

Schedule moves to 23:30 IST = 18:00 UTC. Cron expression changes from
`30 17 * * 5,6,0,1,2` to `0 18 * * 5,6,0,1,2`. Same DOW window
(Fri,Sat,Sun,Mon,Tue) so the bake window (Wed–Thu) is unaffected.

Files touched (all consistent):
- .github/workflows/canary.yml — cron expression + comment block
- .changeset/release-train.md — schedule string in feature description
- CONTRIBUTING.md — "Testing your changes" callout

Verified `grep -rn '23:00 IST|17:30 UTC|"30 17'` returns zero matches.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 23:11:09 +05:30
Priyanshu Choudhary 0f5ae0b01d
feat(windows): complete Windows support (#1025)
* fix: project builds on Windows

Replace Unix cp -r with Node.js fs.cpSync in CLI build script.
Add webpack snapshot config to prevent Next.js scanning Windows junction points.

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

* feat(core): add cross-platform adapter (platform.ts)

Centralizes all platform-branching logic: shell resolution (pwsh > powershell > cmd),
process tree kill (taskkill on Windows), port-based PID discovery (netstat on Windows),
runtime defaults, and env defaults.

Addresses blockers B05, B06, B07, B08 from Windows compatibility proposal.

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

* feat(core): platform-aware runtime default (tmux on Unix, process on Windows)

B04: Config and docs now reflect platform-specific defaults.

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

* fix(cli): use platform-aware runtime fallback in start command

B01/B02: ensureTmux() is only called when runtime resolves to 'tmux'.
On Windows, runtime defaults to 'process', skipping tmux entirely.

* fix(core): tighten Windows PID port matching

* test(core): add mocked tests for platform.ts to fix diff coverage

Adds platform.mock.test.ts with 25 tests covering Windows-specific
branches (resolveWindowsShell fallbacks, killProcessTree, findPidByPort)
and Unix error-handling/env-var fallback chains that require mocking
node:child_process. Pushes platform.ts diff coverage from 45.9% to ≥80%.

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

* fix(core): fix TypeScript errors in platform.mock.test.ts

Return ChildProcess from execFile mock implementations and use "" instead
of undefined for execFileSync mock return value to satisfy strict types.

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

* fix(windows): cross-platform process management (PR 2/6) (#1028)

Fixes B05 and B06: replaces all Unix-only process management with the
  platform adapter so AO works on Windows with runtime: process.

  - dashboard stop/rebuild uses findPidByPort() (netstat on Windows, lsof on Unix)
  - runtime-process destroy uses killProcessTree() (taskkill /T /F on Windows,
    negative-PID SIGKILL on Unix) with conditional detached flag
  - start.ts restart, ao stop --all, and stop-dashboard paths all switched
    from process.kill() to killProcessTree() so child processes are reaped
  - lifecycle-service stopLifecycleWorker() replaced with killProcessTree()
  - Fixed destroy() hang: exit listener now registered before awaiting kill
    so fast-exiting processes don't fire before the listener attaches

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

* fix(cli): spawn dashboard with detached:true on Unix for process group kill

Dashboard was spawned with detached:false, so killProcessTree's
process.kill(-pid) failed with ESRCH (not the group leader) and fell
back to killing only the listening process, orphaning Next.js workers.

Matches the runtime-process pattern: detached:!isWindows() makes the
dashboard the process group leader on Unix so the negative-PID group
kill in killProcessTree correctly reaps all children. On Windows,
detached:false is preserved — taskkill /T /F handles the tree kill
by PID regardless of process group membership.

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

* fix(cli): forward SIGINT/SIGTERM to dashboard group; restore lifecycle stop semantics

Two Bugbot issues from the detached-dashboard and killProcessTree changes:

1. Dashboard Ctrl+C orphan: with detached:true on Unix, the dashboard is in
   its own process group and does not receive SIGINT from the terminal. Add
   process.once(SIGINT/SIGTERM) handlers that forward the signal via
   killProcessTree so the entire dashboard group is reaped on exit. Handlers
   are cleaned up when the dashboard exits to avoid leaks.

2. stopLifecycleWorker wrong return value: killProcessTree swallows ESRCH,
   so a stale PID entry (process already dead) now returned true ("stopped")
   instead of false ("not running"). Add an isProcessRunning guard before
   the kill to restore the original semantics.

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

* fix(cli): prevent double SIGTERM dispatch when both SIGINT and SIGTERM arrive

The forward handler now self-removes both listeners before calling
killProcessTree, so a second signal cannot invoke it again on an
already-dead PID.

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

* fix(core): respect signal parameter in killProcessTree on Windows

SIGTERM now uses taskkill /T /PID (WM_CLOSE, graceful) instead of /F,
preserving the SIGTERM→wait→SIGKILL escalation used by lifecycle-service,
start.ts, and runtime-process. SIGKILL keeps /T /F /PID (force).

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

* test(core): update killProcessTree Windows tests for signal-aware taskkill

Split the single taskkill test into two: SIGTERM uses /T /PID (graceful)
and SIGKILL uses /T /F /PID (force), matching the updated implementation.

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

* test(core,cli): add missing coverage for platform.ts and lifecycle-service

- platform.mock.test.ts: cover Windows getEnvDefaults PATH fallback (line 148)
- lifecycle-service.test.ts: cover stopLifecycleWorker stale-PID path,
  normal SIGTERM kill, and SIGKILL escalation after timeout

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

* fix(cli): suppress consistent-type-imports lint error in test mock factory

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

* fix(agents): add process-runtime PID check to isProcessRunning (#1031)

B13 (P0): All 4 agent plugins now check PID directly when runtime is
'process' instead of only scanning ps -eo for tmux TTYs. Enables correct
dashboard activity state on Windows.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(windows): platform-aware shell for postCreate, script-runner, symlinks (PR 4/6) (#1032)

fix(windows): platform-aware shell for workspaces and script-runner (B07, B08, B19)

  B07: workspace-worktree and workspace-clone use getShell() instead of sh -c.
  B08: script-runner spawns scripts in file-mode on Unix (so $1/$2/$3 reach
       positional args) and uses getShell() on Windows; AO_BASH_PATH override
       uses || so empty string is treated as unset.
  B19: workspace-worktree symlink falls back to cpSync on Windows.

  Also fixes path separator check in workspace-worktree to use path.sep
  instead of hardcoded "/" for correct Windows behaviour.

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

* fix(test): use mockReturnValueOnce for pwsh shell mock to prevent test pollution

vi.clearAllMocks() clears call history but not mockReturnValue implementations.
The Windows pwsh shell tests were polluting subsequent tests that expected the
default sh mock. Changed to mockReturnValueOnce so the override is consumed
by the single call and subsequent tests get the default sh implementation.

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

* fix(cli): script-runner always uses bash on Unix, getShell() only on Windows

getShell() on Unix returns process.env.SHELL || /bin/sh, which may be zsh,
fish, or plain sh. When a script file is passed as an argument to these
shells (file mode), the #!/bin/bash shebang is ignored and bash-specific
syntax in ao-doctor.sh / ao-update.sh / setup.sh breaks.

Fix: hardcode bash on Unix (AO_BASH_PATH still overrides it), use getShell()
only on Windows where bash is unavailable.

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

* fix(core): use lazy factory for Zod runtime default

z.string().default(getDefaultRuntime()) evaluates getDefaultRuntime() once
at module load time, creating hidden coupling between import order and
platform detection. Using a factory function ensures the default is resolved
lazily each time it is needed, making the intent explicit.

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

* fix(cli): add detached: !isWindows() to dashboard spawn for correct process cleanup

Without detached:true on Unix, killProcessTree(pid) calls process.kill(-pid)
which targets a process group the child never owns — ESRCH causes fallback to
direct kill, leaving grandchild processes alive. Matches the pattern already
used in start.ts lines 782 and 795.

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

* fix(cli): forward SIGINT/SIGTERM to detached dashboard child on Unix

Detached children run in their own process group, so Ctrl+C does not reach
them. Without forwarding, the dashboard holds the port after the parent exits.
Matches the identical pattern in start.ts lines 1154-1165.

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

* fix(core): guard killProcessTree against pid <= 0

On Unix, -0 === 0 in JS, so killProcessTree(0) would call process.kill(0)
which sends the signal to every process in the calling process's group,
killing AO itself. findPidByPort can return "0" since it passes the
truthiness check and the /^\d+$/ regex. Guard pid <= 0 at the top of
killProcessTree and return early.

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

* feat(windows): Node.js metadata wrappers + Claude Code hook + pwsh shell (squash merge PR5)

Squash merges feat/windows-hooks-and-launch (PR #1033) into PR1.

Blockers addressed:
- B16: ~/.ao/bin/gh and git wrappers are now Node.js scripts + .cmd shims on
  Windows (bash on Unix unchanged). WRAPPER_VERSION bumped to 0.3.0 to force
  reinstall.
- B17: Claude Code PostToolUse hook uses JSON.parse/fs built-ins on Windows
  instead of bash+jq+grep+sed. Atomic writes via temp file + renameSync.
  chmod skipped on Windows.
- B18: runtime-process uses getShell().cmd + shellInfo.args() instead of
  shell:true (which resolves to cmd.exe on Windows). getShell() returns
  pwsh > powershell.exe > cmd.exe on Windows, bash on Unix.

Conflict resolution:
- runtime-process spawn: kept PR5's getShell() approach (B18 fix), removed
  shell:true which PR1 had as a placeholder.
- runtime-process destroy: kept PR1's cleaner killProcessTree delegation
  (PR5 had inline platform-branching written before killProcessTree was
  integrated into this worktree).
- Tests: merged PR5's new Windows compatibility tests, adjusted assertions to
  match PR1's killProcessTree(pid, signal) API. Fixed Windows compat tests
  that expected old spawn(launchCommand, opts) signature.

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

* fix(core): deduplicate Node.js wrapper updateAoMetadata and add AO_DATA_DIR path validation

- Extract shared NODE_UPDATE_AO_METADATA constant used by both gh/git wrappers
- Add AO_DATA_DIR validation matching bash ao-metadata-helper.sh (must be under ~/.ao/, ~/.agent-orchestrator/, or tmpdir)
- Bump WRAPPER_VERSION to 0.5.0 to force reinstall with new security check
- Update version in agent-codex and core tests to match 0.5.0
- Fix CI test failures from WRAPPER_VERSION bump (0.2.0 → 0.4.0 → 0.5.0)

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

* test(core): add IPv6 netstat test for findPidByPort + mark _resetShellCache as @internal

- Add test case for IPv6 LISTENING entries ([::]:3000) in Windows netstat output
- Add @internal JSDoc to _resetShellCache to clarify it is test-only

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

* fix(cli): use -File mode on Windows for script-runner so positional args are forwarded

PowerShell -Command does not forward argv elements after the command string to the
script — they are treated as top-level PowerShell args and silently dropped. Using
-File passes remaining args as positional parameters ($1, $2, …) to the script, so
e.g. `ao doctor --fix` correctly reaches the script on Windows.

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

* fix(cli,core): remove unused getEnvDefaults export, add SIGKILL fallback in signal forward handler

- Remove getEnvDefaults from @composio/ao-core public API — no production callers;
  the function remains in platform.ts for future use (B10/B11)
- Add 5 s SIGKILL fallback in dashboard.ts and start.ts forward() handlers so the
  parent process cannot hang indefinitely if the child ignores SIGTERM

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

* refactor(cli): extract forwardSignalsToChild utility, fix ESM build script, reject Windows absolute symlinks

- Extract forwardSignalsToChild(pid, child) into shell.ts — eliminates verbatim
  duplication of the SIGTERM/SIGKILL forwarding logic between dashboard.ts and start.ts
- Fix build script: replace node -e "require(...)" with node --input-type=commonjs -e
  "require(...)" — required because package is "type":"module" and require is not
  available in node -e by default in ESM context
- Fix duplicate import in shell.ts (no-duplicate-imports lint error)
- Reject Windows drive-letter (C:\) and UNC (\server\share) paths in symlink
  validation — previously only Unix absolute paths starting with "/" were blocked

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

* fix(cli): clear SIGKILL fallback timer when child exits cleanly

If the child exits before the 5-second escalation window, the fallback
setTimeout would still fire and call process.exit(1). Track the timer
in the outer scope so the child.once("exit") handler can cancel it.

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

* fix: resolve two open bugbot issues on windows-platform-adapter PR

- fix(platform): always use /bin/sh on Unix instead of \$SHELL so
  postCreate commands and runtime launches work correctly when the
  user's login shell is non-POSIX (fish, nushell, etc.)

- fix(script-runner): detect cmd.exe fallback on Windows and throw a
  clear, actionable error pointing to AO_BASH_PATH rather than passing
  the PowerShell-specific -File flag to cmd.exe (which produces a
  cryptic error and still can't run bash scripts)

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

* fix(cli): gate lifecycle worker detached flag behind !isWindows()

Spawning with detached: true unconditionally creates a new console
window on Windows. Use the same !isWindows() pattern established
elsewhere in this PR so the process group behaviour is correct on
both platforms. killProcessTree already uses taskkill /T on Windows
so cleanup is unaffected.

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

* fix(cli): require AO_BASH_PATH for all Windows shells, not just cmd.exe

pwsh and powershell.exe cannot run bash scripts any more than cmd.exe
can — shebangs are ignored and bash-specific syntax fails. The previous
guard only matched cmd.exe, allowing pwsh (the most common Windows
fallback) to silently invoke -File on a bash script and produce a
confusing PowerShell syntax error.

Simplify to: throw on any Windows shell without AO_BASH_PATH. Also
removes the now-dead getShell() call and -File code path from
script-runner.

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

* fix(core): always force-kill on Windows; fix stale .cjs JSDoc

killProcessTree: drop the SIGTERM-without-/F branch on Windows.
taskkill without /F sends WM_CLOSE which is unreliable for headless
Node.js console processes — they may silently survive, leaving orphaned
processes. Always pass /F so termination is guaranteed. Callers that
do SIGTERM→wait→SIGKILL escalation are unaffected: SIGKILL simply
finds the process already dead.

agent-workspace-hooks: correct JSDoc that still said <name>.js after
the extension was changed to .cjs (forced CJS mode).

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

* refactor(cli): remove trivial findRunningDashboardPid wrapper

The function was a one-line pass-through to findPidByPort with no added
logic. Callers now import findPidByPort from @composio/ao-core directly.
waitForPortFree calls findPidByPort inline. Deleted the test file that
only tested the pass-through.

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

* fix(cli): make forwardSignalsToChild idempotent via WeakSet guard

Prevents duplicate SIGINT/SIGTERM handlers if called more than once for
the same ChildProcess — avoids double killProcessTree and racing
process.exit(1) from stacked SIGKILL fallback timers.

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

* fix(agent-claude-code): three Windows correctness fixes

C-1: Add AO_DATA_DIR allowlist validation to METADATA_UPDATER_SCRIPT_NODE.
     The Node.js PostToolUse hook now validates AO_DATA_DIR against
     ~/.ao/, ~/.agent-orchestrator/, and os.tmpdir() before writing —
     matching the protection already in ao-metadata-helper.sh and the
     Node.js wrappers in agent-workspace-hooks.ts.

I-1: Guard getCachedProcessList() against Windows. ps -eo pid,tty,args
     is Unix-only; the guard makes the intent explicit and avoids a
     spurious execFile call when a stale tmux handle is encountered on
     Windows.

I-2: Read systemPromptFile content synchronously on Windows instead of
     using $(cat ...) bash command substitution, which is not understood
     by PowerShell or cmd.exe.

Tests added for all three fixes.

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

* fix(agents): apply Windows correctness fixes to aider, codex, opencode

Mirrors the fixes already applied to agent-claude-code:

I-1: Guard ps -eo pid,tty,args behind isWindows() in isProcessRunning for
     all three agents. ps is Unix-only; a stale tmux handle on Windows
     would silently return false via exception catch. The explicit guard
     makes intent clear and avoids the unnecessary execFile call.

I-2: Inline systemPromptFile content on Windows instead of $(cat ...)
     bash command substitution (aider: --system-prompt; opencode: prompt
     value). codex is unaffected — it passes the path via -c flag and
     reads the file itself.

Tests: added isWindows mock (default false) to all three test suites to
prevent real isWindows()=true on Windows from triggering the new guard
in existing Unix-path tests. Added Windows-specific tests for each fix.

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

* fix(core): use F_OK and skip bare extension in Windows gh/git wrappers

On Windows, fs.constants.X_OK is equivalent to F_OK (execute bit does
not exist), so any existing file passes the check. The empty extension
was also tried first, meaning a bare file named "gh" would be selected
over gh.exe. Switch to F_OK and only check .exe/.cmd extensions.

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

* fix(windows): QA fixes — dashboard spawn, shellEscape, tmux hint, PID fallback

T04: resolveNextBin() skips POSIX .bin/next shim on Windows; invokes
next/dist/bin/next via process.execPath instead (ENOENT fix).

T18: shellEscape() branches on isWindows() — PowerShell uses '' doubling,
Unix uses POSIX '\'' escaping. All 4 agent plugins benefit automatically.

T06 secondary: tmux attach hint in `ao spawn` output gated behind
runtimeName === "tmux" (process runtime has no tmux session).

T06/T11: runtime-process destroy() and isAlive() fall back to
handle.data.pid when the in-memory processes Map is empty — fixes
cross-process CLI calls (ao session ls / ao session kill).

* fix(web): prevent nft EPERM on Windows home directory junction points

Next.js nft (Node File Tracer) scans homedir() at build time and hits
EPERM on Windows junction points (e.g. Application Data). Adds homedir()/**
to TraceEntryPointsPlugin.traceIgnores on Windows server builds.

* Revert "Merge branch 'main' into feat/windows-platform-adapter"

This reverts commit 5ba7644548, reversing
changes made to 5da9bedf5c.

* Reapply "Merge branch 'main' into feat/windows-platform-adapter"

This reverts commit 6a326a07e3.

* fix(windows): update @composio imports to @aoagents scope

Our Windows-specific files were written before the @composio → @aoagents
rename landed. Update all affected imports across runtime-process,
workspace-clone, workspace-worktree, cli commands, and test files.

* feat(windows): add PTY host for ConPTY terminal sessions

Windows equivalent of the tmux daemon. Per-session detached pty-host.js
process owns a ConPTY (via node-pty), listens on a named pipe
(\.\pipe\ao-pty-{hash}-{sessionId}), and relays terminal I/O to any
connected client.

- runtime-process: spawn pty-host on Windows, route sendMessage/getOutput/
  isAlive/destroy through named pipe protocol
- mux-websocket: named pipe relay for dashboard terminal (skip TerminalManager
  on Windows), resolvePipePath via generateConfigHash (instant, no pipe scan)
- direct-terminal-ws: use real mux server on Windows instead of placeholder
- tmux-utils: findTmux returns null on Windows, resolvePipePath added
- orchestrator-prompt: runtime-agnostic language
- opencode: fix isProcessRunning tmux-before-guard bug (W29)

Addresses blockers W01-W12, W23, W24, W28, W29, W33-W35.
Unix behavior completely unchanged.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(windows): QA fixes — session attach, ao stop, activity detection

- cli/session: add Windows ao session attach via named pipe relay with
  raw stdin mode and Ctrl+\ to detach; skip getTmuxActivity on Windows
- cli/start: fix ao stop looking for "tr-orchestrator" instead of the
  actual numbered session (e.g. tr-orchestrator-5) — also fixes Linux
- agent-claude-code: fix toClaudeProjectPath dropping Windows drive colon
  (C:\→C- not C) breaking JSONL lookup; ignore stale JSONL entries from
  previous sessions in reused worktrees
- pty-client: use \r (carriage return) instead of \n for PTY Enter key

Addresses blockers W13 (partial), W14.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: resolve merge conflicts from main — rename isOrchestratorSession, update stop tests

- session.ts: use isOrchestratorSessionName (renamed in main) for JSON output
- start.test.ts: update stop command tests to use sm.list() instead of sm.get()

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address CI failures and review comments

- session.ts: restore isOrchestratorSession from core (checks both name
  and metadata role) instead of name-only isOrchestratorSessionName
- session.ts: remove unused allSessionPrefixes after merge conflict
- start.test.ts: update stop command tests for sm.list() flow
- toClaudeProjectPath: remove speculative space replacement, keep only
  verified chars (/ : .) — addresses review comment about Unix breakage

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(windows): address review feedback, fix tests, and improve Windows coverage

- Fix CI diff coverage and review feedback
- Fix test reliability for session attach, stop, and Windows attach
- Add coverage for session attach binary protocol and edge cases
- Clean up stdin listener + add resolvePipePath tests
- Address review comments + coverage for pipe relay
- Make 80 failing tests pass on Windows (cross-platform mocks, path assertions)
- Fix production code: execFile shell option for .cmd, isPathInside separator,
  openclaw binary detection via `where` on Windows
- Add platform-aware test assertions for shell escaping, PATH handling, hooks
- Add signal forwarding comment for Windows dashboard process

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(windows): QA fixes — activity timestamps, prompt delivery, pty-host keep-alive

- session.ts/status.ts: use session.lastActivityAt on Windows (no tmux)
- session-manager.ts: stabilize ConPTY output before sending post-launch prompt
  to prevent prompts being swallowed during agent startup splash screen
- pty-client.ts: split message + Enter into two writes (300ms gap) to match
  tmux send-keys behavior; fix isAlive to return true while pipe is connectable
  regardless of whether the agent process inside has exited
- pty-host.ts: keep named pipe server alive after agent exits (mirrors tmux
  session persistence) so clients can still attach and view scrollback

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

* fix(core): Windows-stable storage hash and atomic write retry

storage-key: normalize to POSIX form (strip drive letter, replace backslash
with forward slash) before hashing so identical repos produce identical
hashes across Windows and Unix, and across different Windows working
directories of the same checkout.

atomic-write: retry renameSync up to 10x with 50ms backoff when Windows
returns EPERM/EACCES/EBUSY — antivirus, file indexer, or backup software
briefly hold handles to recently-written files. Cleans up the temp file
on final failure so subsequent retries don't trip "file exists".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(windows): plugin runtime gaps + ConPTY graceful shutdown

runtime-process:
- Reserve the per-instance processes-map slot before the platform split
  so the Windows ConPTY branch participates in duplicate-create detection
  and getMetrics/getAttachInfo bookkeeping. Previously, Windows returned
  a handle without storing it, so duplicate session IDs were silently
  accepted and getMetrics always reported 0 uptime.
- Add 500ms graceful-exit poll before SIGKILLing the pty-host on destroy
  so node-pty can dispose its ConPTY handle. Skipping this orphaned the
  conpty_console_list_agent helper and triggered Windows Error Reporting
  dialogs (0x800700e8) on real runs, not just tests.
- pty-host: install SIGTERM/SIGINT/SIGHUP/SIGBREAK/beforeExit handlers
  that drive the same shutdown sequence (kill pty, drop clients, close
  pipe, exit after 50ms grace), and route MSG_KILL_REQ through the same
  path. Previously MSG_KILL_REQ only called pty.kill() and left the host
  process lingering.
- Add windowsHide:true to the pty-host child spawn so node-pty's helper
  console window stays hidden on errors.

workspace-worktree: normalize paths to a comparable POSIX form
(backslash→slash, lowercase drive letter) when matching git worktree
list --porcelain output against project directories. git emits
forward-slash paths on Windows; path.join produces native backslashes
— the comparison failed and list() returned empty.

agent-opencode: guard tmux/ps usage with isWindows() in isProcessRunning
so process-runtime sessions on Windows take the PID-signal path instead
of attempting Unix-only commands.

cli/start: detect Windows local paths in isLocalPath (drive letter
prefix, UNC path, .\, ..\) so spawn arguments like C:\... aren't
mistaken for project names.

integration test: replace cat + /tmp with platform-native echo (findstr
"x*" on Windows, cat on Unix) and os.tmpdir(); the original used
Unix-only tooling and would never run on Windows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(windows): isolate USERPROFILE per test, normalize path assertions

Before this, vitest worker isolation only overrode HOME, but on Windows
os.homedir() reads USERPROFILE. Tests that wrote to ~/.agent-orchestrator
ended up sharing the real user's data directory across workers, leading
to flaky cross-test pollution.

- test-utils: createTestEnvironment / setupTestContext now override both
  HOME and USERPROFILE to the per-test fake home, restore both on
  teardown. rmSync uses maxRetries:5/retryDelay:50 to ride out the same
  Windows file-lock window that atomic-write retries cover.
- core test files (global-config, plugin-integration, portfolio-*,
  project-resolver, recovery-actions, orchestrator-prompt*): set fake
  USERPROFILE alongside HOME and use the retry-aware rmSync.
- update-check.test: normalize path separators in assertions
  (path.replace(/\/g, "/")) so script-path matching works on Windows
  without forcing the production code to emit posix paths.
- orchestrator-prompt.dist.test: pass shell:true on Windows to execFileSync
  for .cmd targets, working around Node CVE-2024-27980's hardening.

Removed lifecycle-service.test.ts — it covered stopLifecycleWorker, which
was deleted when lifecycle was moved in-process during the merge with
main. The remaining lifecycle paths are exercised by lifecycle-manager
tests in core.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(core): restore must rewrite statePayload.runtime.handle, not just top-level

Restore was writing the freshly-spawned runtime handle to the top-level
metadata `runtimeHandle` key, but the canonical lifecycle parser prefers
`statePayload.runtime.handle` and falls back to the top-level only when
statePayload is missing. The next lifecycle tick read the stale handle
from statePayload and rewrote both keys from it, silently undoing the
restore's update.

Symptom: a session restored after AO restart kept the old PID in
metadata. Lifecycle probe found that PID dead (it was from a previous
boot) and the dashboard rendered the orchestrator as exited/killed even
though a new process was actually running.

Fix: rebuild the canonical lifecycle with the new handle via
buildUpdatedLifecycle() and persist via lifecycleMetadataUpdates() so
statePayload and runtimeHandle stay in sync. Mirrors the pattern used
in kill/spawn paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(cli): mock exec for ps verification in stop test

killDashboardOnPort runs a unix-only `ps` cmdline check before killing.
Without mocking exec, the call rejects and the catch returns false, so
killProcessTree is never called and the assertion fails on Linux CI.

* fix(windows): suppress console flashes, register process runtime, auto-detect Git Bash, chunk PTY input

- platform.ts: add windowsHide:true to pwsh/powershell/taskkill/netstat
  spawns so AO no longer flashes a console window for each subprocess.
- script-runner.ts: auto-detect Git Bash at the common install paths on
  Windows when AO_BASH_PATH is unset; tighter error if neither auto-detect
  nor override succeeds. WSL bash intentionally excluded — invoking it
  from Windows-native Node mixes Linux paths with Windows cwd and
  silently breaks repo scripts. Also adds windowsHide:true to the spawn.
- web/services.ts: register @aoagents/ao-plugin-runtime-process so the
  dashboard can spawn sessions on projects using runtime: process
  (the Windows default per getDefaultRuntime).
- pty-client.ts: chunk ptyHostSendMessage into 512-char frames with a
  15ms gap so large prompts (~3-4KB+) are no longer truncated by
  ConPTY's input buffer. Cross-platform safe; Unix PTYs absorb chunks
  at full speed. Trailing Enter still sent as a separate frame after
  the existing 300ms pause.
- Mock test helpers updated to handle the (cmd, args, options, callback)
  arity introduced by passing windowsHide; new test covers Git Bash
  auto-detection.

* fix(windows): add windowsHide to remaining subprocess spawns

Sweeps the spawn sites missed by the first pass — `ao stop`, session
list, opencode introspection, tmux helpers, and worktree git/postCreate
all bypassed the previous fix and still flashed conhost on Windows.

- cli/lib/shell.ts: exec helper (used by git/gh/tmux wrappers)
- core/session-manager.ts: EXEC_SHELL_OPTION + standalone tmux call
- core/tmux.ts: tmux execFile helper
- plugins/workspace-worktree: git wrapper + rev-parse + postCreate shell
- workspace-worktree tests: assertions updated for the new options shape

* fix(codex): make agent-codex work on Windows

Three Windows-specific gaps that combined to make every Codex spawn fail
on PowerShell with "Unexpected token '-c' in expression or statement":

- formatLaunchCommand(): prepend `& ` to the joined launch string when
  running on Windows. shellEscape quotes the resolved binary path
  ('C:\Users\...\codex.cmd'), and PowerShell parses a leading quoted
  string as an expression — without the call operator the next flag
  triggers a parser error before codex is ever invoked. bash treats
  the same string as a normal command, so the prefix is Windows-only.
  Applied at both getLaunchCommand and getRestoreCommand exits.

- resolveCodexBinary(): add a Windows branch using `where.exe` instead
  of `which`. Prefers codex.cmd (npm shim) over codex.exe (Cargo build),
  then falls back to %APPDATA%\npm\codex.{cmd,exe} and ~\.cargo\bin
  for users whose PATH doesn't yet include the install dir. Lookup runs
  with windowsHide:true so the search itself doesn't flash a console.

- sessionFileMatchesCwd(): compare paths via a canonical form
  (forward slashes, lowercased drive letter) so Codex JSONL rollout
  files can still be located when payload.cwd uses a different slash
  direction or drive-letter case than the workspace path AO computes
  via path.join. Without this, dashboard activity/cost stay empty
  for Codex sessions on Windows.

* fix(windows): resolve gh.exe via PATHEXT and fix path-shape test regexes

resolveGhBinary() searched PATH for a literal "gh" file and threw on
Windows where the binary is gh.exe (or gh.cmd for npm shims). All gh
calls in tracker-github and scm-github failed before reaching execFile,
which made spawn() fall back from tracker-derived branch names and made
cleanup() skip the gh-driven kill paths entirely.

Honor PATHEXT on win32 so the resolver matches gh.exe/.cmd/.bat. Update
the four affected integration assertions to accept Windows path shapes.
Also bump the runtime-process sendMessage sleep on Windows — ConPTY
pipe round-trip needs more headroom than the Unix direct-stdin path.

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

* fix(windows): junctions/hardlinks for symlinks, WinRT toast notifier, DPI re-fit

workspace-worktree: when symlinkSync EPERMs on Windows (no admin /
Developer Mode), try a junction for directories and a hardlink for
files before falling back to recursive cpSync. The previous fallback
copied node_modules into every worktree — slow and bloated.

notifier-desktop: add a win32 branch using PowerShell + WinRT toast XML
(no third-party deps). The script is base64-encoded as -EncodedCommand
to sidestep PowerShell argument tokenization. Toast failures log a
warning instead of rejecting so a stripped-down SKU or disabled
notifications can't crash the lifecycle.

DirectTerminal: re-fit on devicePixelRatio changes via matchMedia.
ResizeObserver doesn't fire when only DPR changes (e.g. dragging the
window between monitors at different scales on Windows), leaving an
unrendered stripe to the right of the last column until manual resize.

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

* fix(test): update notifier-desktop integration test for Windows toast support

I missed this duplicate test in the integration-tests package when I
added the Windows branch to notifier-desktop. The mock callback used the
3-arg execFile signature (cmd, args, cb) but the new win32 path calls
execFile with 4 args (cmd, args, opts, cb), so the callback landed in
the opts slot and "cb is not a function" broke CI on Linux.

Make the mock signature-agnostic and replace the win32 "no execFile,
warns" assertion with one that verifies the EncodedCommand toast script.
Add a separate freebsd case for the actual unsupported-platform path.

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

* docs: consolidate six Windows port plans into one closeout

All 11 punch-list tasks shipped (junctions, WinRT toast, DPR re-fit
landed last) plus the foundational PTY-host / runtime-process work.
Stop fix is the only deferred item, waiting on upstream PR #1496.

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

* fix(agents): use shell:true on Windows in detect() to honor PATHEXT

execFileSync with a bare command name on Windows does not consult
PATHEXT — it only finds literal .exe files. CLIs installed via
npm install -g land at %APPDATA%\npm\<name>.cmd, which detect() can't
see, so AO reports the agent as not installed.

Add shell: isWindows() so cmd.exe handles PATHEXT and finds .cmd shims.
Adds windowsHide: true while we're there to suppress conhost flashes.

Affects all 5 agent plugins: aider, claude-code, codex, cursor, opencode.
Reproduced with codex installed via npm on a Windows EC2 box where
where.exe codex resolved to codex.cmd but detect() returned false.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(windows): probe absolute powershell path so PATH-degraded children don't fall through to cmd.exe

The dashboard (Next.js) sometimes spawns the runtime-process pty-host with a PATH that
lacks C:\Windows\System32. Both `pwsh` and `powershell.exe` probes in
resolveWindowsShell() then fail and we drop to cmd.exe — which can't execute the
PowerShell-syntax launch commands agents emit (e.g. Codex's `& 'codex' ...`),
producing `'&' was unexpected at this time.` and an immediately-exited orchestrator.

Probe %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe directly via
existsSync — this path is guaranteed on Windows 10+ and doesn't depend on PATH.
Also add an AO_SHELL env override as an explicit escape hatch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: restore orchestrator session with its systemPromptFile

When restoring an orchestrator session whose agent has no resumable thread for
the worktree (e.g. Codex when the rollout file's cwd doesn't match), restore()
falls back to getLaunchCommand(agentLaunchConfig). The fallback's
agentLaunchConfig was missing systemPromptFile, so Codex booted as a bare TUI
with no orchestrator instructions — the dashboard terminal showed the default
"Write tests for @filename" prompt instead of the orchestrator running.

spawnOrchestrator writes the prompt to {baseDir}/orchestrator-prompt-{sessionId}.md
and threads it through agentLaunchConfig.systemPromptFile (session-manager.ts:1687).
Re-attach the same file on restore when the role is orchestrator and the file
still exists on disk.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(test): assert negative pid in start full-stop test

killProcessTree on Unix targets the process group first via
process.kill(-pid, signal); only falls back to positive pid if that
throws. The test mock returns true, so only the negative-pid call
ever fires. Update assertion to match the actual call.

Caught by CI on Linux (test was Windows-skipped locally).

* fix(test): assert on killProcessTree mock, not process.kill

killProcessTree is module-mocked at the top of start.test.ts, so
process.kill is never invoked by the stop command — the spy
assertion would always see 0 calls on Linux CI. Assert on the
mock directly. Mock is platform-agnostic, so the skipIf is gone.

* fix(windows): node wrapper updateAoMetadata supports V2 .json metadata format

The Windows Node.js gh/git wrappers in NODE_UPDATE_AO_METADATA only tried
the bare session path (e.g. ao-154), but V2 storage uses ao-154.json files.
This caused silent metadata update failures on Windows — PR URLs written by
agents via `gh pr create` were never recorded in session metadata.

Fix mirrors bash ao-metadata-helper.sh: try .json first (V2), fall back to
bare name (V1/legacy). Also adds JSON.parse/stringify handling for V2 JSON
format instead of the key=value line-splitting that only worked for V1.

Bump WRAPPER_VERSION 0.6.0 → 0.7.0 to force reinstall on existing setups.

* chore: remove accidentally committed package-lock.json files

* feat(windows): pty-host registry + sweep on stop and project delete

Windows pty-hosts spawn detached so they survive parent exit (mirroring tmux
on Unix). That same detachment means taskkill /T cannot reach them on
graceful shutdown — they live in their own console group, outside the
parent's process tree. Per-session metadata can't be the source of truth
either: rm -rf'd worktrees, mid-write crashes, or manual recovery sever
AO's only handle to the host PIDs and orphan them silently.

This adds a sideband registry at ~/.agent-orchestrator/windows-pty-hosts.json
that AO writes on spawn (runtime-process) and reads on shutdown (cli/start.ts
sweepWindowsPtyHosts) and project delete (web/.../route.ts via
stopStaleWindowsPtyHosts). Reads auto-prune entries whose PID is gone, so
the registry is self-healing across crashes.

Sweep is graceful-first: each entry gets ptyHostKill via its named pipe,
500 ms grace probe, then killProcessTree as the hard fallback. The result
("swept N pty-host(s): G graceful, F force-killed") goes to the ao stop
log so users can see cleanup happened.

Verified live: spawn registers, destroy unregisters, ao stop --all sweeps,
PID 0 entries auto-prune on next read.

* fix(windows): retry worktree rmSync on file-handle drain race

After ao kills a runtime, the just-exited pty-host's child processes
(conpty_console_list_agent.exe, the agent's spawned shell, .git/index.lock)
still hold open handles inside the worktree for ~30 s–2 min while Windows
drains them. rmSync(force: true) deletes individual files but the parent
rmdir blocks with EBUSY/ENOTEMPTY/EPERM, leaving an empty orphan directory
under ~/.agent-orchestrator/projects/*/worktrees/.

destroy()'s catch-block fallback now calls removeDirWithRetry, which on
Windows retries with backoff [0, 100, 250, 500, 1000, 2000] ms checking
existsSync between attempts, and throws a descriptive error if the
directory survives all six. Non-Windows behaviour is unchanged (single
rmSync).

The thrown error escapes to session-manager.ts:kill which already swallows
it, so callers see no behaviour change today — but observability layers
can hook in later to surface real failures instead of silent orphans.

Addresses the Windows subset of #1562 (the cross-platform stale
.git/worktrees/<id>/ registration is still tracked there separately).

* fix(windows): code-review hardening — shell args, runtime default, sessionId, V2 pipe path

Four small fixes flagged in review of the Windows port:

- core/platform.ts: AO_SHELL override now infers args flag from the shell
  basename (cmd → /c, bash/sh/zsh → -c, anything else → -Command). Previously
  every override got PowerShell args, so AO_SHELL=cmd or AO_SHELL=bash
  silently broke run-command flows.

- core/global-config.ts: defaults.runtime now resolves to getDefaultRuntime()
  (process on Windows, tmux elsewhere) instead of the hardcoded "tmux".
  First-run on Windows no longer writes a config that immediately fails
  runtime resolution.

- web/server/mux-websocket.ts: validateSessionId now runs on the Windows
  named-pipe relay path. The Unix branch validates inside TerminalManager;
  the Windows path bypassed it entirely, so an unsanitised id became both
  a map key and was interpolated into a pipe path downstream.

- web/server/tmux-utils.ts: resolvePipePath now reads the V2 JSON layout
  (~/.agent-orchestrator/projects/{projectId}/sessions/{id}.json) first,
  then falls back to V1 line-delimited metadata for users who haven't run
  ao migrate-storage. The single-source-of-truth note is still accurate;
  the search just covers both layouts during the migration window.

Each change has a paired unit test.

* chore: drop superseded windows-port-closeout plan

* fix(core): lazy-resolve homedir() in windows-pty-registry

REGISTRY_FILE was computed at module load via homedir(), which fired
before vitest mock factories for `node:os` could install. Tests that
mock node:os (notifier-desktop, terminal-iterm2, agent-claude-code
activity-detection) hit either a TDZ error or "homedir not defined on
mock" because the mock isn't bound at evaluation time.

Resolve the path lazily inside readRaw/writeRaw so each call honours
the current mock. Also rename the test helper export from a const to
a function (__getWindowsPtyRegistryFile) so tests can read the
post-mock value.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cli): exit 0 when SIGKILL fallback fires on slow Ctrl+C

forwardSignalsToChild's 5 s fallback called process.exit(1) after
SIGKILL, which marks user-initiated Ctrl+C as an error whenever the
child is merely slow to drain (Next.js connection draining is the
common case). Shell scripts and CI pipelines that check the AO exit
code break.

Use exit 0 — graceful user shutdown is not a failure even if the
child needed force-killing. Reported by greptile review on PR #1025.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(core): drop synchronous shell probes that block event loop

resolveWindowsShell ran execFileSync("pwsh", ["-Version"], { timeout: 5000 })
on every cold start. On the common case (Windows 10/11 with no pwsh
installed) the call blocks the Node event loop for the full 5 s timeout,
stalling AO startup, runtime spawns, and postCreate hooks.

Walk PATH ourselves via existsSync — the lookup is microseconds and
needs no subprocess. Cascade unchanged: AO_SHELL → pwsh on PATH →
absolute powershell.exe → powershell on PATH → cmd.exe.

Reported by greptile review on PR #1025.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(runtime-process): treat EPERM as alive in pty-host destroy probe

destroy()'s 500 ms graceful-shutdown loop probes the pty-host with
process.kill(pid, 0) and treats any throw as "process gone, clean
exit". On Windows, cross-context processes can return EPERM — the
process is alive but we lack permission to signal it. Returning
early in that case orphans the pty-host and skips killProcessTree.

Detect EPERM and break out of the wait loop so the orphan falls
through to killProcessTree. Other error codes (ESRCH etc.) still
mean the process is gone.

Reported by Copilot review on PR #1025.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cli): discover Git Bash via PATH walk for non-default installs

WINDOWS_BASH_CANDIDATES only checks C:\Program Files{,(x86)}\Git, so
users who installed Git for Windows on a different drive (e.g.
D:\Program Files\Git\) hit "Cannot run repo scripts on Windows
without bash" even though Git Bash is available. AO_BASH_PATH is the
documented escape hatch but should not be required.

Add a PATH-walk fallback that finds bash.exe wherever Git's bin dir
sits — Git for Windows adds itself to PATH at install time, so this
covers the typical non-default-drive case without a subprocess or
registry lookup.

Reported by greptile review on PR #1025.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(core): hard-code Windows path separators in findOnPath

Using path.delimiter / path.join in the PATH walker meant Linux CI
ran the test with `:` as the splitter and `/` as the joiner. The unit
test simulates Windows by setting PATH="C:\fake\bin" — on Linux
that splits to ["C", "\fake\bin"] and produces "C/powershell.EXE",
neither of which match the mocked existsSync.

findOnPath is only ever called from resolveWindowsShell, so use `;`
and `\` unconditionally. The runtime data — process.env values,
mocked existsSync — is what's being tested, not host-OS path logic.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(windows): PowerShell repo-script runner + ao-doctor/ao-update.ps1

runRepoScript on Windows now prefers a .ps1 sibling of the requested .sh
script and runs it via pwsh.exe (or bundled powershell.exe as fallback).
Adds ao-doctor.ps1 and ao-update.ps1 as Windows equivalents of the
existing bash scripts.

* test(cli): add missing mockExecSilent hoist in dashboard.test.ts

The findRunningDashboardPidsForWebDir tests reference mockExecSilent
but it was never declared in vi.hoisted, so they crashed with
ReferenceError before any assertion ran. Add the missing hoist and
wire execSilent into the shell.js mock.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(windows): echo projectId in pipe relay messages so MuxProvider routes correctly

MuxProvider keys subscribers under `${projectId}:${id}` when projectId is
provided. The Windows pipe relay was dropping projectId from outbound
messages, so the client routed by id alone and the subscriber bucket
mismatched — leaving the xterm pane blank on
/projects/[id]/sessions/[id].

Echo projectId on every outbound terminal frame (opened/data/exited/error)
so the Windows path matches the Unix tmux relay's behavior.

* test(core): respect TMPDIR in platform defaults test

* fix(runtime): harden dashboard launch shutdown

* fix(windows): scope pipe maps and resolvePipePath by projectId

The Windows pipe relay was project-scoped only on outbound WS frames.
Server-side storage and pipe-path resolution still keyed by bare session
id, so two projects sharing a session id on the same mux connection
would collide on the same socket/buffer entry, and resolvePipePath
returned the first matching project's metadata regardless of caller
intent. Brings the Windows path in line with the Unix subscriptionKey
contract.

- resolvePipePath(sessionId, projectId?, fs?) reads only the caller's
  project metadata when projectId is provided; legacy callers keep the
  walk-all-projects fallback.
- winPipes / winPipeBuffers keyed by \${projectId}:\${id}.
- projectId threaded through handleWindowsPipeMessage data/resize/close
  cast sites.
- Tests cover the project-collision case in both mux-websocket and
  tmux-utils.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(windows): clear 10 Windows test failures

Real fix:
- events-db: add closeDb() to release the better-sqlite3 file lock on
  activity-events.db. Without it, Windows callers cannot rmSync the AO
  base dir while the connection is open. Test teardowns in
  test-utils.ts and plugin-integration.test.ts now call closeDb()
  before rm to fix 4 EBUSY failures.

Test-only:
- tmux-utils.test.ts: normalize backslashes to forward slashes in two
  resolveTmuxSession 'hash-prefix' tests; matches the pattern already
  used by sibling tests in the same file.
- dashboard.test.ts, script-runner.test.ts, update-script.test.ts:
  add it.skipIf(process.platform === 'win32') to four tests that
  assert Unix-specific behavior (lsof cwd matching, posix script
  paths, ao-update.sh smoke). Each file already uses the same skip
  pattern for sibling tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(cli): port-scan fallback + Windows PowerShell branch coverage

start.test.ts: re-add the orphaned-dashboard port-scan test that was
lost during the merge from main (commit 4958512d). When the dashboard
auto-reassigns to port+N because the configured port was busy, ao stop
must walk port+1..port+MAX_PORT_SCAN to find it. Skipped on Windows
because killDashboardOnPort skips the ps cmdline verification there.

script-runner.test.ts: add coverage for the Windows PowerShell branch
in runRepoScript. Two Windows-only tests assert (1) ao-doctor.sh is
rewritten to ao-doctor.ps1 and dispatched via pwsh.exe / powershell.exe
with -NoProfile -NonInteractive -ExecutionPolicy Bypass -File and
forwarded user args, and (2) the rewrite is .sh-suffix-driven, not
blind, so a non-.sh script does not get a .ps1 lookup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(agent-kimicode): make plugin Windows-compatible

Seven blocking issues prevented kimicode from working on Windows. None
were guarded by isWindows checks because the plugin was authored
without importing it. Symptoms ranged from silent agent launch
failures to misclassified process state to total session-discovery
breakage.

1. getLaunchCommand emitted bare command strings ("kimi --work-dir
   ...") which PowerShell parses as a quoted expression rather than
   executing. Wrap with formatLaunchCommand() so Windows gets the
   "& " call operator, matching agent-codex.

2. isProcessRunning called ps -eo on the tmux branch with no platform
   guard. ps does not exist on Windows, so a stale tmux handle would
   throw and misclassify a live agent as exited. Added the same
   isWindows() return-false guard agent-codex uses.

3. resolveWorkspacePath called realpath() unconditionally. On Windows,
   Node's realpath silently canonicalizes non-existent paths instead
   of throwing ENOENT — turning "/workspace/test" into
   "D:\workspace\test" and diverging the session-discovery hash from
   any caller that hashed the raw input. Stat first so the catch path
   is reached uniformly across platforms.

4. isInsideKimiSessions hardcoded "/" as the path separator in the
   sandbox check. realpath returns native paths (backslashes on
   Windows) so candReal.startsWith(rootReal + "/") never matched —
   every candidate was rejected and findKimiSessionMatch returned
   null forever. Use path.sep.

5. getEnvironment set PATH and GH_PATH locally with hardcoded POSIX
   values. session-manager already injects both for every agent
   plugin, so the local writes were dead code that masked the
   Windows-aware central logic. Drop them; mirror agent-codex.

6. getLaunchCommand passed config.systemPromptFile via --agent-file,
   but kimi expects --agent-file to be a YAML agent spec, not arbitrary
   markdown. AO writes the orchestrator prompt as a plain .md file, so
   kimi exited with 'Invalid YAML in agent spec file: expected
   <document start>, but found <block sequence start>' on the first
   bullet. Read the file synchronously and inline its contents into
   --prompt instead, concatenating with any existing config.prompt.

7. session-manager listed kimicode in requiresNativeRestore, so when
   getRestoreCommand returned null (because the previous launch failed
   before kimi wrote any session data), AO threw
   SessionNotRestorableError instead of falling back to a fresh
   getLaunchCommand. Removed kimicode from the allowlist; falling back
   is the only sensible behavior when there is no session on disk to
   resume.

Tests: switched the per-suite workspace constant to a per-test
mkdtemp-scoped path so a coincidental directory at /workspace/test
on the host doesn't make Windows realpath canonicalize it. Mocked
isWindows so platform-aware production code can be exercised
deterministically. Made the shell-escape prompt assertion
platform-aware (POSIX 'backslash-quote' vs PowerShell double-quote).
Replaced the --agent-file tests with system-prompt-content-into-prompt
assertions backed by a real temp file under fakeHome.

Result: all 103 tests pass on Windows (was 30 failures pre-fix).

* fix(agent-claude-code): preserve Windows drive-letter slug encoding

The merge of origin/main #1611 ("fold underscores in Claude project
slug") inadvertently regressed Windows behavior. #1611 kept the
pre-existing `.replace(/:/g, "")` so `C:\Users\dev\foo` slug-encoded
to `C-Users-dev-foo` (single dash), but Windows-side QA had already
established (commit 582c5373) that real Claude Code on Windows
produces `C--Users-dev-foo` — the colon position becomes a dash,
not stripped. Stripping the colon broke JSONL lookup on Windows so
session info / restore / metadata persistence all silently failed.

Two test files disagreed after the merge: activity-detection.test.ts
expected the Windows-correct double-dash form (kept by my merge),
while index.test.ts expected origin's single-dash form (added by
#1611). Linux CI ran activity-detection's case against the
single-dash impl and failed loudly.

Fix: drop the redundant `.replace(/:/g, "")`. The broader
`[^a-zA-Z0-9-]` regex already handles the colon as a dash, which
matches Claude's actual on-disk encoding on Windows. Updated
index.test.ts to expect `C--Users-dev-foo` and fixed an unrelated
local-Windows test bug where a hardcoded POSIX path string was
compared against a `pathJoin` result (passes on Linux CI but fails
locally on Windows).

Underscore folding from #1611 is preserved.

* fix(cli): Windows platform adapter follow-ups

Three independent Windows correctness fixes bundled with their tests:

* daemon.ts: killExistingDaemon now uses killProcessTree (taskkill /T /F)
  instead of raw process.kill so detached grandchildren of the daemon
  (pty-host, dashboard subprocess) are reached on Windows. POSIX behavior
  is preserved via killProcessTree's process-group fallback.

* startup-preflight.ts: on Windows, when the project config selects
  runtime: tmux, offer to rewrite the line to runtime: process in the
  project YAML instead of prompting "install tmux?". The rewrite is a
  targeted line-replace (not yaml round-trip) so comments and quoting
  are preserved. Decline -> hard exit with manual-fix guidance.

* path-equality: new pathsEqual / canonicalCompareKey helpers used by
  start.ts and resolve-project.ts for "same filesystem entry" checks.
  realpathSync on Windows can return canonical paths whose drive-letter
  case or 8.3-vs-long-name expansion differs from the input even when
  both resolve to the same on-disk entry, which made naive === comparisons
  miss and surface as phantom "register this project?" prompts on
  re-runs of `ao start <path>`. Lowercases on Windows; POSIX is
  unchanged.

Also fixes resolve-project.ts's isLocalPath to recognize Windows path
patterns (drive-letter, UNC, .\, ..\) so `ao start C:\path\to\repo`
takes the path branch instead of being mis-classified as a project id.

Test changes: makeConfig now defaults to runtime: process so tests run
on every platform without tripping the Windows-tmux exit; the one tmux
preflight test pins process.platform = 'linux'. The "kills existing
process" test asserts on killProcessTree instead of process.kill.
On-disk yaml fixtures in start.test.ts switch from runtime: tmux to
runtime: process for the same reason.

New tests: 7 in startup-preflight.test.ts (Windows rewrite, decline
exit, missing configPath exit, comment+quoting preservation, Linux
pass-through), 8 in path-equality.test.ts (drive-letter case, segment
case, POSIX case-sensitivity, realpathSync fallback, ~ expansion),
killProcessTree assertions added to daemon.test.ts.

Verified non-issues during the audit (no code change): ao stop graceful
shutdown gap (the work was already moved into ao stop itself in a prior
refactor; running.json/last-stop/sessions are persisted before the
parent kill, and stale state is self-healing on next read);
better-sqlite3 cross-platform binary (optionalDependencies +
files: ['dist'], no prebuilt .node bundled in any release artifact);
ao-doctor / ao-update PowerShell rewrite (script-runner already
rewrites .sh -> .ps1 on Windows, .ps1 siblings ship in assets/scripts/,
covered by an existing Windows-only test); bun-tmp-janitor leak
(janitor is a no-op on Windows because opencode ships no win32 binary
and Windows refuses to unlink mapped files).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cursor): silence stderr bleed-through in detect() on Windows

execFileSync("agent", ["--help"]) with encoding but no explicit stdio
inherits stderr from the parent process. On Windows with shell:true,
cmd.exe prints "'agent' is not recognized as an internal or external
command" to the terminal even though the exception is caught.

Fix: add stdio:["ignore","pipe","ignore"] to capture stdout (needed for
Cursor marker checks) and discard stderr. Mirrors the pattern used by
the kimicode plugin's detect(). Also adds a 5s timeout as a safety net.

Zero behavior change on macOS/Linux: shell:false means Node throws ENOENT
directly with no subprocess output, so the try/catch already handles it.

Fixes the spurious error printed during ao start first-run setup on Windows.

Co-authored-by: Priyanchew <57816400+Priyanchew@users.noreply.github.com>

* fix(runtime-process): preserve EPERM in Windows pty-host sweep exit-poll

The catch in sweepWindowsPtyHosts treated every error as "process exited",
including EPERM. On Windows EPERM means the pty-host exists but the caller
lacks permission to signal it (cross-context), so the orphan was skipping
the killProcessTree force-kill step and leaking. Mirror the destroy() logic
at line 290: only flag exited on non-EPERM (typically ESRCH).

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

* test(runtime-process): poll for payload instead of fixed sleep

The Windows ConPTY round-trip (named pipe -> pty-host -> pwsh -> findstr
-> rolling buffer) varies from hundreds of ms to seconds depending on
runner load, AV scanners, and cold caches. The previous 1500 ms fixed
sleep flaked on slow Windows runners (observed empty getOutput buffer at
sample time). Replace it with a 10 s deadline poll that checks for the
actual payload substring, robust to both timing variance and incidental
shell banners arriving first.

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

* docs: document cross-platform abstractions and reflect Windows support

Adds docs/CROSS_PLATFORM.md as the canonical reference for cross-platform
development: the "Golden Rule" (no raw process.platform === "win32" — use
isWindows() and the helpers in platform.ts), a full inventory of every
platform helper (platform.ts, path-equality, windows-pty-registry,
pty-client, sweepWindowsPtyHosts, validateSessionId, resolvePipePath,
setupPathWrapperWorkspace, activity-state helpers, AO_SHELL/AO_BASH_PATH),
the EPERM-vs-ESRCH gotcha when probing processes, PowerShell-vs-bash
differences, IPv6 localhost stalls, agent-plugin specifics, and a 10-point
pre-merge checklist.

Updates internal docs (CLAUDE.md, AGENTS.md, docs/ARCHITECTURE.md,
docs/DEVELOPMENT.md, CONTRIBUTING.md, .github/copilot-instructions.md,
.cursor/BUGBOT.md, packages/core/README.md, packages/plugins/runtime-tmux/
README.md, packages/core/src/prompts/orchestrator.md, ARCHITECTURE.md) to
remove tmux-only / POSIX-only claims, point at the new doc, and (in
docs/ARCHITECTURE.md) describe the Windows runtime architecture: pty-host
helper, named-pipe protocol, registry, sweep, mux WS Windows branch.

Updates user-facing docs (README.md, SETUP.md, docs/CLI.md) to split
prerequisites by OS (no tmux on Windows), reflect that ao doctor and
ao update work on Windows, and note that power.preventIdleSleep is a
no-op on Linux and Windows.

Updates the agent-orchestrator skill (skills/agent-orchestrator/SKILL.md
and references/config.md) so it advertises Windows support, drops tmux
from the required-bins list, and gives the right Windows guidance for the
"spawn tmux ENOENT" error.

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

* test(core): update orchestrator-prompt test for cross-platform runtime warning

The orchestrator system prompt was rewritten in 1d8c8f75 to call out both
tmux send-keys (Unix) and the Windows named-pipe write path so the
orchestrator agent doesn't try either. The test still asserted the old
literal "never use raw \`tmux send-keys\`" string. Update it to assert the
new platform-neutral phrasing plus the presence of both runtime mentions.

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

* ci(windows): matrix Linux+Windows + close coverage gaps

Adds windows-latest to typecheck/test/test-web matrices (lint stays
Linux-only; nothing ESLint catches differs by OS). fail-fast: false
so one OS's failure never masks the other's. tmux install steps gate
on runner.os == 'Linux' since Windows uses runtime-process. test job
adds a node-pty prebuild smoke step on Windows so a future ABI break
fails fast with a clear message. test-web is broadened from
server/__tests__/ to the full vitest suite — closes a pre-existing
Linux-too gap and ensures component/hook/lib tests run on Windows.

Closes three completeness gaps where Windows code paths existed but
no test exercised them:

1. session.test.ts (5 tests): "tests Windows behavior, skips on
   Windows" defensive pattern. Tests fully mock isWindows + net.connect
   + child_process — flipping skipIf(win32) to plain it() runs them on
   both OSes. All 45 tests pass on Windows.

2. dashboard.test.ts (+2 tests): findRunningDashboardPidsForWebDir
   has parallel POSIX (lsof + cwd verification) and Windows
   (findPidByPort, no cwd check) implementations. Existing tests
   asserted lsof; new runIf(win32) tests assert findPidByPort path
   plus dedup across multiple ports.

3. start.test.ts (+1 test): port-scan fallback for orphaned
   dashboards skips ps cmdline verification on Windows by design.
   Existing test asserted ps was called; new runIf(win32) parallel
   asserts ps was NOT called and the kill still fires.

Adds first PS1 script test coverage (previously zero):

4. update-ps1.test.ts (4 tests): argparse — --help/-h, unknown flag,
   conflicting --skip-smoke + --smoke-only.

5. doctor-ps1.test.ts (4 tests): argparse + full check pipeline
   smoke. The pipeline test runs every Check-* function against an
   empty repo and asserts the script exits cleanly with a "Results: N
   PASS, N WARN, N FAIL, N FIXED" summary line — catches PS1 syntax
   errors and crashes mid-pipeline.

Net effect: CLI suite went from 622 -> 630 passing tests on Windows
(5 unskipped + 8 new); skipped count dropped from 25 -> 20. All other
suites unchanged.

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

* ci(windows): add minimal permissions block to CI workflow

CodeQL flagged the workflow as missing an explicit permissions
declaration (security/code-scanning/61). All jobs are read-only
(checkout, install, build, test) — contents: read is sufficient.
Matches the workflow-level pattern already used in coverage.yml.

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

* chore: add changeset for native Windows support

Minor bump across the linked package group. The next release PR will
consume this and bump from 0.4.0 to 0.5.0.

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

* fix(cli): make ao open work cross-platform

Mac-only assumptions broke `ao open` on Windows and Linux:

- source of truth was `tmux list-sessions`, which is empty without tmux
- the open action shelled out to `open-iterm-tab`, a macOS helper

Switch the source of truth to `sm.list()` (works on every platform — also
handles `runtime-process` sessions on Windows) and branch the open action:

- macOS: `open-iterm-tab` (unchanged), tmux attach inside iTerm
- Windows: `wt new-tab cmd /k ao session attach <id>` for live sessions,
  with `cmd /c start cmd /k ...` as the no-`wt` fallback. Both paths route
  through `cmd /k` because `wt` and `start` call CreateProcess directly,
  which doesn't honor PATHEXT and reports 0x80070002 for `ao` (really
  `ao.cmd`). New tab anchors at `config.projects[id].path` so the spawned
  attach can resolve `agent-orchestrator.yaml` via loadConfig's upward
  search; without this attach fails with "No agent-orchestrator.yaml found"
  when the user's homedir is the inherited cwd.
- Linux: dashboard URL via `openUrl()`. No consistent terminal-spawn API
  across DEs, so we don't try.

Other behavior changes:

- read the live daemon's port from `running.json` so URLs stay correct
  when the dashboard auto-picked a non-default port
- warn when the daemon is not running (URL fallback won't load)
- aggregate targets (`all`, `<project>`) hide terminated sessions; named
  lookup keeps them in scope and opens the dashboard with the death
  reason inline (`died at <ts>: session=<reason>, runtime=<reason>`) plus
  a `ao session restore <id>` hint
- new `--browser` flag forces the URL path on any platform

Add `isMac()` to `platform.ts` (per the project rule that platform checks
live in one place rather than spread as ad-hoc `process.platform === ...`
guards) and re-export from core.

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

* fix(cli): satisfy lint on ao open changes

- replace inline `import("node:child_process")` type annotation in vi.mock
  with a top-of-file `import type * as ChildProcess` (consistent-type-imports)
- drop the `[]` initializer on `sessionsToOpen` since every branch assigns
  before any read (no-useless-assignment)

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

* chore: add changeset for cross-platform ao open fix

Patch entry for d04fad33 / 32345ba8. Linked group already minor-bumping
via the Windows-support changeset, so this just contributes a distinct
CHANGELOG line.

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

* chore: fold ao open fix into the Windows-support changeset

Single umbrella entry is the right place for it — the separate patch
changeset was redundant given the linked-group minor bump already in
flight. Reverts 3557e556.

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

* Changes before error encountered

Agent-Logs-Url: https://github.com/ComposioHQ/agent-orchestrator/sessions/9f3caf0b-66fb-4eff-bd3f-7fb9ab889630

Co-authored-by: Priyanchew <57816400+Priyanchew@users.noreply.github.com>

* test(core): mock node:child_process via importOriginal in migration test

The atomic-write.ts → platform.js refactor in eaa27b9b pulled platform.ts
into migration-storage-v2.test.ts's module graph. platform.ts evaluates
promisify(execFile) at top level, but the test's bare-object child_process
mock omitted execFile, so the dynamic import crashed with "No 'execFile'
export is defined on the 'node:child_process' mock".

Switch to vi.doMock with importOriginal so any unmocked exports stay real.
This is robust against future imports adding more child_process surface.

Only Ubuntu CI surfaced the regression — the failing test sits inside
describe.skipIf(process.platform === "win32") so the windows-latest leg
never executed it.

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

* test(core): hoist child_process type to satisfy consistent-type-imports

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

* chore(perf): add AO_PERF-gated instrumentation for dashboard load

Temporary tracing added to diagnose 15-20s dashboard terminal load on Mac
and Windows. Gated on AO_PERF=1 (server) and NEXT_PUBLIC_AO_PERF=1
(client) so production paths stay untouched. To be removed once the
bottleneck is fixed.

Wrap points:
- core/perf.ts: perfMark / perfTime helpers + perfCid
- web /api/sessions/[id]: per-stage timings (getServices, sm.get, audit,
  enrichMetadata, total)
- core/session-manager: runtime.isAlive, agent.getActivityState,
  agent.getSessionInfo, ensureHandleAndEnrich
- agent-codex: findCodexSessionFile (scanned/opened/matched counts) +
  cache hit marker
- runtime-process/pty-client: connect outcome + isAlive (split
  connectMs vs statusMs)
- web/lib/serialize: enrich legs (agentSummary vs issueTitle) timed
  independently while still running concurrently
- web/sessions/[id]/page.tsx: client.fetch.start/end with cid header
  forwarded for end-to-end correlation
- web/MuxProvider: ws.open + ws.firstByte per terminal

* fix(core): drop bogus session.agent reference from perf extras

Session has no `agent` field — typed as a metadata key, not a
top-level property. CI typecheck caught what local rtk-filtered
output had hidden. The session-id cid already disambiguates per-session
so the extra wasn't load-bearing.

* revert: remove AO_PERF instrumentation

Reverts b3f522f9 and 004b2a79. The perf marks pinpointed that the
server API path is fast — total <50ms after warm-up — so the 30s
dashboard-terminal delay lives in the WS / xterm path, not in the
session-manager hot path that this instrumentation covered.

Will re-instrument that layer (mux-websocket terminal-open ->
opened-sent -> firstByte) separately when we resume the investigation.

* fix(core): drop unused isWindows import after post-launch removal

The merge took main's no-op for post-launch prompt delivery, which was
the only user of isWindows() in this file. Removing the dangling import
to unblock lint.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: yyovil <itsyyovil@gmail.com>
2026-05-09 00:10:53 +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
i-trytoohard b9b20e19d1
chore: release 0.6.0 (#1723)
* chore: release 0.6.0

* test(agent-codex): bump version pin to 0.6.0

---------

Co-authored-by: Prateek <karnalprateek@gmail.com>
2026-05-08 02:37:44 +05:30
i-trytoohard 8fee6c0e2d
chore: release 0.5.0 (#1676)
* chore(release): add changesets for 0.5.0 and bump codex version test

- Add changesets for #1643 (orchestrator worktree adoption), #1549
  (sidebar empty-state), and #1608 (terminal attach + mux routing).
- Update agent-codex package-version.test.ts expectation from 0.4.0
  to 0.5.0 so the test no longer fails after the upcoming version bump.

* chore: release 0.5.0

---------

Co-authored-by: i-trytoohard <193449657+i-trytoohard@users.noreply.github.com>
2026-05-06 16:44:45 +05:30
i-trytoohard ef8ac42dd4
chore: release 0.4.0 (#1625)
* chore: release 0.4.0

Consume 33 changesets across the linked package group. All public
packages bumped to 0.4.0 and published to npm.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(agent-codex): bump package-version assertion to 0.4.0

Release gate test was still asserting 0.3.0 after the 0.4.0 bump.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: align CHANGELOG headers with @aoagents npm scope

The H1 of every package CHANGELOG.md still read @composio/* from
before the npm scope rename. Body entries that historically reference
@composio/* are left intact — they document what was true at the time
of those releases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Prateek <karnalprateek@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 06:57:24 +05:30
Harshit Singh Bhandari e465a4702d
fix(agent-claude-code): fold underscores in Claude project slug (#1611) (#1612)
`toClaudeProjectPath` only normalized `/`, `.`, and `:` — but Claude Code's
on-disk slug also folds underscores (and other non-alphanumerics) to `-`.
AO project data dirs are named `<sanitized>_<hash>` (e.g.
`graph-isomorphism_d185b44d56`), so the slug AO computed pointed at a
directory that never existed. Cascading failures:

- `getSessionInfo` couldn't read the JSONL → `claudeSessionUuid` never
  got persisted to session metadata.
- On restore, `getRestoreCommand`'s metadata lookup found nothing AND its
  workspace-scan fallback also missed (same bad slug), returning `null`.
- Session-manager's native-restore guard then threw
  `SessionNotRestorableError` → API returned 409.

Verified on-disk: every session under projects without underscores has
`claudeSessionUuid` persisted; every session under projects with
underscores does not. The orchestrator angle in #1611 is the loudest
symptom — orchestrators die early so they have nothing else to fall back
on — but the same bug silently broke worker restore in any multi-project
setup.

Fix: replace `[/.]` with `[^a-zA-Z0-9-]` in the slug regex, matching
Claude Code's actual encoding. Adds direct unit tests for
`toClaudeProjectPath` covering the underscore case plus existing paths,
and a regression test in the `getSessionInfo` path-conversion suite.

Fixes #1611.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-03 20:40:18 +05:30
Ashish Huddar ab65d12356
Fix native restore fallback for Claude and Codex sessions (#1602)
* Fix native session restore fallback for Claude and Codex

* Address restore metadata review comments

* Fix metadata normalization lint

* Address PR metadata review feedback

* Prevent fresh restore fallback for native agents
2026-05-01 21:27:17 +05:30
Copilot e548584130
chore: align workspace package.json versions with npm registry (#1587)
* Initial plan

* chore: bump all workspace package versions from 0.2.5 to 0.3.0

Agent-Logs-Url: https://github.com/ComposioHQ/agent-orchestrator/sessions/da5b2769-e7d4-4d08-a60c-bd5f695d1ca7

Co-authored-by: harshitsinghbhandari <212377671+harshitsinghbhandari@users.noreply.github.com>

* fix: update package-version test to expect 0.3.0

Agent-Logs-Url: https://github.com/ComposioHQ/agent-orchestrator/sessions/ad61e33e-417f-4482-b06c-0b60826b7f2d

Co-authored-by: harshitsinghbhandari <212377671+harshitsinghbhandari@users.noreply.github.com>

* chore: revert non-ao version bumps

Only @aoagents/ao drives the 'ao update available' prompt
(packages/cli/src/lib/update-check.ts compares against the
@aoagents/ao registry version and reads the local @aoagents/ao
package.json). All other workspace bumps are unnecessary.

* chore: align workspace versions with npm registry

Catch up source-of-truth package.json versions to what is already
published on npm. The registry reflects releases done via Changesets;
the in-tree files had drifted to 0.2.5.

  0.2.5 -> 0.3.0: cli, core, web, agent-aider, agent-claude-code,
                  agent-codex, agent-opencode, notifier-composio,
                  notifier-desktop, notifier-slack, notifier-webhook,
                  runtime-process, runtime-tmux, scm-github,
                  terminal-iterm2, terminal-web, tracker-github,
                  tracker-linear, workspace-clone, workspace-worktree
  0.2.5 -> 0.2.6: notifier-discord, notifier-openclaw, scm-gitlab,
                  tracker-gitlab
  0.1.0 -> 0.1.1: agent-cursor

Also updates agent-codex package-version.test.ts to expect 0.3.0.

* test(cli): use future version in update-check cache test

The cache-fresh test assumed getCurrentVersion() returned a value
older than the cached latestVersion. With packages/ao now at 0.3.0
and resolvable from cli via pnpm's hoisted store at test time,
getCurrentVersion() returns 0.3.0, so isOutdated against a cached
latestVersion of 0.3.0 is false and the assertion fails.

Use 99.0.0 in the cache so the comparison stays meaningful regardless
of the current installed version.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: harshitsinghbhandari <212377671+harshitsinghbhandari@users.noreply.github.com>
Co-authored-by: harshitsinghbhandari <claudeagain@pkarnal.com>
2026-05-01 15:31:04 +05:30
Harshit Singh Bhandari 36fed87b2e
refactor(core): storage redesign — projectId-based paths, JSON metadata (#1466)
* refactor(core): switch metadata format from key=value to JSON and add V2 path functions

Phase 1-2 of the storage redesign: adds new projectId-based path functions
(getProjectDir, getProjectSessionsDir, etc.) alongside deprecated storageKey-based
ones, and switches metadata serialization from key=value flat files to JSON with
.json extension. Structured fields (runtimeHandle, statePayload) are stored as
proper JSON objects instead of stringified strings within key=value.

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

* refactor: wire V2 projectId-based paths and remove storageKey system

Switch all consumers from hash-based storage paths to projectId-based
paths (Phase 4) and completely remove the storageKey system (Phase 5).

Phase 4 — V2 path wiring:
- session-manager.ts: all 9 getProjectSessionsDir() calls use projectId
- lifecycle-manager.ts, recovery/scanner.ts, recovery/actions.ts: V2 paths
- portfolio-session-service.ts: JSON metadata + projectId-based paths
- web routes (sessions/[id], projects/[id]): V2 paths
- cli report command: V2 paths
- All test files updated with HOME isolation for parallel safety

Phase 5 — storageKey removal:
- Types: removed storageKey from ProjectConfig, PortfolioProject,
  DegradedProjectEntry
- Schemas: removed from ProjectConfigSchema, GlobalProjectEntrySchema
- Removed: StorageKeyCollisionError, deriveProjectStorageIdentity,
  ensureProjectStorageIdentity, findStorageKeyOwner, relinkProject,
  relinkProjectInGlobalConfig, applyWrappedLocalStorageKeys,
  moveStorageDirectory, countSessionEntries
- CLI: removed `project relink` command
- Web: removed storageKey from settings UI, simplified collision handling
- Simplified registerProjectInGlobalConfig and resolveProjectIdentity

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

* refactor(core): restructure SessionMetadata types for storage redesign Phase 3

Complete the typed field restructuring on SessionMetadata:
- statePayload/stateVersion → lifecycle?: CanonicalSessionLifecycle
- runtimeHandle: string → RuntimeHandle (with backward-compat parsing)
- prAutoDetect: "on"/"off" → boolean (with legacy string conversion)
- dashboardPort/terminalWsPort/directTerminalWsPort → nested dashboard object
- LifecycleDecision: flat detecting* fields → nested detecting object

Includes migration command (ao migrate-storage), V2 path functions,
storageKey removal, and updated test plan (to-test.md).

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

* fix(core): address review findings for storage redesign migration

Fix all HIGH-priority review findings and blockers from external review:
- Detect bare 12-hex hash directories during migration inventory
- Skip observability directories during migration
- Detect V2 tmux session naming patterns for active session check
- Derive status from lifecycle when not stored in migrated JSON
- Fix rollback to preserve storageKey format and post-migration data
- Extract shared flattenToStringRecord utility to avoid duplication
- Handle prAutoDetect "true"/"false" string variants

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

* fix(core): update displayName test for JSON metadata format

The upstream displayName test asserted key=value file format and
bare filename. Update to check JSON content and .json extension.

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

* fix(core): fix runtimeHandle type in upstream restore test

The upstream displayName restore test passed runtimeHandle as
JSON.stringify(makeHandle(...)) — a string. Our type change requires
the RuntimeHandle object directly.

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

* fix(core): address PR review comments

- Handle empty files from reserveSessionId() in mutateMetadata() —
  treat empty/whitespace content as empty record instead of throwing
  on JSON.parse
- Fix archive doc comment: archives live under <sessionsDir>/archive/,
  not <projectDir>/archive/
- Remove migration test file from gitleaks path allowlist — no false
  positives are triggered, so blanket file exclusion is unnecessary

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

* fix: use targeted regex instead of path allowlist for gitleaks

Replace the blanket file allowlist with a regex matching the specific
test placeholder hash "abcdef012345" that triggers the generic-api-key
rule. This keeps secret scanning active for the migration test file.

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

* fix: replace high-entropy test placeholder to avoid gitleaks false positive

Use `aaaaaa000000` instead of `abcdef012345` as the dummy 12-hex-char
hash in migration tests. The old value triggered gitleaks' generic-api-key
rule when combined with `storageKey:` in YAML-like test fixtures. This
eliminates the need for any gitleaks allowlist entry for this file.

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

* fix(cli): auto-register flat local config in ao start

When running `ao start` in a directory with a flat
agent-orchestrator.yaml (no `projects:` key) that isn't registered
in the global config, the Zod validation error was surfacing as a
raw error dump. Now auto-registers the project in the global config
and retries, matching the behavior of `ao start <path>`.

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

* fix(core): correct migration error message to use ao session kill

The error message referenced `ao kill --all` which doesn't exist.
The correct command is `ao session kill --all`.

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

* fix(core): address review findings — worktree paths, archive location, recovery log

- Migration now writes absolute worktree paths instead of relative
  (relative paths resolved against cwd, not project dir, breaking restore)
- Archive directory moved from projects/{pid}/archive/ to
  projects/{pid}/sessions/archive/ to match runtime deleteMetadata behavior
- getProjectArchiveDir() updated to return sessions/archive/ consistently
- fixArchiveFilename() handles sanitized timestamps (dashes replacing colons)
- getRecoveryLogPath() fallback uses AO base dir instead of synthetic
  projects/_recovery/ directory

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

* fix(core): update metadata hooks for JSON format and .json extension

Both the Claude Code PostToolUse hook and the PATH wrapper hooks
(gh/git) were constructing metadata paths without .json extension and
using key=value sed to update metadata. This broke after the storage
V2 migration which uses .json files with JSON content.

Changes:
- Try {sessionId}.json first, fall back to bare {sessionId} for
  pre-migration layouts
- Detect JSON format (first char '{') and use jq for updates
- Fall back to key=value sed for legacy metadata files
- Bump WRAPPER_VERSION 0.3.0 → 0.4.0 to force wrapper reinstall

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

* fix(core): reset lifecycle on restore and keep killed sessions in active metadata

Two runtime bugs fixed:

1. Restore: lifecycle object was not reset — lifecycle manager read the old
   terminal state and immediately transitioned back to Done. Now resets
   lifecycle to working/alive via cloneLifecycle + buildLifecycleMetadataPatch.

2. Kill: sessions were immediately archived, making them invisible to list()
   and get(). Dashboard showed "Page not found" instead of Done/Terminated.
   Now keeps killed sessions in active metadata with terminal status.

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

* fix(core): address storage redesign review findings

Fix CI blocker and several correctness/consistency issues found during
review of PR #1466:

1. Fix codex plugin test failures — WRAPPER_VERSION bumped to 0.4.0 in
   agent-workspace-hooks.ts but codex tests still expected 0.3.0

2. Add agentReport and reportWatcher to jsonFields in
   unflattenFromStringRecord — these object fields were missing from the
   known-fields set, causing silent data corruption on mutateMetadata
   roundtrip (object → string → stays string instead of reparsing)

3. Normalize prAutoDetect writes from "off" to "false" in
   session-manager — the JSON round-trip converts "off" to boolean false
   on disk, which flattens to "false" on read-back. Writing "false"
   directly avoids the ambiguity and matches the round-trip behavior

4. Fix STORAGE_REDESIGN.md to match implementation — archive path is
   sessions/archive/ (not a sibling of sessions/), and status is still
   persisted (computed-only deferred to follow-up)

5. Keep detecting fields at top level during migration — the lifecycle
   manager reads detectingAttempts/detectingStartedAt/detectingEvidenceHash
   from session.metadata (top-level), not from lifecycle.detecting.
   Nesting them during migration caused silent reset on first poll

6. Remove to-test.md development artifact (895 lines)

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

* fix(core): remove unused readMetadata import in lifecycle test

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

* fix(core): fix 3 critical migration issues

1. Orchestrator blindness: stop extracting orchestrators to orphaned
   orchestrator.json — write them to sessions/ where runtime reads from.
2. Pre-lifecycle "unknown": preserve status in migrated JSON when no
   statePayload exists, preventing readMetadata fallback to "unknown".
3. Archive timestamp collision: add counter to archive filenames to
   prevent same-millisecond overwrites. Fix dead-code ternary.

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

* fix(core): eliminate status dual truth, fix jsonFields whitelist, add rollback dry-run and tests

- Status is now computed on read from lifecycle (single source of truth).
  deriveLegacyStatus maps session.reason to specific terminal statuses
  (killed, cleanup, errored) instead of relying on stored previousStatus.
- Remove jsonFields whitelist in unflattenFromStringRecord — auto-detect
  JSON by checking if value starts with { or [. Prevents silent
  stringification of new JSON fields.
- Add dryRun option to rollbackStorage and wire through CLI --dry-run.
- Add 18 tests for V2 path functions (getProjectDir, assertSafeProjectId,
  compactTimestamp, parseTmuxNameV2, etc.).
- Add migration edge case tests: worktree dir migration, pre-lifecycle
  status preservation, archive filename uniqueness, active session blocking.

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

* fix(core): fix stray worktree recursion, rollback data loss, and worktree path rewrite

- moveStrayWorktrees now recurses into ~/.worktrees/{projectId}/{sessionId}/
  (default workspace plugin layout) instead of only scanning top-level entries
- Rollback checks for post-migration sessions before deleting project dirs,
  preserving sessions created after migration with a warning
- Worktree path rewrite only fires when the destination directory actually
  exists, keeping original paths for worktrees not yet moved

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

* fix(core): reset terminal PR state on session restore

When restoring a session whose PR was already merged/closed, the
lifecycle manager would immediately re-detect the merged PR and
terminate the session again — making restore useless for merged sessions.

On restore, if pr.state is "merged" or "closed", reset it to "none"
with reason "cleared_on_restore". This lets the session run freely;
if the agent creates a new PR, auto-detect picks it up normally.
Also clears mergedPendingCleanupSince to prevent stale cleanup.

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

* fix(core): remove stale previousStatus args and unused SessionStatus import

Two call sites in lifecycle-manager.ts still passed session.status as
a second argument to deriveLegacyStatus and buildLifecycleMetadataPatch
after the previousStatus parameter was removed. Also removes unused
SessionStatus import from metadata.ts.

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

* fix(core): address PR review comments — parser, docs, delete route, prefix sanitization

- parseTmuxNameV2: allow hyphens in prefix to match sessionPrefix
  validation ([a-zA-Z0-9_-]+), fixing "my-app-1" parsing
- SessionMetadata: update stale doc comments — JSON format, no hash prefix
- DELETE /api/projects/[id]: report actual removedStorageDir based on
  whether the directory existed before deletion
- start.ts registerFlatConfig: sanitize projectId before deriving
  sessionPrefix, matching config-generator.ts behavior

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

* fix(agent-claude-code): add --dangerously-skip-permissions for all restored sessions

getRestoreCommand only added the flag for orchestrator sessions, but
getLaunchCommand adds it for any session with permissionless/auto-edit.
This caused restored worker sessions to lose permissionless mode.

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

* fix(core): skip .migrated dirs in inventory to prevent .migrated.migrated on re-run

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

* fix(core): rollback worktree preservation, scoped tmux detection, JSON parse whitelist

- Move worktrees back to restored hash dirs before deleting project dir on rollback
- Scope v2OrchestratorPattern to known project prefixes instead of matching any tmux session
- Restrict unflattenFromStringRecord JSON parsing to known structured fields only

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

* feat(cli): show "Add this project" option in ao start project picker

When running ao start in a git repo that isn't registered, the project
selector now includes an option to add the current directory as a new
project instead of requiring the user to run a separate command.

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

* feat(cli): show "Add project" in already-running menu when cwd is unregistered

When AO is already running and the user runs ao start from an
unregistered git repo, the menu now offers to add that directory
as a new project alongside the existing open/restart/quit options.

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

* feat(cli): add --reports flag to ao status for agent report history

Adds --reports option to `ao status` that displays the agent report
audit trail per session. Accepts "full" for all entries or a positive
integer for the last N entries.

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

* fix(cli): replace removed storageKey reference with getProjectSessionsDir in status command

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

* fix(core,web): address PR review issues — crash safety, atomic ops, corrupt data handling, test fixes

- metadata.ts: handle corrupt JSON gracefully (return null instead of crashing), use atomic renameSync for archive, conditionally persist status only when lifecycle is not an object
- storage-v2.ts: add crash-safety marker file for migration, fix archive filename handling for .json suffix and compact timestamps, use Date parsing for duplicate session resolution
- lifecycle-state.ts: add JSDoc and clarify deriveLegacyStatus default case behavior
- lifecycle-transition.ts: add JSDoc clarifying buildTransitionMetadataPatch scope
- AddProjectModal.test.tsx: fix pre-existing jsdom localStorage mock so saveRecentPath works in tests
- Add tests for corrupt JSON handling, migration markers, and crash recovery

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

* fix(core): harden storage-redesign against edge cases (EC-1 through EC-8, EC-14, EC-27)

Address 10 edge cases found during systematic review of storage redesign:

- EC-1: Wrap mutateMetadata read-modify-write in withFileLockSync to prevent race conditions
- EC-2: Replace existsSync+readFileSync TOCTOU pattern with try-catch in readMetadata/readMetadataRaw
- EC-3: Append PID to archive filenames to prevent same-second collision
- EC-4/5: Add crossDeviceMove helper with EXDEV fallback (cpSync+rmSync) for migration renames
- EC-6/13: Restrict project ID validation to [a-zA-Z0-9][a-zA-Z0-9._-]* with 128-char max
- EC-7: Guard rollback rename against pre-existing target directory
- EC-8: Add mtime+path tiebreaker for duplicate session resolution
- EC-14: Fix misleading "Resuming" log message in migration
- EC-27: Extend readMetadataRaw status override to handle statePayload-only sessions

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

* fix(core,cli): prevent silent data loss on upgrade — V1 detection, git worktree repair, storageKey preservation

Three P0 fixes for storage-redesign migration UX:

1. Warn on `ao start` when legacy hash-based directories exist,
   telling users to run `ao migrate-storage` before sessions disappear.

2. Run `git worktree repair` from each project's repo root after
   migration moves worktree directories — fixes broken git references
   that would otherwise make git status/push fail inside moved worktrees.

3. Preserve `storageKey` in global config allowlist so it isn't silently
   stripped on load before migration has a chance to use it.

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

* fix(core): skip active session check during migrate-storage --dry-run

Dry run is read-only — blocking on active sessions defeats the purpose
of previewing what migration would do.

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

* fix(integration-tests): update archive filename regex for PID suffix

EC-3 appended -p{pid} to archive filenames to prevent same-second
collisions. Update the integration test regex to match the new format.

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

* fix(core): address final merge review — Zod schema gaps, worktree repair, rollback safety, status priority

5 fixes from final review:

1. Add storageKey to GlobalProjectEntrySchema (Zod) so it survives
   parse→save round-trips until migration strips it.

2. Add 5 missing reason values to lifecycle Zod schemas
   (auto_cleanup, pr_merged, cleared_on_restore, pr_merged_cleanup)
   so lifecycle isn't silently reconstructed from stale status on restart.

3. Run repairGitWorktrees when stray worktrees are moved, not only
   when hash-dir worktrees are moved (was checking wrong counter).

4. Count archived post-migration sessions in rollback safety check
   so rollback warns before silently deleting user's archived data.

5. Fix portfolio-session-service status priority to prefer lifecycle-
   derived status over stored, matching metadata.ts behavior.

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

* fix(core): harden storage redesign migration rollback

* fix(core,cli,web): allocate suffixed project ids on duplicate names

* fix(core,cli): graceful migration errors + skip orchestrator selector

- Migration: wrap per-project migration in try/catch so one failure
  doesn't abort the entire run. Handle ENOTEMPTY when .migrated target
  already exists from an interrupted previous run.
- CLI: ao start now always opens the selected orchestrator's dashboard
  page directly instead of the orchestrator selector.

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

* fix(core,cli): align with upstream to reduce merge conflicts

Bump WRAPPER_VERSION from 0.4.0 to 0.6.0 to match upstream's gh CLI
tracer changes (#1238), and update start.test.ts URL assertion to use
canonical orchestrator IDs (no number suffix) per upstream's orchestrator
identity fix (#1487). These pre-merge alignments eliminate 3 of the 11
conflicts when merging upstream/main.

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

* fix: resolve Phase 1+2 merge conflicts with upstream/main (#1487, #1238)

* fix(core,web): allow restoring merged sessions

Remove "merged" from NON_RESTORABLE_STATUSES and delete the
hasMergedLifecyclePR guard so sessions with merged PRs can be
restored like any other terminal session. Previously clicking
"Restore" on a merged session returned a misleading 409 error
("session is not in a terminal state") — the session was terminal,
just explicitly blocked.

Also fix Dashboard.tsx to show the restore button for merged
sessions and improve the error message in restore() to include
the actual status and activity state.

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

* Implement hashed project identity

* fix(core,cli,web): address PR #1466 review findings

1. Patch session JSON worktree field after moving stray worktrees
2. Preserve migration marker and skip config stripping on partial failure
3. Sanitize legacy project IDs with unsafe characters during migration
4. Use sed-based JSON update when jq is unavailable instead of corrupting
   JSON metadata with key=value fallback
5. Fall back to flat local config repo during first registration when
   git origin provides no repo identity
6. Return and print effective registered project ID from ao project add
7. Update web route tests to use effective hashed project IDs and fix
   repairWrappedLocalProjectConfig to find entries by content fallback

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

* fix(core): use strict equality to satisfy eqeqeq lint rule

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

* fix(core,web): address Copilot review comments

1. parseTmuxNameV2: accept digit-leading prefixes to match the config
   schema validation ([a-zA-Z0-9_-]+)
2. DELETE /api/projects/[id]: return 400 for unsafe project IDs instead
   of letting getProjectDir throw into the 500 catch-all
3. POST /api/projects: return structured 409 on collision with
   existingProjectId, suggestedProjectId, and suggestion fields so the
   AddProjectModal collision UI actually works

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

* fix(core,workspace): route new worktrees to V2 project directory

The workspace-worktree plugin defaulted to ~/.worktrees/ for all new
worktrees, bypassing the V2 layout entirely. New sessions created
worktrees at ~/.worktrees/{projectId}/{sessionId} instead of
~/.agent-orchestrator/projects/{projectId}/worktrees/{sessionId}.

Add optional worktreeDir to WorkspaceCreateConfig so session-manager
can pass getProjectWorktreesDir(projectId) per spawn/restore call.
The plugin uses this override when provided, falling back to the
plugin-level default for backward compat.

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

* fix(cli): prefix unused addCwdOption variable to satisfy lint

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

* fix(core): address migration review findings and orchestrator tmux double-prefix

Migration (storage-v2.ts):
- Use atomicWriteFileSync for all session JSON writes (crash safety)
- Wrap stripStorageKeysFromConfig in withFileLockSync (concurrency safety)
- Add case-insensitive projectId collision detection (macOS HFS+/APFS)
- Call repairGitWorktrees in rollback path (git worktree ref repair)
- Skip stray worktree moves for failed projects (partial-failure safety)

Session manager:
- Fix orchestrator tmux name double-prefix: getOrchestratorSessionId
  already returns "{prefix}-orchestrator", so tmuxName should use
  sessionId directly, not "${prefix}-${sessionId}"

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

* refactor(core): remove archive path functions from paths.ts and index.ts

Remove getProjectArchiveDir, getArchiveFilePath, and compactTimestamp
from V2 path helpers as part of archive system removal. Sessions will
stay in sessions/ with lifecycle.state: "terminated" instead of being
moved to sessions/archive/. Callers in metadata.ts and migration will
be updated in subsequent tasks.

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

* refactor(core): remove archive logic from metadata.ts

Remove archive system from metadata layer: simplify deleteMetadata to
permanent-only deletion, delete readArchivedMetadataRaw and
updateArchivedMetadata functions, and update unit/integration tests.

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

* refactor(core): remove archive code from session-manager.ts

Remove all archive-related logic from the session manager now that
terminated sessions stay in sessions/ instead of being moved to an
archive directory.

Changes:
- Remove readArchivedMetadataRaw/updateArchivedMetadata imports
- Delete listArchivedSessionIds and markArchivedOpenCodeCleanup functions
- Remove archive search from findOpenCodeSessionIds
- Remove listArchivedSessionIds from reserveNextSessionIdentity
- Replace archive fallback in kill() with readMetadataRaw + lifecycle check
- Remove archive fallback in restore() (findSessionRecord finds all sessions)
- Replace archive iteration in cleanup() with terminated session iteration
- Remove boolean archive flag from all deleteMetadata calls
- Remove unused readdirSync import
- Update lifecycle and restore tests to use terminated state instead of archive

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

* fix(core): stop archiving sessions on cleanup in recovery/actions.ts

Remove the deleteMetadata call that archived sessions after marking them
terminated. Sessions now remain in sessions/ with terminated state.
Also remove the now-unused deleteMetadata import.

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

* refactor(core): flatten archives into sessions/ during migration instead of copying to archive dir

Remove the archive system from storage-v2 migration: old V1 archives are now
flattened into sessions/ as terminated session records instead of being copied
to sessions/archive/. Duplicate sessions across hash dirs are skipped with a
warning instead of being archived. Remove fixArchiveFilename(), compactTimestamp
import, archives field from result types, and archive counting from rollback.

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

* refactor(core): remove archive directory filter from listMetadata

The isFile() check already excludes directories. Archive filter was only
needed when sessions/archive/ was actively used.

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

* fix(core): update tests to match archive-removal behavior

cleanupSession in recovery/actions.ts now marks sessions as terminated
instead of deleting metadata. Updated two recovery-actions tests to
assert on terminated status instead of file deletion. Also fixed
metadata and integration tests for the new deleteMetadata signature
(no boolean archive arg).

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

* fix(core): address build/test issues from archive removal

- Fix writeMetadata calls missing required fields in test files
- Remove boolean archive arg from deleteMetadata calls in integration tests
- Update recovery-actions tests to expect terminated state instead of deletion
- Remove unused readdirSync import from migration test

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

* docs: update handoff doc — archiving removed

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

* docs: remove handoff document

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

* feat(cli): add last-stop state persistence for ao stop/start restore

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

* feat(cli): ao stop kills all active sessions and records them

ao stop now kills all active sessions (orchestrator + workers), not just
the orchestrator. Killed session IDs are saved to last-stop.json for
restore on next ao start.

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

* feat(cli): ao start offers to restore sessions from last ao stop

On interactive startup, if last-stop.json exists with sessions for the
current project, the user is prompted to restore them. The orchestrator
is skipped (already restored by ensureOrchestrator). The file is cleared
after the prompt regardless of choice.

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

* fix(cli): update stop tests for all-sessions kill behavior

Update test mocks to return proper KillResult shape and adjust test
assertions for the new all-sessions stop behavior. Add console.log
fallback for killed session IDs (non-TTY/test capture).

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

* fix(core): address review — sed JSON corruption, sanitizeBasename dot

- Replace sed-based JSON fallback with node -e in workspace hooks and
  claude-code plugin. sed "s|}|...|" replaces the first } per line,
  corrupting nested JSON (lifecycle, runtimeHandle). node is a hard dep
  and handles nested objects correctly via JSON.parse/stringify.
- Drop . from sanitizeBasename allowed chars — config.ts Zod schema
  rejects dots in project keys, so my.app_hash would fail loadConfig.

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

* fix: address storage redesign review issues

* fix(core): persist stale runtime state + show cross-project sessions in ao stop/start

- session-manager: persist lifecycle to disk when enrichment detects dead
  runtime (missing/exited) — prevents stale "alive" metadata from keeping
  terminated sessions on the active sidebar (ao-100 bug)
- lifecycle-state: map runtime_lost reason to "killed" legacy status
- ao stop: list ALL sessions across projects, not just targeted project;
  display and record cross-project sessions in last-stop.json
- ao start: show sessions from other projects that were stopped, so user
  knows they need separate ao start for those projects

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

* fix(cli): scope ao stop to target project when explicit arg is given

ao stop (no arg) kills all sessions across all projects since it also
kills the parent ao start process. ao stop <project> now correctly
scopes to just that project's sessions.

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

* fix(cli): show all projects in tab completions by merging global config

listProjects() only read the local config (found via cwd search), which
may contain just one project. Now also reads the global config at
~/.agent-orchestrator/config.yaml to include all registered projects
in shell completions for ao stop, ao start, etc.

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

* fix(cli): fall back to global config when project arg not in local config

ao stop <project> and ao start <project> failed when cwd has a local
agent-orchestrator.yaml that doesn't contain the targeted project.
Now falls back to ~/.agent-orchestrator/config.yaml which has all
registered projects, matching what tab completions already show.

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

* fix(cli): ao stop <project> must not kill parent process or dashboard

ao stop donna was killing the parent ao start process and dashboard,
which serve ALL projects. Now only kills the parent process and
dashboard when no project arg is given (full shutdown). When targeting
a specific project, only that project's sessions are killed.

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

* fix(cli): always load global config for ao stop to see all projects

sm.list() iterates config.projects to find sessions. When loadConfig()
finds the local agent-orchestrator.yaml (1 project), ao stop only sees
that project's sessions — other projects' tmux sessions survive. Now
ao stop always loads the global config which has all registered projects.

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

* fix(cli): ao start restores all sessions including cross-project ones

ao start showed sessions from all projects but only restored the
current project's sessions. Now restores all sessions listed, using
the global config so the session manager can see all projects.

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

* fix(web): sidebar shows all sessions regardless of active project

Remove project scoping from useSessionEvents so the sidebar always
receives sessions from every project. Kanban filtering is applied
client-side via a projectSessions memo.

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

* fix(cli): Ctrl+C on ao start performs full graceful shutdown

Previously Ctrl+C only stopped lifecycle workers and exited, leaving
sessions alive in tmux and not recording last-stop state for restore.
Now the SIGINT/SIGTERM handler mirrors ao stop: kills all sessions,
records last-stop state, and unregisters from running.json. A 10s
timeout ensures the process always exits even if cleanup hangs.

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

* docs: update architecture docs for CLI, lifecycle, and dashboard changes

- CLAUDE.md: add canonical lifecycle states/reasons, stale runtime
  reconciliation, LastStopState + running.json to storage section,
  config resolution note, CLI behavior section (ao start/stop/Ctrl+C),
  key files (lifecycle-state.ts, running-state.ts, start.ts, sidebar)
- AGENTS.md: add lifecycle-state.ts, start.ts, running-state.ts to key
  files, add CLI behavior notes section
- copilot-instructions.md: add lifecycle-state.ts + start.ts to
  high-risk files, add common mistakes for runtime_lost, sidebar
  scoping, and ao stop project scoping
- DESIGN.md: add decision log entry for sidebar cross-project sessions

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

* docs: update PR behavior dashboard with behavioral fixes and cross-project CLI

Add sections for stale runtime reconciliation, dashboard sidebar
scoping, tab completions, config resolution, Ctrl+C graceful shutdown,
and documentation updates. Update stats to 90 files, +6481/-2421.
Update ao stop/start panels with cross-project behavior. Update
summary with runtime reconciliation and cross-project CLI verdicts.

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

* Revert "docs: update PR behavior dashboard with behavioral fixes and cross-project CLI"

This reverts commit 6d968b9ff5.

* fix(cli): add removeProjectFromRunning and targeted stop tests

- Add removeProjectFromRunning() to running-state.ts — removes a
  project from running.json so ao start <project> can restart without
  hitting the "already running" gate after ao stop <project>
- Add projectNeedsRestart check in ao start — skips "already running"
  menu when the project was removed from running.json by a targeted stop
- Add 6 tests for targeted stop behavior: no parent kill, no unregister,
  removes project from running.json, kills correct sessions, full stop
  still tears down parent+dashboard, last-stop records correct scope

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

* docs: update handoff docs with accurate checkout recipes and CLI details

Fix checkout instructions to not assume everyone has the same fork as
origin — add separate sections for the PR author vs new contributors.
Correct stop.ts references (doesn't exist — stop logic is in start.ts).
Document removeProjectFromRunning, projectNeedsRestart gate, isProjectId
guard, and Ctrl+C signal handler details.

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

* fix(cli): handle URL/path args when AO is already running

Previously `ao start <URL>` or `ao start <path>` while the daemon was
already running silently ignored the arg and showed a menu about cwd.
The user's URL was dropped.

Now, for TTY callers, when AO is already running and a URL/path arg is
provided:

- If the project is already registered AND in running.projects, just
  open the dashboard. No menu, no re-clone.
- Otherwise, register the project against the active config (clone for
  URLs via handleUrlStart, or addProjectToConfig for paths) and open
  the existing dashboard. Don't fall through to runStartup — that would
  spawn a duplicate dashboard on a different port.

Non-TTY callers (scripts/agents) keep the old "AO is already running"
message and do NOT mutate config behind the user's back.

Adds two tests:
- Path arg already registered + running → opens dashboard, no menu, no
  YAML mutation.
- Path arg unregistered + AO running → registers without prompting, no
  menu, prints "Opening the dashboard".

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

* fix(cli): register URL/path args in global config and spawn orchestrator

Previously `ao start <URL>` while AO was already running would register
the new project in the cwd's local config (polluting an unrelated
project's YAML) and tell the user to `ao stop && ao start <id>` to
actually spawn the orchestrator — clunky and surprising.

Now the flow:

- Always register against ~/.agent-orchestrator/config.yaml (global),
  never the cwd's local config. URLs go through handleUrlStart to
  clone, then are re-registered globally; paths go through
  addProjectToConfig with a global-config arg so it routes to
  registerProjectInGlobalConfig.
- Spawn the orchestrator session via sm.ensureOrchestrator so the
  dashboard immediately shows it.
- Warn that lifecycle polling for the new project requires
  `ao stop && ao start <id>` (the running daemon's worker can only
  poll projects it knew about at startup).
- Open the existing dashboard. No duplicate dashboard, no menu.

Already-registered + running case unchanged: just open the dashboard.

Tests updated to set AO_GLOBAL_CONFIG so the global lookup is isolated
from the test machine's real config, and to assert ensureOrchestrator
is called with the new project ID.

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

* fix(cli): reload dashboard config after registering new project

After `ao start <URL/path>` registers a new project in the global
config, the running dashboard's services cache still holds the stale
config — so the project page 404s until the daemon is restarted.

Hit POST /api/projects/reload (which invalidates the services cache)
right after registering. Failure to reach the dashboard is non-fatal:
print a hint to refresh the page.

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

* fix(cli): repair wrapped local config after URL clone

handleUrlStart writes a legacy wrapped (`projects:`) agent-orchestrator.yaml
inside the cloned repo. After registering the project against the global
config, the project resolver hits the wrapped local config and routes the
project into degradedProjects (with a resolveError) — so loadConfig drops
it from config.projects and ao start would throw "Failed to register".

Call repairWrappedLocalProjectConfig() right after the global registration
to convert the wrapped config to the flat format the new resolver expects.
Best-effort: if repair fails, defaults fill in behavior.

Cleanup note: any wrapped local configs from earlier runs (and stale
~/.agent-orchestrator/config.yaml entries from earlier test runs that
pre-dated AO_GLOBAL_CONFIG isolation) need manual cleanup.

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

* fix(cli): clone+register flat config directly, surface empty-repo errors

Replaces the previous "register, then repair the wrapped config" hack
with a single-shot clone-and-register flow that produces a valid flat
local config from the start.

Why the previous flow was wrong:
- handleUrlStart writes a legacy wrapped (`projects:`) agent-orchestrator.yaml
  inside the cloned repo. The new global-config resolver rejects that
  shape and routes the project into `degradedProjects`, which breaks
  `loadConfig().projects[id]` lookups and 404s the dashboard route.
- repairWrappedLocalProjectConfig() papered over that — but the right
  fix is to never write a wrapped config in the first place.

What this does instead, when `ao start <URL>` runs while the daemon
is alive:

1. Parse the URL, resolve the clone target, clone (or reuse).
2. Detect the actual default branch via `git symbolic-ref refs/remotes/origin/HEAD`,
   falling back to local HEAD. Returns null for empty repos.
3. If the repo is empty (no commits / no refs), fail early with a
   clear actionable message — otherwise ensureOrchestrator throws a
   confusing "Unable to resolve base ref" deep inside the worktree
   plugin.
4. registerProjectInGlobalConfig with identity only (path, repo,
   defaultBranch, sessionPrefix derived from project ID).
5. writeLocalProjectConfig with behavior only (scm + tracker plugin
   choices, derived from the host platform). Skip the write if the
   repo already commits its own agent-orchestrator.yaml.
6. Refresh the global config and spawn the orchestrator session.

Drops `repairWrappedLocalProjectConfig` import — no longer needed.

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

* fix(migration): keep agent-report and report-watcher metadata flat

Migration was nesting six agent-report keys (agentReportedState, At,
Note, PrUrl, PrNumber, PrIsDraft) and four report-watcher keys
(reportWatcherLastAuditedAt, ActiveTrigger, TriggerActivatedAt,
TriggerCount) into `agentReport` / `reportWatcher` wrapper objects.

The live runtime readers — parseExistingAgentReport in agent-report.ts
and the report-watcher writes in lifecycle-manager.ts — read these
keys flat off `session.metadata`. readMetadataRaw() then runs the
result through flattenToStringRecord(), which JSON.stringify()s any
object value into a single string under the wrapper key. It does NOT
unfold the nested object back into the flat keys the readers expect.

Net effect: any V1 session that had a non-empty agent report or a
non-zero report-watcher trigger count silently lost that state after
migration. The active-tmux gate in `ao migrate-storage` blunts the
worst case (sessions are terminated by the time migration runs, so
the freshness window often expires the data anyway), but reports
within the 5-minute freshness window and dashboard "last reported"
fidelity are still affected.

Fix: keep these ten keys flat in the V2 JSON, identical to the
existing handling for the `detecting*` fields. Same rationale, same
shape. Adds a regression test that asserts the flat keys round-trip
through migration and rewrites the two grouping tests to assert the
new flat shape.

Reported on PR #1466 by @ashish921998.

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

* docs(prompt): teach orchestrator to read agent reports via ao status --reports

The orchestrator system prompt explained the worker-only `ao report`
command and the freshness/precedence rules around agent reports, but
never told the orchestrator how to inspect them. The CLI flag
`ao status --reports <full | N>` already exists for exactly this
purpose — surface it in Monitoring Progress and cross-reference it
from the Explicit Agent Reports section so the orchestrator has an
obvious read path when an inferred status disagrees with what the
worker self-reported.

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

* fix(cli): attach to existing daemon for ao start <project> after targeted stop

Reported on PR #1466 as P1: after `ao stop <project>` removed the project
from running.json (via removeProjectFromRunning) but left the parent
ao start process alive, `ao start <project>` took the projectNeedsRestart
path and fell through to runStartup(). runStartup() then started a SECOND
dashboard on a new port and overwrote running.json — leaving two AO
processes running, with running.json pointing at only the new one and the
original parent's lifecycle worker still polling.

Fix: when running && projectArg is a project ID && project not in
running.projects, attach to the existing daemon instead of falling through
to runStartup. The new branch:

- Loads the project from the global config and refuses with a clear error
  if it isn't registered there.
- Spawns the orchestrator session via the live session manager
  (sm.ensureOrchestrator).
- Calls the new addProjectToRunning() helper to put the project back into
  running.json so subsequent `ao stop` (no args) sees it and `ao spawn`
  doesn't print the "running instance is not polling project X" warning.
- Reloads the dashboard's services cache via POST /api/projects/reload so
  the project page works on the existing dashboard.
- Surfaces a yellow warning that lifecycle polling for the new project
  isn't attached without a full daemon restart — same architectural caveat
  documented in the URL/path attach branch and tracked separately as the
  dynamic project supervisor follow-up issue (#1522).
- Works for both TTY and non-TTY callers; non-TTY just skips the
  openUrl + dashboard popup.

Adds addProjectToRunning() in running-state.ts symmetric to the existing
removeProjectFromRunning(): file-locked, idempotent, no-op when state is
missing or already lists the project.

Adds a regression test that asserts:
- mockRegister is NOT called (no second daemon registration)
- ensureOrchestrator is called with the requested projectId
- addProjectToRunning is called with the projectId
- The interactive menu is NOT shown
- Output contains the expected "Attaching to running AO instance" /
  "reattached to running daemon" lines

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

* docs: add scripts/demo-pr-1466.sh — end-to-end reviewer demo

Self-contained, sandboxed walkthrough of every PR #1466 behavior change.
Designed to be recorded as a screencast — section banners replace
narration, no live typing, deterministic output.

Six acts:
  1. Migration V1 → V2 (live: seed hash dirs + key=value, dry-run, execute,
     show V2 layout, verify @ashish921998 fix that agent-report keys stay
     flat after migration, prove rollback safety on rerun)
  2. Cross-project CLI P1 fix (filter the regression test by name and run
     it live — asserts no second daemon is spawned by ao start <project>
     after ao stop <project>)
  3. Dashboard sidebar shows all projects (display the Dashboard.tsx fix)
  4. Restore from ao stop / Ctrl+C (last-stop.json round-trip)
  5. Ctrl+C graceful shutdown handler with 10s hard timeout
  6. Empty-repo guard for ao start <URL> (the detectClonedRepoDefaultBranch
     null path that surfaces a useful error before ensureOrchestrator)

Then prints the final 560 / 981 test summary so the recording ends on
a green CI signal.

Sandbox notes:
  • $HOME is overridden to /tmp/ao-demo-1466 for the duration of the
    script so getAoBaseDir() resolves there. The operator's real
    ~/.agent-orchestrator is never touched.
  • A REAL_HOME is captured before the override and restored when
    running the full test suites, since vitest needs the operator's
    real config path to avoid cross-test contamination.
  • Re-run is idempotent — rm -rf $DEMO_HOME at the top recreates
    the sandbox from scratch.

Verified runs end-to-end on storage-redesign with exit code 0.

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

* demo: richer fixture — 2 projects, 6 sessions, real source trees

Earlier seed was a single empty repo with one session and a 2-line README.
Reviewers would dismiss it as not credible migration evidence.

New seed:
  • 2 source projects (myproject, frontend), each a real TS package layout
    with package.json, tsconfig.json, src/lib/, tests/, .gitignore, README,
    and 6 commits of history. 8 files per repo.
  • 6 sessions across the 2 hash dirs, in varied states:
      - ao-1 (working, agent-report state + report-watcher counters + PR
        fields — headline @ashish921998 flat-key fix in one record)
      - ao-2 (V1-archived, terminated, manually_killed)
      - ao-3 (stuck, with report-watcher trigger active)
      - my-orchestrator-1 (kind=orchestrator)
      - fe-1 (working, PR open with PR fields)
      - fe-2 (V1-archived, terminated, runtime_lost)
  • Real git worktree for ao-1 with an actual diff file —
    proves worktree migration moves files and rewrites git refs.
  • Pre-seeded global config.yaml lists both projects so the migrator
    has identity to project against.

Migration handles all 6 sessions (4 active + 2 archived → flattened) and
the 1 worktree. The verification step inspects ao-1.json post-migration
and asserts every flat agent-report / report-watcher key from the
@ashish921998 fix is present, with no nested wrapper objects.

Also fixes:
  • MIGRATED_PROJECT used to grab alphabetically-first directory which
    made the JSON read crash when frontend won — hardcoded to myproject.
  • Before-display referenced $HASH_DIR/archive but the actual archive
    location is $HASH_DIR/sessions/archive — corrected.

End-to-end verified: exit 0, "PASS — agent-report flat-key contract
preserved", 560/560 CLI + 981/981 core tests in the final summary.

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

* fix(migration): relink Claude Code session storage when worktrees move

Reported in PR #1466 QA: after `ao migrate-storage`, restoring a session
launches a fresh `claude` instance — chat history is gone.

Root cause: Claude Code keys session JSONLs by the encoded form of the
workspace cwd (~/.claude/projects/<encoded>/<session-uuid>.jsonl, where
encoded = cwd with `/` and `.` replaced by `-`, see toClaudeProjectPath
in agent-claude-code/src/index.ts). The migrator moves worktrees from
~/.agent-orchestrator/{hash}-{project}/worktrees/{sid} to
~/.agent-orchestrator/projects/{projectId}/worktrees/{sid}, which
produces a different encoded path. The agent's session JSONLs are still
at the old encoded path and stay orphaned. getRestoreCommand looks under
the new encoded path, finds nothing, returns null — and the caller
falls back to a fresh launch.

Fix: track every (oldWorkspacePath, newWorkspacePath) pair across both
migration phases (per-project migrateProject and the cross-project
moveStrayWorktrees), then call relinkClaudeSessionStorage after all
worktree moves complete. The relink renames each
~/.claude/projects/<old-encoded>/ → <new-encoded>/. Skip when source
doesn't exist (no Claude history) or target already exists (manual
reconciliation needed). Same step is invoked in reverse from
rollbackStorage so `--rollback` undoes the relink.

The encoding helper is duplicated locally in migration/storage-v2.ts to
avoid pulling the agent plugin into core/migration just for one string
transformation. Kept in sync by hand; if the plugin's encoding ever
changes, both copies need to update together.

Codex stores sessions date-sharded with the cwd embedded inside each
JSONL's session_meta line, so the same physical-rename trick doesn't
apply. Codex relinking is left as a follow-up — the comment in
relinkClaudeSessionStorage points at it.

Two regression tests added:
  • Happy path: V1 worktree at OLD encoded path with a JSONL inside
    Claude's projects dir; after migrateStorage the JSONL is at the
    NEW encoded path and the OLD dir is gone. claudeSessionsRelinked === 1.
  • Safety: target dir already exists at the new encoded path; migration
    skips the relink, neither dir is touched, claudeSessionsRelinked === 0.

Tests use HOME override to sandbox ~/.claude/ so the runner's real
agent-storage is never touched.

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

* fix(boundary): four cross-module seams flagged in PR #1466 review

- Migration: rewrite Codex rollout session_meta.cwd for moved
  worktrees so getRestoreCommand keeps finding the old thread.
  Mirrors the Claude relink with a single-line in-place rewrite.
- CLI start: stop adding the project to running.projects in the
  attach-to-existing-daemon branch. Lifecycle polling cannot be
  attached mid-flight, so claiming coverage made `ao spawn`
  silently suppress its "instance is not polling X" warning.
- CLI stop: defensively drop foreign sessions before the kill
  loop when a project arg is given. `sm.list(projectId)` already
  scopes, but the kill loop is destructive enough to deserve a
  consumer-side guard.
- Web DELETE /api/projects/[id]: validate the id through
  getProjectDir BEFORE calling cleanupManagedWorkspaces so a
  malformed key never reaches a workspace plugin.

Adds regression tests for each.

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

* fix(boundary): four more cross-module seams flagged in PR #1466 review

- Recovery actions (cleanup/escalate/recoverSession-on-max-attempts)
  now mutate the canonical lifecycle alongside the flat status. For
  V2 sessions readMetadataRaw derives status from lifecycle, so the
  prior flat-only writes were silently overridden on the next read.
- Targeted `ao stop <project>` no longer calls
  removeProjectFromRunning. The parent process's in-memory lifecycle
  worker keeps polling that project (a child CLI cannot reach into
  parent memory), so running.projects must keep listing it to remain
  truthful. The attach branch in `ao start <project>` now triggers
  on any project-id arg with a live daemon, regardless of
  running.projects content; the polling-not-attached warning fires
  only when the project is genuinely not in running.projects.
- `ao start` restore loop preserves last-stop.json for sessions that
  fail to restore (transient workspace/runtime errors) instead of
  clearing the only persisted record. Successful or fully-failed
  flows still clear it.
- New integration round-trip: migrate a Codex JSONL with the old
  worktree cwd, then call the real agent-codex.getRestoreCommand
  with the migrated workspacePath and assert it returns
  `codex resume <threadId>`.

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

* fix(review): four illegalcall PR review findings on PR #1466

- writeMetadata sites in session-manager (spawn + ensureOrchestrator)
  spread `buildLifecycleMetadataPatch` (string-typed patch) into a
  typed SessionMetadata literal, which silently wrote `lifecycle` as
  a JSON string and made freshly-spawned sessions read with
  `lifecycle: undefined` until the first poll round-trip.
  Override the spread with the canonical object form and drop the
  metadata.ts safety net that compensated for the bug.
- Migration archive-flatten regex `/^([a-zA-Z0-9_-]+?)_\d/` was lazy
  and captured `team` for `team_1-7_<ts>.json`. Replace with an
  anchor on the timestamp suffix in both call sites so any sessionId
  containing `_<digit>` is parsed correctly.
- Migration duplicate-sessionId resolution renamed-the-loser to
  `${sessionId}__from-${hash}` rather than silently dropping it.
  Both records survive in V2; the rename is logged.
- `running-state.ts` writes `running.json` and `last-stop.json` via
  `atomicWriteFileSync` (temp+rename) so a crash mid-write cannot
  leave torn JSON that orphans an alive AO process or erases the
  next-start restore prompt.

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

* fix(metadata): preserve corrupt session JSON before overwriting

mutateMetadata used to merge against an empty record and atomically
rewrite when parseMetadataContent returned null on corrupt JSON. The
original bytes were lost — the user had no signal anything was wrong,
the file just became "not corrupt anymore — and missing fields".

Side-rename the file to `<path>.corrupt-<ts>` and warn before the
rewrite so forensics survive. Adds two regression tests and drops the
stale STORAGE_REDESIGN.md reference comment.

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

* chore(lint): fix 4 errors introduced by recent boundary fixes

- storage-v2.ts:656,1453 — drop unnecessary `\-` escape inside `[…]`
  character class (no-useless-escape).
- storage-v2.ts:979 — replace inline `import("node:fs").Dirent` type
  annotation with a top-level `Dirent` named import (consistent-type-imports).
- recovery/actions.ts:11 — merge the second `../types.js` `import type`
  into the existing line (no-duplicate-imports).

Tests + typecheck unchanged (991 passing).

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

* fix(cli): propagate reloaded config out of resolveProject after add

The interactive "Add <cwd>" menu path in `resolveProject` registers
the project in the global config (with a hashed id like
`mail-automate_3e4d45c2ba`) and reloads the config internally to
fetch the new project entry. It returned only `{projectId, project}`,
so the outer caller kept the pre-add `config` reference — which has
no key for the just-added project.

Downstream that surfaced as:

    Failed to start lifecycle worker:
    Unknown project: mail-automate_3e4d45c2ba

because `ensureLifecycleWorker(config, projectId)` checks
`config.projects[projectId]` against the stale config.

`resolveProject` and `resolveProjectByRepo` now also return the
(possibly reloaded) config; the three call sites pick it up via
`({ projectId, project, config } = await resolveProject(...))`.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-28 17:55:53 +05:30
yyovil b086908f60
add zsh completion support for ao (#1374)
* feat: add zsh completion for ao (#1371)

Add a generated zsh completion command and dynamic completion backend so ao can tab-complete projects and session IDs without relying on jq or brittle text parsing. Document standard zsh and Oh My Zsh install paths, and cover the new flow with CLI tests.

* fix(cli): address copilot completion review feedback for PR 1374

* fix completion and harden local workflow parsing

* Update packages/cli/src/lib/completion.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix completion regressions and agent-ci review feedback

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-04-24 03:48:25 +05:30
harshitsinghbhandari b0d0994efd fix: improve agent plugin cost accounting and restore safety 2026-04-18 13:56:59 +05:30
harshitsinghbhandari dd83a11503 fix: model missing activity evidence explicitly (#122)
Represent missing activity probes as first-class signal states so lifecycle inference only treats valid idle evidence as proof. This prevents false stuck transitions, keeps API/UI lifecycle truth aligned, and makes root monorepo verification deterministic by serializing recursive build and typecheck.
2026-04-17 19:28:56 +05:30
Dhruv Sharma ab1e4fb069
Merge pull request #1180 from yyovil/add/type-resolution
Add node type resolution for non-web packages
2026-04-13 19:56:36 +05:30
yyovil 9bed49d453 fix: scope node types to node packages 2026-04-13 18:25:21 +05:30
i-trytoohard 36a64c98b7
chore: bump all package versions to 0.2.5 (#1190)
* chore: release 0.2.5

Realign main with npm registry after off-branch publish of 0.2.3/0.2.4.
Bump all 21 linked packages to 0.2.5 and cherry-pick the startup-grace-period
fix for #989 (was in 5e4244a8 but never merged to main).

Also sync non-linked plugin versions (notifier-discord, notifier-openclaw,
scm-gitlab, tracker-gitlab) to their current npm versions.

* Revert "chore: release 0.2.5"

This reverts commit eb17f32834.

* chore: bump all package versions to 0.2.5, remove release workflow

- Bump all 25 packages to 0.2.5 to realign with npm registry
- Update package-version test to expect 0.2.5
- Remove stale .changeset/linear-spawn-branch-name.md
- Delete .github/workflows/release.yml (changesets-based NPM publish)

---------

Co-authored-by: Prateek <karnalprateek@gmail.com>
Co-authored-by: AO Bot <ao-bot@composio.dev>
2026-04-13 05:47:08 +05:30
Prateek 27712442f8 fix: restore GitHub repo URLs to ComposioHQ/agent-orchestrator — only npm scope changed 2026-04-09 16:00:32 +00:00
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
Harsh Batheja be0ce0baac
fix(agent-claude-code): return idle state for freshly spawned sessions with no JSONL file (#891)
* fix(agent-claude-code): return idle state when no JSONL session file exists

Freshly spawned sessions had no Claude Code JSONL file yet (Claude Code
doesn't create it until the first conversation), causing getActivityState
to return null → displayed as 'unknown' in ao status.

When the process is running but no session file exists, return
{ state: 'idle', timestamp: now } so the dashboard shows the correct
state immediately after spawn.

Closes #883

* fix(agent-claude-code): use session.createdAt for idle timestamp when no JSONL file

Using new Date() as the timestamp caused isIdleBeyondThreshold to always
compute ~0ms, preventing stuck detection from ever firing for sessions that
hang before creating a JSONL file. Using session.createdAt correctly
represents when the session began, allowing stuck detection to eventually
trigger.
2026-04-03 19:44:59 +05:30
Harsh Batheja df8395c3ec
feat: standardize agent plugins — shared hooks, activity JSONL, backfill aider/opencode (#755)
* feat: standardize agent plugins with shared hooks, activity JSONL, and CLAUDE.md

- Add CLAUDE.md with full project context and agent plugin implementation standards
- Extract shared PATH-wrapper metadata hooks into @composio/ao-core (agent-workspace-hooks.ts)
- Backfill Aider + OpenCode: setupWorkspaceHooks, postLaunchSetup, getSessionInfo, getRestoreCommand
- Add recordActivity method to Agent interface for terminal-derived JSONL writing
- Create activity-log.ts in core: appendActivityEntry, readLastActivityEntry
- Lifecycle manager calls recordActivity before getActivityState for agents that implement it
- Upgrade detectActivity in Aider/OpenCode with real terminal prompt/permission patterns
- Upgrade Codex getActivityState to parse JSONL entry types (6 states, up from 2)
- Replace duplicated normalizePermissionMode with shared normalizeAgentPermissionMode from core
- Remove ~200 lines of duplicated shell wrapper code from Codex plugin
- Add git wrapper detection for existing branch switches (parity with Claude Code hooks)
- 484 tests passing across all 4 agent plugins

* chore: unignore CLAUDE.md and AGENTS.md, slim down AGENTS.md to pointer

- Remove CLAUDE.md and AGENTS.md from .gitignore (both should be tracked)
- Slim AGENTS.md from 96 to 30 lines — commands, TL;DR, key files
- Full context now lives in CLAUDE.md; AGENTS.md points there

* fix: eliminate redundant double file read in readLastActivityEntry

Remove the readLastJsonlEntry call that was only used as a null-check,
then immediately discarded before re-reading the same file from scratch.
Now performs a single open + stat + tail-read per poll cycle.

* fix: remove duplicate case-insensitive regex in OpenCode detectActivity

The \(y\)es.*\(n\)o pattern with /i flag was identical to the preceding
\(Y\)es.*\(N\)o/i check — remove the redundant line.

* fix: use zero-initialized buffer and slice to bytesRead in readLastActivityEntry

Replace Buffer.allocUnsafe with Buffer.alloc and slice the result to
actual bytesRead, preventing uninitialized heap data from being parsed
if the file shrinks between stat() and read().

* fix: add staleness cap for waiting_input/blocked and deduplicate recordActivity

- Add ACTIVITY_INPUT_STALENESS_MS (5 min) cap so stale waiting_input/blocked
  entries don't keep sessions stuck in needs_input on the dashboard forever.
- Extract checkActivityLogState() into core — shared by aider, opencode, codex.
- Extract classifyTerminalActivity() into core — deduplicates the identical
  recordActivity logic across all three plugins.

* fix: prioritize native Codex JSONL over AO activity log in getActivityState

Reorder detection so Codex's native 6-state JSONL (approval_request,
error, tool_call, etc.) is checked first. AO activity JSONL from
terminal parsing is now a fallback only for waiting_input/blocked states
that the native JSONL may not have captured. Previously the AO log was
always fresh (written every poll cycle by recordActivity) and shadowed
the richer native detection entirely.

* fix: restrict AO activity JSONL to waiting_input/blocked only

checkActivityLogState now only returns results for waiting_input/blocked
states. Non-critical states (active/ready/idle) return null, forcing
callers to fall through to their native signals (git commits, chat
history, OpenCode API, Codex native JSONL). This prevents the lifecycle
manager's recordActivity writes (which refresh mtime every poll cycle)
from shadowing richer detection methods and breaking stuck-detection.

* fix: prevent stale idle timestamp in aider and skip flags in git wrapper

- Remove Aider's fallback that returned idle with activityResult.modifiedAt
  (always fresh due to recordActivity writes). Now returns null when no
  git commits or chat history are found, letting the lifecycle manager
  handle stuck-detection correctly.
- Fix git wrapper catch-all case to skip flag arguments (e.g. -B) and
  look at $3 for the actual branch name.

* fix: add mtime fallback for empty Codex JSONL and remove unused exports

- When the native Codex session file exists but readLastJsonlEntry returns
  null (empty/unparseable), fall back to stat-based mtime detection instead
  of losing activity detection entirely.
- Remove unused exports getActivityLogPath and ACTIVITY_INPUT_STALENESS_MS
  from @composio/ao-core barrel — they are only used internally.

* fix: opencode activity state detection and CLAUDE.md agent plugin standards

- Fix session ID capture to handle both session_id (snake_case) and
  sessionID (camelCase) from OpenCode 1.3.x JSON responses
- Replace broken --command true with -- noop for session creation
  (true is not a valid OpenCode command since 1.3.x)
- Add JSONL mtime fallback in getActivityState so active/ready/idle
  states work even when findOpenCodeSession returns null
- Rewrite CLAUDE.md activity detection section with the full
  getActivityState contract, mandatory JSONL mtime fallback pattern,
  and 8 required tests every agent plugin must implement

* fix: opencode --command true flag and activity JSONL mtime staleness

- Fix opencode getLaunchCommand to use `--command true` instead of `-- noop`
  (aligns with test expectations and opencode CLI docs)
- Fix checkActivityLogState to use entry.ts instead of file mtime for
  staleness checking — recordActivity refreshes mtime every poll cycle,
  which prevented stale waiting_input/blocked entries from being detected
- Fix opencode getActivityState fallback to use entry state directly
  instead of re-deriving from mtime, which always returned "active"
  because recordActivity refreshes the file every cycle
- Update tests to reflect new entry-state-based fallback behavior

* fix: deduplicate recordActivity writes and restore mtime-based fallback

recordActivity was writing to the JSONL every poll cycle (~30s), which
kept refreshing the file mtime and prevented the JSONL mtime fallback
in getActivityState from ever reaching "ready" or "idle".

Fix: skip writes when the state hasn't changed and the last entry is
<20s old. This keeps mtime fresh during active work (writes every
20-30s, within the 30s activeWindow) but lets it age naturally when
the agent goes quiet.

Also restores the mtime-based age classification in the JSONL fallback
(active/ready/idle by mtime age) instead of returning the entry state
directly, which was always "active" since that's what recordActivity
writes.

Applied to both OpenCode and Aider plugins. Updated CLAUDE.md with
the dedup pattern and rationale.

* fix: align integration tests with opencode `-- noop` launch command

Update 9 test expectations from `--command true` to `-- noop` to match
the reverted getLaunchCommand implementation.

* fix: add JSONL mtime fallback to Aider getActivityState

When git commits and chat history are both unavailable (e.g. early
session startup), Aider's getActivityState now falls back to the AO
activity JSONL mtime for active/ready/idle classification — matching
OpenCode's existing step 3 fallback. Previously it returned null,
leaving the dashboard with no activity signal.

* fix: add write deduplication to Codex recordActivity

Add the same dedup logic that Aider and OpenCode already have — skip
writes when the state hasn't changed and the last entry is recent
(<20s). Prevents unbounded file growth and stale mtime refreshes.

* refactor: extract shared recordTerminalActivity into core

Move the duplicated recordActivity logic (classify + dedup + append)
from all three plugins into a shared `recordTerminalActivity` function
in `@composio/ao-core/activity-log`. Each plugin's `recordActivity`
is now a thin wrapper that delegates to the shared function.

Add core tests for classifyTerminalActivity, checkActivityLogState,
and recordTerminalActivity (10 tests).

* fix: validate JSONL entry fields, handle invalid dates, consistent operators

- Validate required fields (ts, state, source) before casting parsed
  JSON to ActivityLogEntry — prevents malformed entries from propagating
- Guard against invalid Date parsing in checkActivityLogState — returns
  null instead of comparing against NaN
- Use <= instead of < in Aider chat-history threshold comparisons to
  match OpenCode and Aider's own JSONL fallback path

* fix: use --command true for opencode run, validate sed key parameter

- Replace `-- noop` with `--command true` in opencode getLaunchCommand
  so the bootstrap uses a valid command
- Validate metadata key against [a-zA-Z0-9_-]+ in the git wrapper's
  update_ao_metadata to prevent sed metacharacter injection

* fix: extract DEFAULT_ACTIVE_WINDOW_MS constant, clarify Codex recordActivity

- Extract magic number 30_000 into DEFAULT_ACTIVE_WINDOW_MS constant in
  core types, used by Aider and OpenCode for active/ready thresholds
- Clarify in CLAUDE.md that Codex implements recordActivity as a safety
  net for when its native JSONL is missing/unparseable, not redundantly

* fix: add JSONL mtime fallback to Codex getActivityState

When native Codex session file is missing but AO JSONL has data,
derive active/ready/idle from JSONL mtime instead of returning null.
Matches the fallback pattern already in Aider (step 4) and OpenCode
(step 3).

* fix: validate ActivityState and source values when parsing JSONL entries

Validate that `state` is one of the known ActivityState values and
`source` is "terminal" or "native" before constructing the entry.
Construct the entry explicitly instead of using unsafe double cast.

* fix: wrap getOutput + recordActivity in try-catch to protect getActivityState

If runtime.getOutput() throws (e.g. tmux unresponsive), the error
previously propagated to the outer catch, skipping getActivityState
entirely. Now the entire recordActivity preamble is wrapped in its
own try-catch so getActivityState always runs.

* chore: add .ao/ to gitignore

* chore: clean up gitignore comment

* test: add coverage for activity-log and agent-workspace-hooks

- activity-log: test readLastActivityEntry (missing file), invalid
  entry.ts in checkActivityLogState, blocked state path
- agent-workspace-hooks: test buildAgentPath (dedup, defaults,
  ordering), setupPathWrapperWorkspace (create/skip wrappers,
  AGENTS.md create/skip)

Raises diff coverage from 39% toward 80% threshold.

* test: add real file I/O tests for readLastActivityEntry and recordTerminalActivity

Test readLastActivityEntry with actual temp files: valid entries,
empty file, invalid JSON, invalid state, missing fields, multi-line.
Test recordTerminalActivity dedup logic and actionable state bypass.

* fix: add activeWindow threshold to Codex native JSONL state detection

Action entries (tool_call, user_input, exec_command) now use the 30s
active window: <=30s is "active", 30s-5min is "ready", >5min is "idle".
Previously these skipped "ready" entirely, going straight from "active"
to "idle" at the 5min threshold.

* fix: add activeWindow threshold to Claude Code native JSONL state detection

Same fix as Codex — action entries (user, tool_use, progress) now use
the 30s active window for consistent 3-state classification across
all agent plugins: <=30s active, 30s-5min ready, >5min idle.

* fix: handle truncated JSONL, add exited state, fix session lookup and dedup window

- readLastActivityEntry: increase tail buffer to 4KB, skip truncated
  first line when reading from offset, try lines from end on parse error
- Add "exited" to valid ActivityState set in JSONL validation
- findOpenCodeSession: pick most recently updated session when multiple
  title matches exist, preventing stale session binding
- Increase dedup window from 20s to 60s so mtime can age past the 30s
  active window between writes, allowing "ready" state to be reached

* fix: use entry state for JSONL fallback, write AGENTS.md to .ao/, revert dedup to 20s

- Replace mtime-based active/ready/idle derivation in all 3 plugin
  fallbacks with direct entry.state + entry.ts usage. This eliminates
  the fundamental conflict between write deduplication and mtime
  freshness — the entry already has the correct detected state.
- Revert dedup window to 20s (purely I/O optimization, no longer
  affects state detection since mtime is not used)
- Write AO session context to .ao/AGENTS.md (gitignored) instead of
  modifying the repo-tracked AGENTS.md, preventing dirty worktree state

* fix: reorder Codex fallback chain so AO JSONL is checked before stat mtime

When native JSONL exists but can't be parsed, the stat() fallback
previously returned early, skipping AO JSONL waiting_input/blocked
detection and the ready state. Now it falls through to AO JSONL first,
then uses stat mtime as a last resort with proper 3-state classification.

* fix: re-validate canonicalized ao_dir against trusted roots

After resolving symlinks with pwd -P, re-check real_ao_dir against
the trusted root allowlist. Prevents paths like /tmp/../../home/user
from passing the pre-canonicalization check then escaping to arbitrary
directories after symlink resolution.

* fix: update tests for .ao/AGENTS.md location and remove unused vi import

- Update Codex setupWorkspaceHooks tests to expect .ao/AGENTS.md
  instead of workspace root AGENTS.md
- Remove unused vi import from activity-log test (lint error)

* fix: add age-based decay to JSONL entry fallback via getActivityFallbackState

Extract getActivityFallbackState in core — reclassifies entry state
based on entry.ts age (active→ready→idle) so old entries don't stay
as "active" forever when recordActivity stops being called. All three
plugins now use this shared helper for their JSONL fallback paths.

* fix: apply staleness cap to actionable states in getActivityFallbackState

Stale waiting_input/blocked entries (older than ACTIVITY_INPUT_STALENESS_MS)
are now treated as idle in the fallback, preventing them from bypassing
the staleness filtering in checkActivityLogState.

* fix: respect entry state as ceiling in getActivityFallbackState

Age-based decay can only demote (active→ready→idle), never promote.
A fresh "idle" entry stays "idle" instead of being reclassified as
"active" — the detected state from terminal output is authoritative.

* docs: update CLAUDE.md to match current activity detection implementation

- Replace inline recordActivity dedup example with recordTerminalActivity delegation
- Replace mtime-based fallback example with getActivityFallbackState
- Update step 4 description: entry state + age-based decay, not mtime
- Add new core exports to utilities section
- Document .ao/AGENTS.md location and setupPathWrapperWorkspace
- Update required test list for entry-based fallback

* fix: skip metadata helper rewrite when version marker matches

Move ao-metadata-helper.sh write inside the needsUpdate check so it's
only rewritten when wrapper scripts are outdated, not on every call.

* fix: update Codex test for metadata helper skip when version matches

Metadata helper is now inside the needsUpdate check, so when the
version marker matches, no wrapper writes occur (including helper).
2026-04-01 21:50:07 +05:30
github-actions[bot] c7d6634839 chore: version packages 2026-03-20 15:47:55 +00:00
suraj_markup 178af32682
Merge pull request #463 from suraj-markup/feat/onboarding-improvements
feat: reduce onboarding friction — auto-init, add-project, dashboard publishing, error hardening
2026-03-19 01:21:34 +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 a1a9966ed5 Fix CI failures: lint eqeqeq + test manifest displayName
- Change != null to !== undefined && !== null in caller-context.ts and
  session-manager.ts (3 locations) to satisfy eqeqeq lint rule
- Add displayName field to all 4 agent plugin test manifest assertions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 13:55:08 +05:30
suraj-markup 694681f728 Fix review issues: ESM compat, prompt accuracy, port registration
- Replace require() with execFileSync in all 4 agent plugin detect()
  functions — fixes ReferenceError in ESM-only environments
- Remove non-existent -p flag from orchestrator prompt spawn/batch-spawn
  docs — prevents orchestrator agent from generating broken commands
- Return actual port from runStartup() and pass to register() — fixes
  running.json storing wrong port when auto-escalation picks a free port

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 05:49:53 +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
deepak 367f1484c6 fix: use space-padded regex for cd-prefix stripping
Updates the cd-prefix stripping regex to require a space before the
delimiter (&& or ;). This allows paths containing & or ; characters
to be matched correctly while still finding the command separator.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 11:24:46 +00:00
deepak 3575643473 fix: simplify cd-prefix regex to avoid shell quoting confusion
Store the regex pattern in a variable and remove confusing single quotes
from the character class. The pattern now uses [^&;]* to explicitly
exclude & and ; without mixing shell quoting into the regex pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 05:07:28 +00:00
deepak 59633e45b4 fix(agent-claude-code): detect cd-prefixed gh/git commands and use relative hook path 2026-03-08 10:42:45 +00:00
prateek ef40c529f8
fix: handle permissions=skip correctly in codex plugin (#337)
* fix: handle permissions=skip correctly in codex plugin

* refactor: rename permission mode to permissionless and align agent mappings

---------

Co-authored-by: Jayesh Sharma <wjayesh@outlook.com>
2026-03-07 20:27:01 +05:30
prateek 128b94a932
fix: cache ps output across sessions to fix 51s dashboard load (#244)
* fix: cache ps output across sessions to fix 51s dashboard load

findClaudeProcess() was calling `ps -eo pid,tty,args` once per session.
On machines with ~1150 processes, each `ps` call takes 30-35s. With 18
sessions enriched in parallel, this caused /api/sessions to take 51+
seconds despite the 2s per-session timeout.

Add a module-level TTL cache (5s) with in-flight deduplication so `ps`
is called at most once regardless of session count. Also reduce timeouts
from 30s to 5s — stale process data isn't useful.

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

* fix: guard ps cache callbacks against stale overwrites

The .then() and catch callbacks in getCachedProcessList() could clobber
a newer in-flight cache entry if the TTL expired and a new request
replaced psCache while the old one was still pending. Both now check
`psCache?.promise === promise` before writing.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 20:41:03 +05:30
prateek e5105133c5
Default dangerouslySkipPermissions to true (#226)
* docs: add demo video and article links to README

Add tweet screenshot for the video demo prominently after the intro,
and link to the full article thread. Replaces the TODO placeholder.

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

* docs: use article screenshot for README article link

Replace text-only article link with clickable screenshot showing
the article title, preview image, and engagement stats.

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

* docs: replace demo video screenshot with higher quality version

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

* Default dangerouslySkipPermissions to true for autonomous agent operation

Spawned agents need to run CLI commands without permission prompts. Changed
the agentConfig.permissions schema default from undefined to "skip" so
--dangerously-skip-permissions is included by default. The orchestrator
session is hardcoded to "skip" regardless of config since it must always
run ao CLI commands autonomously.

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

* Default agentConfig to {} so permissions default propagates

When agentConfig is absent from YAML, .optional() leaves it undefined,
so project.agentConfig?.permissions evaluates to undefined instead of
"skip". Change to .default({}) so Zod always constructs the object and
applies the inner permissions default.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:04:50 +05:30
prateek 91dd7cc15f
fix: keep Claude Code interactive after initial prompt (#145)
* fix: keep Claude Code interactive after initial prompt

Claude Code's -p flag runs in one-shot mode (exits after responding),
which prevents follow-up messages via `ao send`. Instead, launch Claude
interactively and deliver the initial prompt post-launch via
runtime.sendMessage().

Adds `promptDelivery` property to the Agent interface so each agent
plugin can declare whether prompts should be inlined in the launch
command or sent after the agent starts.

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

* fix: make post-launch prompt delivery non-fatal and add test coverage

- Move sendMessage call outside the try/catch that destroys the session.
  A prompt delivery failure should not kill a running agent — user can
  retry with `ao send`.
- Add tests: no-prompt + post-launch agent, sendMessage failure resilience,
  5s delay verification, systemPrompt/systemPromptFile alongside omitted -p.

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

* test: add integration test for prompt delivery (proves bug and fix)

Two real-Claude integration tests that contrast:
1. `-p` mode: Claude exits after responding (the bug)
2. Interactive + sendMessage: Claude stays alive, follow-up works (the fix)

Runs in CI with ANTHROPIC_API_KEY. Skips when prerequisites missing.

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

* fix(test): skip interactive test without auth, improve TUI readiness detection

The integration test failed in CI because interactive Claude requires
full login auth (not just ANTHROPIC_API_KEY). Skip the interactive suite
when `claude auth status` reports not logged in.

Also fix local flakiness: replace blind 5s sleep with polling for
Claude's TUI prompt character (❯) before sending the first message,
and increase scrollback capture from 200 to 500 lines.

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

* fix(test): skip interactive test in CI, fix TUI readiness detection

The interactive test ran in CI despite hasInteractiveAuth() — Claude
reports logged in when ANTHROPIC_API_KEY is set, but interactive mode
requires OAuth. Use `!process.env.CI` as the skip condition instead.

Also fix waitForTuiReady false positive: the OAuth screen's
"Paste code here if prompted >" matched the `>` regex. Now checks
the last non-empty line for Claude's specific ❯ prompt character,
and bails early if the OAuth/login screen is detected.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 18:11:06 +05:30
prateek 40c1906d41
feat(web): redesign dashboard, session detail, and orchestrator terminal (#125)
* docs: add design research artifacts — briefs, token reference, screenshots

Comprehensive design research package for the ao dashboard, session
detail page, and orchestrator terminal. Produced via competitive analysis
of 14 products (Linear, Vercel, Railway, Fly.io, Inngest, WandB, LangSmith,
Supabase, and more) + Playwright CSS extraction from live sites + full
codebase audit.

Artifacts:
- docs/design/design-brief.md            Main design brief (v2, Playwright-updated)
- docs/design/session-detail-design-brief.md   /sessions/[id] design spec
- docs/design/orchestrator-terminal-design-brief.md  Orchestrator page spec
- docs/design/token-reference.css        Drop-in CSS replacement for globals.css
- docs/design/competitive-analysis-raw.md  Raw research notes, all 14 sites
- docs/design/design-brief-v1.md         Original text-only brief (pre-Playwright)
- docs/design/README.md                  Index + research methods summary
- docs/design/screenshots/linear-homepage.png   Playwright-captured screenshot
- docs/design/screenshots/railway-homepage.png  Playwright-captured screenshot

Key findings:
- Linear CSS token values verified via Playwright (body bg #08090A, accent
  #7070FF, Berkeley Mono monospace, type scale, radius, transitions)
- Recommended palette: #0C0C11 base (blue-cast dark vs current GitHub #0d1117)
- Highest-impact change: load Inter Variable via next/font/google
- Orchestrator terminal needs visual differentiation (violet accent, status strip)
- token-reference.css is ready to drop into packages/web/src/app/globals.css

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

* feat(web): redesign dashboard, session detail, and orchestrator terminal

Implements a cohesive dense dark-mode design system across all three main views.

- New color token palette: #0c0c11 base, #141419 surface, #1c1c25 elevated
- Accent blue #5b7ef8, status semantics (ready/error/attention/working/idle/done)
- Violet accent #a371f7 reserved for orchestrator
- Inter Variable + JetBrains Mono loaded via next/font with CSS variables
- activity-pulse keyframe for live agent dots

- AttentionZone header: dot + label + flex divider + count pill + chevron
- Sessions laid out in responsive 1→2→3 column grid
- Solid green merge button (translateY hover), no confirm() dialog

- Breadcrumb nav: ← Agent Orchestrator / {session-id} [orchestrator badge]
- CSS 8×8px activity dot with pulse animation replaces emoji labels
- Merge-ready state: green-bordered banner with checkmark icon
- Orchestrator sessions show zone counts strip (merge/respond/review counts)

- xterm.js dark theme (#0a0a0f bg, #d4d4d8 fg, full 16-color ANSI palette)
- variant prop: "agent" (blue cursor) vs "orchestrator" (violet cursor)
- Dynamic height prop instead of fixed 600px; fullscreen toggle with SVG icons

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

* refactor(web): strip rainbow stats, clean header, IBM Plex Sans typography

- Replace Inter with IBM Plex Sans (technical tool aesthetic, distinctive numerics)
- Replace 4-color big-number stats bar with a single compact inline status line
  in the header: "35 sessions · 1 working · 9 PRs" — no decorative colors
- Remove the two-tone "Agent (blue) Orchestrator (white)" title — just "Orchestrator"
- Remove ClientTimestamp (useless) — replaced by orchestrator nav link
- Zone headers: colored dot only (semantic), neutral uppercase label, plain count
  — removes the rainbow-colored label text that read as a widget template
- Add subtle radial gradient glow at top of page for depth

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

* feat(web): kanban layout, amber accent, full-width, bigger stats

- Switch accent from blue (#5b7ef8) to amber/gold (#d18616) throughout
- Replace grid layout with horizontal Kanban columns for active zones
  (merge, respond, review, pending, working), Done stays full-width below
- Remove max-w-[1100px] constraint — full viewport width
- Header stats numbers 20px bold (was 12px), orchestrator link is now a
  visible bordered button
- AttentionZone gains variant="column" for Kanban mode (compact header
  with count pill, vertical card stack)
- Update all hardcoded rgba(91,126,248,...) in SessionCard to amber

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

* fix(web): layout, alert sizing, column order, button feel

- Kanban column order: working→pending→review→respond→merge
  (left = in progress, right = ready to ship)
- Columns use flex-1 min-w-[200px] to fill available width
  instead of fixed 260px leaving half the page empty
- Alert badges: inline-flex wrapper prevents stretching to full
  row width when wrapping
- Terminal button: add bg-subtle fill so it reads as a button
- PR number (#91): remove opaque pill background, now plain
  amber text link — clearly a hyperlink
- Merge PR button: pt-0.5 spacer above the action area

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

* fix(web): don't cache rate-limited partial PR data

When GitHub rate limits fire, enrichSessionPR was caching the
bad partial data (0 additions, CI failing) for 60 seconds, causing
the dashboard to show incorrect data for the full TTL window.

- Skip cache write when majority of API calls failed
- Downgrade console.error → console.warn (this is handled/expected)

The next page refresh will retry live API calls, so data recovers
as soon as the rate limit window resets.

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

* feat(web): graceful GitHub API rate limit handling in UI

When the GitHub plugin hits rate limits, the dashboard now:

- Shows a single amber banner: "GitHub API rate limited — PR data
  (CI status, review state, sizes) may be stale. Will retry on
  next refresh."
- Hides CI badge, review decision, and size pill on PR cards
  (they'd show wrong values: +0 -0 XS, CI failing)
- Shows a subtle "⚠ PR data rate limited" note on affected cards
  instead of misleading alert badges
- Skips CI/review/conflict-based attention zone classification
  for rate-limited PRs (prevents sessions moving to Review due
  to phantom "CI failing" from the fallback value)
- Doesn't cache partial rate-limited data so next refresh retries
  live API calls as soon as the rate limit window resets

What still works when rate limited:
- Session ID, title, branch, PR number/link
- Session activity status (working/spawning/etc.)
- Merge button if mergeability was already cached
- Restore/terminate/send actions

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

* feat(web): dashboard redesign — glassmorphism, Kanban, rate-limit handling, perf fix

Design:
- Kanban layout: active zones as flex columns (working→pending→review→respond→merge),
  Done as full-width grid below
- GitHub dark color palette (main's tokens) with glassmorphic card surfaces
  (rgba bg + backdrop-blur) and subtle blue/violet body gradient
- Activity state shown as labeled pill (● active / ● idle etc.) instead of bare dot
- Session card: title on its own row, larger font, inline-flex alert badges (no stretch)
- PR number rendered as plain accent link, not a blue pill badge
- Terminal button has background fill to feel like a button
- Info circle icon replaces alarming warning triangle for rate-limit indicators
- "1 working" → "1 active" in header stats
- PR table constrained to max-w-[900px] and centered
- Orchestrator session no longer uses purple accent

Rate limiting:
- isPRRateLimited() helper; getAttentionLevel() skips PR classification when limited
- Rate-limited banner in Dashboard; suppressed CI/size/review badges in PRStatus
- SessionCard shows subtle "PR data rate limited" indicator; getAlerts() returns []
- serialize.ts: rate-limited enrichment results cached for 5 min (not 60s) to stop
  retrying 168 failing API calls every minute

Performance:
- page.tsx: 4s hard timeout on PR enrichment — serves stale data fast instead of
  blocking SSR for 75s under rate limiting
- cache.ts: TTLCache.set() accepts optional ttl override for per-entry control

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

* fix: suppress stale size/CI/review in PR table when rate limited

PRTableRow now shows "—" for size, CI, and review columns when GitHub
API is rate limited, matching the card view which already hides these.
Prevents misleading "+0 -0 XS" size and "needs review" labels from the
default fallback values.

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

* feat: 3D card effect with depth shadow and top-edge shine

Cards now clearly pop against the dark background:
- Solid gradient bg (rgba(28,36,47) → rgba(18,23,31)) instead of
  near-invisible rgba(22,27,34,0.8) surface
- Layered box-shadow: contact shadow + diffuse depth + inset top highlight
  that simulates light hitting the card's top edge (the "shine")
- Hover: card lifts 2px with deeper shadow
- Merge-ready: green-tinted bg with green ambient glow + stronger lift on hover

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

* fix: restore text legibility inside session cards

The darker solid card gradient made muted/secondary text nearly
invisible — #484f58 (text-muted) had only ~2:1 contrast on the
new card bg. Override the color tokens locally within .session-card
to GitHub's established dark-mode legibility values:

  --color-text-muted:     #484f58 → #656d76  (3.8:1 on card bg)
  --color-text-secondary: #7d8590 → #8b949e  (6.2:1 on card bg)
  --color-text-tertiary:  #484f58 → #656d76

Scoped to .session-card so the rest of the UI is unchanged.

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

* fix: address bugbot comments — fonts, review zone, ActivityDot, orchestrator btn

- layout.tsx: add IBM Plex Sans weight 700 (was missing, font-bold falling
  back to 600)
- DirectTerminal.tsx: use "IBM Plex Mono" instead of unloaded "JetBrains Mono"
- SessionDetail.tsx: add review zone to OrchestratorStatusStrip (was omitted,
  sessions with CI failures were invisible in the strip)
- ActivityDot.tsx: extract shared component, remove duplicate implementations
  in SessionCard.tsx and SessionDetail.tsx
- Dashboard.tsx: redesign orchestrator button with 3D glass style matching
  card aesthetic (blue-tinted bg, depth shadow, hover lift)

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

* fix(web): lint — eqeqeq, duplicate import, unused var

- ActivityDot.tsx: != → !== (eqeqeq rule)
- PRStatus.tsx: merge duplicate @/lib/types imports into one
- SessionCard.tsx: remove unused activityIcon import

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

* feat(web): elevate session detail + orchestrator page design

- Nav: glass backdrop-blur effect with chevron back link
- Header: detail-card 3D treatment with left-border accent keyed to activity color
- Meta chips: bordered pill style with subtle bg instead of flat text
- Status tag: pill badge for status instead of plain text
- PR card: detail-card 3D treatment, border-color reflects PR state
- PR merged badge: purple pill instead of gray text
- Unresolved count: red pill badge in section header
- Blockers section: renamed "Issues" → "Blockers"
- Terminal section: colored bar indicator instead of plain label
- Orchestrator status strip: total agent count + per-zone colored pills
- globals.css: add .nav-glass and .detail-card classes

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

* fix(web): fetchZoneCounts parses body.sessions, delayed 2s to avoid contention

The /api/sessions endpoint returns `{ sessions: [...] }` not a bare array.
fetchZoneCounts was treating the whole response object as an array, so
zone counts were always zero on the orchestrator detail page.

Also delays the initial fetchZoneCounts call by 2s so it doesn't contend
with the session fetch on page load (both hit /api/sessions which is slow
when GitHub enrichment is running).

Also includes: Playwright kill-Chrome-for-Testing tip in CLAUDE.md,
toned-down detail-card shadow in globals.css.

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

* perf+test(web): cache-first PR enrichment, skip exited sessions, fix component tests

Performance improvements:
- enrichSessionPR() now accepts cacheOnly option and returns boolean
- /api/sessions/[id]: serve from cache immediately, only block on first load
- /api/sessions: skip PR enrichment for EXITED sessions (no longer changing)
- cache: increase default TTL from 60s to 5 minutes

Test fixes (match redesigned SessionCard + AttentionZone):
- "restore session" (header) → "restore"; expanded panel still shows "restore session"
- "merge PR #N" → "Merge PR #N" (capital M)
- "CI status unknown" → "CI unknown"
- "ask to fix CI" / "ask to fix CI" → "ask to fix"
- "terminate session" → "terminate"
- Zone labels: RESPOND/WORKING/DONE → Respond/Working/Done (CSS uppercase is visual only)
- "working" zone no longer collapsed by default; collapse tests now use "done" zone

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

* feat(core): ActivityDetection with timestamp propagation

- Add ActivityDetection interface { state, timestamp? } to types.ts
- Agent getActivityState() returns ActivityDetection | null instead of
  ActivityState | null, allowing timestamp from JSONL mtime to propagate
- session-manager updates session.lastActivityAt when detected.timestamp
  is more recent — fixes "active 22h ago" showing stale timestamps
- Update all agent plugins (claude-code, aider, codex, opencode) to
  return ActivityDetection objects

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

* fix(web): dismissible rate limit banner + 60min rate-limit cache TTL

- Add X dismiss button to GitHub API rate limit banner in Dashboard.tsx
  so it can be closed during demos
- Extend rate-limited PR cache TTL from 5min to 60min — GitHub GraphQL
  rate limits reset hourly, no point retrying every 5 minutes

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

* fix(web): address Cursor Bugbot review comments on PR #125

- Dashboard StatusLine: active sessions count now uses var(--color-status-working)
  (blue) instead of neutral text color, matching the design system semantics
- SessionCard: isReadyToMerge now guards against rate-limited state — a card
  with stale cached mergeability data won't show green merge-ready styling
- DirectTerminal: add `variant` to useEffect dependency array (was missing,
  causing stale cursor/selection colors if variant changed after mount)
- agent-aider: include `timestamp: chatMtime` in all ActivityDetection returns,
  matching the pattern used by agent-claude-code (enables accurate lastActivityAt)

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

* fix(ci): resolve lint, typecheck, and test failures

Lint:
- Remove unused parseJsonlFile function (superseded by parseJsonlFileTail)
- Remove dead lastLogModified stat() call in getSessionInfo (field was
  removed from AgentSessionInfo but the filesystem read was left behind)

Typecheck + Tests (ActivityDetection):
- session-manager.test.ts: update mocks to return { state: "active" } /
  { state: "idle" } instead of bare strings — getActivityState() returns
  ActivityDetection | null, not ActivityState | null
- integration tests (aider, claude-code, codex, opencode): update imports
  from ActivityState → ActivityDetection, variable types, comparisons
  (activityState?.state !== "exited"), and assertions (?.state).toBe()

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

* fix: parseJsonlFileTail uses readFile for small files; enrich exited sessions with PRs

- parseJsonlFileTail now calls stat() then readFile() for files smaller than
  maxBytes, falling back to open()/handle.read() only for large files. This
  fixes the test infrastructure (which mocks readFile but not open) and also
  fixes a scope bug where `offset` was declared inside an inner try block but
  referenced outside both try blocks.
- Math.max(0, NaN) returns NaN not 0, so size must default to 0 when stat
  returns a mock without a size field: `const { size = 0 } = await stat(...)`.
- Update activity-detection.test.ts: getActivityState() now returns
  ActivityDetection objects, so tests use (await ...)?.state comparisons.
- Remove stale lastLogModified test (field was removed from AgentSessionInfo).
- Remove EXITED skip guard from api/sessions/route.ts: exited sessions can
  still have open, merge-ready PRs that need enrichment on the dashboard.

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

* fix: comprehensive code review fixes — tests, timestamps, UI correctness

Address gaps identified in code review of the ActivityDetection PR:

Core / Session Manager:
- Add `timestamp` to all `{ state: "exited" }` returns in all 4 agent plugins
  (claude-code, aider, codex, opencode) using consistent `exitedAt = new Date()` pattern
- Add 2 new session-manager tests: timestamp propagation when detection timestamp
  is newer, and no-downgrade when detection timestamp is older
- Fix `parseJsonlFileTail` lint error: remove useless `= 0` initializer (value was
  always overwritten before use; catch block returns early)

Web package — tests:
- Fix 3 `api-routes.test.ts` failures: `sessionsGET()` needs a Request object since
  the route reads `request.url` for `?active=true` query param
- Fix `serialize.test.ts` rate-limit test: spy on `console.warn` (what the code uses)
  not `console.error`
- Add 5 `ActivityDot` component tests covering all activity states, unknown states,
  null activity, and dotOnly mode

Web package — UI correctness:
- Fix `relativeTime()` in SessionDetail to guard against invalid/empty ISO strings
- Fix timer Map leak: add `timersRef.current.clear()` in cleanup effect after forEach
- Add `encodeURIComponent` to sessionId in message fetch URL

Server — race condition fix:
- Guard `activeSessions.delete` in pty.onExit, ws.on("close"), and ws.on("error")
  against stale handlers deleting a newly-registered session with the same ID.
  Fixes flaky integration test where afterEach's pty.kill() fired asynchronously
  after the next test had already set up a new session with the same session ID.

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

* fix(web): narrow PREnrichmentData types to eliminate unsafe casts in serialize

PREnrichmentData.ciStatus and .reviewDecision were typed as string,
requiring unsafe `as` casts when reading from cache into DashboardPR.
Narrow them to the same literal union types used by DashboardPR, making
the casts unnecessary. Also narrow ciChecks[].status to match CoreCICheck.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 18:43:57 +05:30
prateek 0e2ca70b0b
feat: session title fallback chain for PR-less sessions (#105)
* feat: session title fallback chain — PR title → summary → issue title → branch

Sessions without PRs now always show a meaningful title on the dashboard
instead of just the status text. The fallback chain is:

1. PR title (already worked)
2. Agent summary (now fetched from JSONL via getSessionInfo())
3. Issue title (now fetched via tracker.getIssue())
4. Humanized branch name (e.g., "feat/infer-project-id" → "Infer Project ID")

Key changes:
- Enrich agent summaries by calling getSessionInfo() for sessions
  without summaries (local file I/O, not API calls)
- Enrich issue titles via tracker.getIssue() with 5-min TTL cache
- Add humanizeBranch() utility for last-resort branch name display
- Add issueTitle field to DashboardSession type
- Show issue title in expanded detail panel

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

* fix: extract humanizeBranch to separate module to avoid client-side timer leaks

Moves humanizeBranch() from serialize.ts to format.ts — a pure utility
module with no side effects. This prevents the client bundle from pulling
in TTLCache instantiations (which create setInterval timers) when
SessionCard.tsx imports the function.

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

* fix: remove dead re-export of humanizeBranch from serialize.ts

No consumer imports humanizeBranch from serialize — SessionCard imports
directly from format.ts. The re-export was unused surface area.

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

* fix: add missing first-project fallback in summary enrichment block

Matches the pattern used by all other enrichment blocks in page.tsx
(issue labels, issue titles, PR enrichment) which fall back to the
first configured project when projectId and sessionPrefix both miss.

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

* feat: smarter title heuristic — skip prompt excerpts, prefer issue titles

The agent summary fallback from extractSummary() often returns truncated
spawn prompts ("You are working on GitHub issue #42: Add auth...") which
make poor titles. The new heuristic detects these prompt excerpts and
prefers the issue title when available.

Updated fallback chain:
  PR title → quality summary → issue title → any summary → humanized branch → status

Changes:
- Add looksLikePromptExcerpt() to detect spawn prompt patterns
- Add getSessionTitle() to encapsulate the smart fallback logic
- Expand humanizeBranch() with more prefix patterns (release, hotfix, etc.)
- SessionCard now uses getSessionTitle() instead of inline ?? chain
- Add 25 unit tests covering all functions and edge cases
- Fix missing issueTitle field in serialize.test.ts fixture

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

* refactor: extract shared resolveProject() to eliminate duplication

Moves resolveProject() from route.ts into serialize.ts as a shared
export. Both page.tsx and route.ts now use the same function instead
of duplicating the 3-step project resolution logic (projectId →
sessionPrefix → first project fallback) inline.

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

* feat: replace looksLikePromptExcerpt heuristic with summaryIsFallback metadata

Instead of fragile string matching to detect truncated spawn prompts,
the agent plugin now sets summaryIsFallback: true when the summary is
a first-message fallback rather than a real agent-generated summary.

- Add summaryIsFallback to AgentSessionInfo (core/types.ts)
- extractSummary() returns { summary, isFallback } in claude-code plugin
- Add summaryIsFallback to DashboardSession, propagate in serialize.ts
- Replace looksLikePromptExcerpt() with !session.summaryIsFallback
- Fix .js extension in format.ts import (review feedback)
- Add thorough tests for all layers of propagation

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

* test: add resolveProject and enrichSessionIssueTitle coverage

- resolveProject: 5 tests covering direct match, prefix fallback,
  first-project fallback, empty projects, and priority ordering
- enrichSessionIssueTitle: 7 tests covering enrichment, # prefix
  stripping, Linear-style labels, skip conditions, error handling,
  and cross-call caching

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

* refactor: extract shared enrichSessionsMetadata, fix session detail route

- Extract duplicated enrichment orchestration (issue labels, agent
  summaries, issue titles) from page.tsx and route.ts into a single
  enrichSessionsMetadata() function in serialize.ts
- Fix /api/sessions/[id] route: was missing agent summary and issue
  title enrichment, and had hand-rolled project resolution instead of
  using resolveProject() (also missing the first-project fallback)
- Optimize: resolve projects once per session instead of 3x
- Add 8 tests for enrichSessionsMetadata covering full pipeline, skip
  conditions, missing plugins, no-tracker config, multiple sessions,
  and default agent fallback

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

* fix: remove dead getAgent and getTracker exports from services.ts

These helpers became unused when enrichSessionsMetadata was extracted
to serialize.ts with inline registry.get() calls (to avoid coupling
serialize.ts to services.ts and pulling plugin packages into webpack).

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 19:02:02 +05:30
prateek 65fa811b3b
feat: implement session restore for crashed/exited agents (#104)
* feat: implement session restore for crashed/exited agents

Add true in-place session restore: same session ID, same worktree, same
metadata — optionally resuming the Claude Code conversation via --resume.

Core changes:
- Add TERMINAL_STATUSES, TERMINAL_ACTIVITIES, NON_RESTORABLE_STATUSES sets
  and isTerminalSession/isRestorable helpers to types.ts
- Add SessionNotRestorableError and WorkspaceMissingError error classes
- Add restore() to SessionManager with 9-step flow: find metadata →
  validate restorability → check/recreate workspace → get restore or
  launch command → create runtime → update metadata
- Add restoredAt field to Session and SessionMetadata

Plugin extensions:
- workspace-worktree: exists() + restore() (git worktree prune + re-add)
- workspace-clone: exists() + restore() (git clone + checkout)
- scm-github: branchExists() via git rev-parse
- agent-claude-code: getRestoreCommand() finds latest JSONL session file
  and builds claude --resume command

CLI + Web:
- Add `ao session restore <id>` subcommand
- Web restore API route uses sessionManager.restore() instead of spawn()
- SessionCard uses centralized TERMINAL_STATUSES/TERMINAL_ACTIVITIES
- Web types re-export core constants with sync tests

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

* fix: add "merged" to TERMINAL_STATUSES

The old inline isTerminal check included "merged" but when refactored
to use the TERMINAL_STATUSES set, "merged" was omitted. This caused
merged sessions (whose activity is not "exited") to incorrectly show
the "terminal" link and "terminate session" button.

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

* fix: enrich runtime state before restore check, remove dead branchExists

- Add enrichSessionWithRuntimeState() call before isRestorable() in
  restore() so crashed sessions (status "working", agent exited) are
  correctly detected as terminal and eligible for restore.
- Remove dead branchExists from SCM interface and scm-github plugin
  (defined but never called anywhere in the codebase).

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

* fix: allow restore of crashed working sessions

Remove "working" from NON_RESTORABLE_STATUSES. The isTerminalSession()
gate already prevents restoring truly active sessions (activity is not
"exited"). This fix allows crashed agents (status "working", activity
"exited") to be restored, aligning core behavior with the UI which
already shows the restore button for this case.

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

* fix: distinguish missing branch from missing restore support

Split the compound condition so workspace restore gives an accurate
error message when branch metadata is null ("branch metadata is
missing") vs when the workspace plugin lacks a restore method.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 01:12:57 +05:30
prateek de6653e258
feat: first-class orchestrator session + file-based system prompt (#101)
* feat: first-class orchestrator session + file-based system prompt

Make the orchestrator a first-class managed session that flows through
the same SessionManager pipeline as worker sessions, and fix a blocking
bug where long system prompts get truncated by tmux/zsh.

Changes:
- Add OrchestratorSpawnConfig type and spawnOrchestrator() to
  SessionManager interface
- Implement spawnOrchestrator() in session-manager.ts: proper
  hash-based tmuxName, runtimeHandle, plugin lifecycle — no workspace
  creation (uses project.path directly)
- Refactor `ao start` to use SessionManager.spawnOrchestrator()
  instead of manual tmux calls + metadata writes (~80 lines removed)
- Refactor `ao stop` to use SessionManager.kill() instead of manual
  tmux kill + metadata delete
- Update `ao init` next steps: guide users to `ao start` before
  `ao spawn`
- Add systemPromptFile to AgentLaunchConfig for file-based system
  prompts (avoids tmux truncation of 2000+ char inline prompts)
- Update agent-claude-code, agent-codex, agent-aider plugins to use
  shell command substitution "$(cat '/path')" when systemPromptFile
  is set
- Update runtime-tmux create() to use load-buffer/paste-buffer for
  launch commands >200 chars
- Add 8 tests for spawnOrchestrator
- Fix SessionManager mock in 8 test files (add spawnOrchestrator)

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

* fix: use hash-based tmux name in orchestrator attach hint

The tmux attach hint after `ao start` printed the user-facing session
ID (e.g. app-orchestrator) instead of the hash-based tmux session name
(e.g. a3b4c5d6e7f8-app-orchestrator), causing "session not found"
errors. Now captures the runtimeHandle.id from spawnOrchestrator's
return value for the correct tmux target.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 19:32:35 +05:30
prateek 59c490a3af
fix: dashboard config discovery + CLI service layer refactoring (#70)
* fix: config discovery, activity detection, and metadata port storage

- findConfigFile() checks AO_CONFIG_PATH env var (resolved to absolute path)
- loadConfig() delegates to findConfigFile() for consistent validation
- Pure Node.js readLastJsonlEntry (no external tail binary), safe for
  multi-byte UTF-8 at chunk boundaries
- Added "ready" activity state to agent plugins
- Store dashboardPort, terminalWsPort, directTerminalWsPort in session
  metadata so ao stop targets the correct processes
- Zod schema port default aligned with TypeScript interface

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

* fix: dashboard config discovery + CLI service layer refactoring

- Config discovery via AO_CONFIG_PATH env var
- Auto port detection with PortManager
- Activity detection with ready state, pure Node.js readLastLine
- 5 CLI services: ConfigService, PortManager, DashboardManager, MetadataService, ProcessManager
- Store all service ports in metadata for ao stop
- Set NEXT_PUBLIC_ env vars for frontend terminal components
- Multi-byte UTF-8 safe readLastJsonlEntry
- Tests for all new services and utils

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

* fix: address bugbot review comments (port fallback + systemPrompt)

1. Align port fallback to 3000 everywhere (matching Zod schema default):
   - start.ts: config.port ?? 3000
   - dashboard.ts: config.port ?? 3000
   - types.ts JSDoc: "defaults to 3000"
   - orchestrator-prompt.ts: already correct at 3000

2. Add --append-system-prompt to Claude Code plugin's getLaunchCommand
   so orchestrator context is actually passed to the Claude agent.
   Previously systemPrompt was generated but silently dropped.

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

* fix: remove dead ConfigService mock from status test

The vi.mock for ConfigService.js referenced a deleted module.
Config mocking is already handled by the @composio/ao-core mock.

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

* fix: extract shared buildDashboardEnv to eliminate duplication

Dashboard env construction (AO_CONFIG_PATH, PORT, NEXT_PUBLIC_*) was
duplicated between start.ts and dashboard.ts. Extracted into
buildDashboardEnv() in web-dir.ts (already shared by both commands).

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 17:08:48 +05:30
prateek adc17c8ae0
feat: overhaul orchestrator prompt with comprehensive CLI reference (#90)
* feat: overhaul orchestrator prompt with comprehensive CLI reference

The generated CLAUDE.orchestrator.md now teaches the orchestrator agent
everything it needs out of the box: identity/role, complete CLI reference
for every `ao` command with flags/options, behavioral guidelines (do/don't),
session lifecycle, workflows, and anti-patterns.

- Rewrite generateOrchestratorPrompt() with detailed CLI docs
- Add "Never Do" section (no legacy scripts, no raw tmux, no coding)
- Add session lifecycle ASCII diagram adapted to project config
- Document ao send flags (--no-wait, --timeout, -f) and mechanics
- Update static CLAUDE.orchestrator.md to use ao CLI exclusively
- Add 35 unit tests for orchestrator prompt generation

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

* refactor: move orchestrator prompt injection into Agent plugin interface

The orchestrator prompt was being injected by directly writing
CLAUDE.local.md and CLAUDE.orchestrator.md in start.ts — Claude Code-
specific logic that doesn't work for other agents (Codex, Aider, OpenCode).

- Add `injectSystemPrompt()` to the Agent interface in types.ts
- Implement in agent-claude-code: writes CLAUDE.{name}.md + @import
- Implement in agent-codex/opencode: writes AGENTS.md
- Implement in agent-aider: writes .aider.conventions.md
- Remove ensureOrchestratorPrompt/ensureOrchestratorImport from start.ts
- start.ts now calls agent.injectSystemPrompt() (agent-agnostic)

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

* refactor: pass orchestrator prompt via CLI flags instead of file injection

Replace the file-based injectSystemPrompt() approach with native agent CLI
flags. Each agent plugin now handles systemPrompt in getLaunchCommand():
- Claude Code: --append-system-prompt
- Codex: --system-prompt
- Aider: --system-prompt
- OpenCode: no flag yet (ignored)

This removes the need to write CLAUDE.orchestrator.md / CLAUDE.local.md /
AGENTS.md files, making the implementation truly agent-agnostic. Also removes
the unused --regenerate flag from `ao start`.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 11:32:33 +05:30
prateek 73957182f7
fix: activity detection — fix path encoding bug, add ready state (#71)
* fix: activity detection — fix path encoding, use tail -1 for JSONL

Two tightly coupled infrastructure fixes:

- Fix toClaudeProjectPath(): leading `/` becomes `-` (not stripped),
  matching Claude Code's actual project directory naming convention.
- Replace manual 4KB buffer read in readLastJsonlEntry() with
  `tail -1` + JSON.parse — handles any file size, any line length,
  and eliminates the truncated-line edge case entirely.

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

* feat: add "ready" state, return null when unknown, remove dead code

Behavioral changes to activity detection:

- Add "ready" to ActivityState — separates "alive at prompt" from
  "idle/stale". Configurable via readyThresholdMs (default 5 min).
- Agent plugins return null when they can't determine activity
  (no workspace, no JSONL, no per-session tracking). Session manager
  preserves existing activity instead of overwriting with a guess.
- Remove isProcessing() from Agent interface — zero callers in
  production code, fully superseded by getActivityState().
- Remove extractLastMessageType() from claude-code — the field it
  populated (lastMessageType) was only consumed by the old inline
  CLI mapping, which is now replaced by plugin delegation.
- CLI status delegates to agent.getActivityState() (single source
  of truth) with metadata fallback when plugin returns null.

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

* test: comprehensive activity detection coverage

- activity-detection.test.ts: 42+ tests covering path encoding,
  getActivityState edge cases (exited/null/fallback), real Claude Code
  JSONL types, agent interface spec types, staleness thresholds,
  JSONL file selection, and realistic session sequences.
- status.test.ts: plugin delegation tests — verifies CLI uses
  agent.getActivityState() as single source of truth, passes
  readyThresholdMs from config, falls back to metadata on null/throw.
- Integration tests: updated type expectations for null returns from
  codex, opencode, and aider; added "ready" to valid state lists.

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

* fix: flaky Linear integration test + missing ready label in SessionDetail

Linear API has eventual consistency — updateIssue state changes don't
propagate instantly. Poll with retries instead of asserting immediately.

Also adds "ready" entry to SessionDetail activityLabel map (was missing,
causing fallback to dim/unstyled rendering).

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

* fix: pure Node.js readLastJsonlEntry, use pollUntilEqual for Linear test

Replace `tail -1` with pure Node.js implementation that reads backwards
from end of file in 4KB chunks. No external binary dependency — works
on any platform.

Fix flaky Linear integration test by using the existing pollUntilEqual
helper instead of an inline retry loop. Linear API has eventual
consistency; pollUntilEqual retries for up to 5s with 500ms intervals.

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

* fix: use tail -1 for readLastJsonlEntry, add real-data integration test

Replace over-engineered pure Node.js backward-reading implementation with
simple `tail -1` via execFile. The codebase already shells out to tmux,
git, and ps everywhere — tail is no different.

Add integration test that validates toClaudeProjectPath() and
readLastJsonlEntry() against real ~/.claude/projects/ data on disk.
No API key needed — just requires Claude to have been run once.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 03:48:19 +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 79aac7cf1d
feat: wire up live activity detection for agent sessions (#45)
* feat: wire up live activity detection for agent sessions

Previously, all sessions showed as "idle" on the dashboard because
activity detection was never called. The Agent plugin interface has
detectActivity(terminalOutput) and Runtime has getOutput(), but the
session manager's list() and get() methods never invoked them.

Changes:
- Updated list() to call runtime.getOutput() and agent.detectActivity()
  after checking if runtime is alive
- Updated get() with the same activity detection logic
- Captures last 30 lines of terminal output for classification
- Falls back to "idle" if output capture fails (graceful degradation)
- Agent plugins classify output into: active, idle, waiting_input,
  blocked, or exited

Testing:
- Added test for activity detection in list() with mocked output
- Added test for activity detection in get() with mocked output
- Added test for graceful fallback when getOutput() fails
- Fixed detectActivity mock (sync not async)
- All 24 tests pass

The dashboard now accurately shows whether agents are actively working,
idle at prompt, waiting for user input, blocked, or exited.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* refactor: extract enrichSessionWithRuntimeState helper

Addresses review comment about duplicated activity detection logic
between list() and get() methods.

Changes:
- Extract activity detection into enrichSessionWithRuntimeState helper
- Both list() and get() now call this shared helper
- Eliminates duplication and makes future changes easier
- All tests still pass (24/24)

Benefits:
- Single source of truth for runtime state enrichment
- Future changes (caching, param tweaks) only need one update
- More maintainable and less error-prone

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* refactor: replace terminal parsing with agent-native activity detection

Replaces hacky terminal output parsing (detectActivity) with deterministic
agent-native state tracking (getActivityState). Each agent now uses its own
internal mechanisms (JSONL files, SQLite, etc.) for reliable activity detection.

## Changes

### Core (`packages/core/src/types.ts`)
- Add `getActivityState(session)` method to Agent interface
- Deprecate `detectActivity(terminalOutput)` with @deprecated tag

### Session Manager (`packages/core/src/session-manager.ts`)
- Update `enrichSessionWithRuntimeState()` to call `agent.getActivityState()`
- Remove terminal output capture and parsing
- Cleaner, more maintainable code

### Claude Code Plugin (`packages/plugins/agent-claude-code/`)
- Implement `getActivityState()` using existing JSONL infrastructure
- Read last JSONL entry and classify by event type:
  - user/tool_use → active
  - assistant/system → idle
  - permission_request → waiting_input
  - error → blocked
  - stale (>30s) → idle
- Export `toClaudeProjectPath()` for testing
- Add unit tests for path encoding

### Other Agent Plugins (Codex, Aider, OpenCode)
- Add stub `getActivityState()` implementations
- Fall back to process running check
- TODO comments for full implementation using:
  - Codex: JSONL rollout files
  - Aider: Chat history mtime
  - OpenCode: SQLite database

### Tests (`packages/core/src/__tests__/session-manager.test.ts`)
- Update tests to expect `getActivityState()` calls
- Remove tests for deprecated terminal parsing
- All 24 tests pass 

## Benefits

 **Deterministic** - File-based, not terminal text parsing
 **Fast** - Single file read, no regex
 **Reliable** - Agent-provided state
 **Testable** - Mock files easily
 **Maintainable** - Pin versions, test format changes

## Migration Path

- `detectActivity()` is deprecated but not removed (backwards compat)
- Claude Code uses new method immediately
- Other agents use fallback until fully implemented
- Future PR will remove deprecated method

## Research

Agent-native mechanisms documented in:
- OpenAI Codex: JSONL rollout files at ~/.codex/sessions/
- Aider: Chat history at .aider.chat.history.md
- OpenCode: SQLite at ~/.local/share/opencode/opencode.db

See /tmp/activity-detection-redesign.md for full design.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* feat: implement native activity detection for all agent plugins

Implements full getActivityState() for Codex, Aider, and OpenCode:

- **Codex**: Checks JSONL rollout files at ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl
  Maps event types (user_message, tool_use, approval_request, error) to activity states

- **Aider**: Checks chat history file mtime at .aider.chat.history.md and recent git commits
  Detects activity based on file modification and auto-commit behavior

- **OpenCode**: Checks SQLite database mtime at ~/.local/share/opencode/opencode.db
  Considers active if database was modified within 30 seconds

All implementations follow the deterministic approach established for Claude Code,
avoiding hacky terminal output parsing in favor of agent-native mechanisms.

Also fixes test mocks to include new getActivityState() method.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: address bugbot review comments for activity detection

Fixes three issues identified by Cursor Bugbot:

1. **Claude Code returns "exited" when runtime is alive** (Medium)
   - Added process-alive check at start of getActivityState()
   - Changed fallback returns from "exited" to "active" when process is running
   - Now matches pattern used by other agents (Codex, Aider, OpenCode)

2. **Claude Code missing process-alive check** (Medium)
   - Added isProcessRunning() check before file-based detection
   - Prevents reporting stale file-based activity when process has exited
   - Ensures "exited" is only returned when process is actually dead

3. **Codex reads entire JSONL file into memory** (Medium)
   - Replaced readFile() with seeked file handle read
   - Now reads only last 4KB (TAIL_READ_BYTES) instead of entire file
   - Matches efficient approach used by Claude Code plugin
   - Prevents memory/latency issues on long-running sessions

All tests passing (85 for Claude Code, 28 for Codex).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: address three additional bugbot review comments

Fixes three issues identified in the second Cursor Bugbot scan:

1. **Catch block doesn't set activity to idle** (Low)
   - Added explicit `session.activity = "idle"` in catch block
   - Previously relied on implicit default from metadataToSession
   - Now explicitly documents and enforces the fallback behavior

2. **Codex rollout file matching uses wrong session ID** (Medium)
   - Removed session ID filtering from findLatestRolloutFile()
   - Codex uses internal UUIDs unrelated to orchestrator session IDs
   - Now finds most recent rollout file across all dates
   - Fixes non-functional activity detection for Codex

3. **Duplicate readLastJsonlEntry across packages** (Low)
   - Extracted shared JSONL tail-reading logic to @composio/ao-core/utils
   - Removed duplicate implementations from agent-claude-code and agent-codex
   - Both plugins now import readLastJsonlEntry and TAIL_READ_BYTES from core
   - Net reduction of 21 lines while improving maintainability

All 240 tests passing (127 core + 85 Claude Code + 28 Codex).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: remove unused TAIL_READ_BYTES import from claude-code plugin

* fix: address third round of bugbot comments - document agent limitations

Fixes three issues from the latest Cursor Bugbot scan:

1. **Codex reads global state not per-session** (High Severity)
   - Removed file-based activity detection from Codex plugin
   - Codex stores rollout files globally without workspace scoping
   - When multiple sessions run, cannot reliably match files to sessions
   - Now falls back to process-running check only (conservative)
   - Documented limitation with TODO for when Codex adds per-workspace support

2. **OpenCode uses global shared database** (Medium Severity)
   - Removed database mtime checking from OpenCode plugin
   - OpenCode uses single global SQLite database for all sessions
   - Multiple sessions cause activity state bleed
   - Now falls back to process-running check only (conservative)
   - Documented limitation with TODO for when OpenCode adds per-workspace support

3. **Unused TAIL_READ_BYTES export** (Low Severity)
   - Removed TAIL_READ_BYTES from core package exports
   - Only used internally by readLastJsonlEntry in utils.ts
   - Reduces unnecessary public API surface

Net reduction: 108 lines of code that couldn't work correctly with multiple sessions.
All tests passing (28 Codex + 27 OpenCode).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* test: rewrite agent integration tests to use getActivityState() instead of detectActivity()

Integration tests were using the deprecated detectActivity() method, which
meant they weren't actually testing the new getActivityState() functionality
that session-manager uses in production.

Changes:
- All agent integration tests now call getActivityState() instead of detectActivity()
- Tests verify getActivityState() returns valid states while running
- Tests verify getActivityState() returns "exited" after process terminates
- Grouped multiple assertions per test run for efficiency
- Updated comments to reflect new behavior (Codex/OpenCode conservative fallback)
- Allow getSessionInfo() to return null for path encoding mismatches

All integration tests pass:
- agent-claude-code: 6 passed (full JSONL-based activity detection)
- agent-codex: 5 passed (conservative fallback)
- agent-opencode: 5 passed (conservative fallback)
- agent-aider: updated but not tested (aider binary not available in CI)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: remove unused imports from integration tests

Fixed ESLint errors:
- Removed unused 'capturePane' imports from all agent integration tests
- Removed unused 'err' variable from catch block

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: return active instead of idle when JSONL entry is null

When readLastJsonlEntry returns null (empty file or read error), getActivityState
now returns "active" instead of "idle" as a conservative fallback. This makes it
consistent with:
- Other fallback cases in the same function (no workspace path, no session file)
- Other agent plugins (Codex, OpenCode, Aider) which return "active" on detection failure
- The stated intent in PR discussion to assume active when process is running

Fixes bugbot comment: https://github.com/ComposioHQ/agent-orchestrator/pull/45#discussion_r2810110669

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: make TAIL_READ_BYTES internal constant instead of exported

TAIL_READ_BYTES is only used internally within readLastJsonlEntry()
and is not exported from the package's index.ts. Removed the export
keyword to make it clear it's an internal implementation detail.

Addresses bugbot comment about unused export.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-16 05:31:02 +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 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 8e5b23e6a0
feat: auto-update session metadata via Claude Code hooks (#34)
* feat: auto-update session metadata via Claude Code hooks

Implements INT-1355: Auto-update session metadata when agent creates PR or switches branch.

## What Changed

- **agent-claude-code plugin**: Added `postLaunchSetup` method that writes a Claude Code hook to `.claude/settings.json` and `.claude/metadata-updater.sh` in each workspace
- **session-manager**: Added `AO_DATA_DIR` environment variable to agent sessions
- **Hook script**: Monitors Bash commands and automatically updates metadata on:
  - `gh pr create` → extracts PR URL, sets `pr=<url>` and `status=pr_open`
  - `git checkout -b` / `git switch -c` → extracts branch name, sets `branch=<name>`
  - `git checkout` / `git switch` (existing branches) → updates branch name for feature branches
  - `gh pr merge` → sets `status=merged`

## How It Works

1. When a session is spawned, `postLaunchSetup` runs after the agent launches
2. Creates `.claude/settings.json` with a PostToolUse hook for Bash commands
3. Writes the metadata updater script to `.claude/metadata-updater.sh`
4. The hook fires after every Bash command execution
5. Parses command and output to detect git/gh operations
6. Updates the session metadata file directly using atomic file operations

## Benefits

- Dashboard shows correct PR associations immediately without manual intervention
- Branch tracking stays in sync with agent actions
- Orchestrator has accurate session state for automation and notifications

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: correct hook payload field name and JSON parsing

Fixes bugbot issues from PR #34:

1. Changed tool_output to tool_response - Claude Code hooks provide
   output in the tool_response field, not tool_output. This fixes PR
   URL extraction from gh pr create commands.

2. Replaced over-escaped sed patterns with cut - The fallback JSON
   parser now uses 'cut -d\" -f4' instead of sed with capture groups,
   which is simpler and avoids escaping issues.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: escape special characters in metadata values

Fixes bugbot issue: metadata updates break on special branch names.

The update_metadata_key function now escapes sed special characters
(& | / \) in values before using them in sed replacement. This prevents
branch names or PR URLs containing these characters from breaking the
metadata update.

Example: branch name "feature/foo&bar" now correctly updates metadata
instead of causing sed to interpret "&" as a backreference.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: only update metadata on successful commands

Fixes bugbot issue: metadata updates ignore command failure.

The hook now checks the exit_code field from the hook payload and only
updates metadata if the command succeeded (exit code 0). This prevents
updating metadata when git/gh commands fail.

Example: if 'gh pr create' fails due to auth issues, the metadata won't
be incorrectly updated with a pr= line.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: use correct timeout units for Claude Code hook

Fixes bugbot issue: hook timeout uses wrong units (High Severity).

Claude Code hook timeouts are in milliseconds, not seconds. Changed
timeout from 5 to 5000 (5 seconds) to give the metadata updater script
enough time to parse tool output and update metadata.

Note: The hook command path is properly handled by JSON.stringify
and does not need additional escaping as Claude Code handles command
execution correctly.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: PR URL regex and stale hook path issues

Fixes 2 bugbot issues:

1. PR URL extraction regex never matches (High Severity): Changed
   'github\.com' to 'github[.]com' because in single-quoted bash
   strings, backslashes are literal. The [.] syntax correctly matches
   a literal dot in grep regex.

2. Shared Claude settings keep stale hook path (Medium Severity):
   Changed hook detection to always update the command path to the
   current workspace, not just check for existence. This handles cases
   where .claude settings are shared/symlinked across workspaces.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 02:29:31 +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
prateek 4b6d62d142
feat: agent plugins, OpenCode plugin, integration tests, CI (#5)
* feat: implement agent plugins (claude-code, codex, aider)

Implement the Agent interface from @agent-orchestrator/core for three
AI coding tools, enabling the orchestrator to launch, detect activity,
and introspect agent sessions.

Claude Code plugin (full implementation):
- JSONL session introspection (summary, session ID, cost, last message type)
- Activity detection via terminal output pattern matching
- Process detection via tmux pane TTY → ps lookup chain
- Launch command generation with permissions/model/prompt support

Codex and Aider plugins (functional stubs):
- Launch command generation with tool-specific flags
- Process detection via TTY lookup
- Stub introspection (no JSONL support yet)

Closes INT-1329

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

* fix: address PR review — shell escaping, activity detection, tests

- Replace JSON.stringify with POSIX shell escaping (single quotes) for
  all agent launch commands to prevent command injection
- Remove `unset CLAUDECODE &&` shell syntax from getLaunchCommand (breaks
  execFile); moved to getEnvironment as empty string
- Fix detectActivity returning "exited" for empty pane when process is
  confirmed alive — now returns "idle"
- Tighten BLOCKED_PATTERNS to specific error framing (^Error:, ENOENT:,
  APIError:, etc.) to avoid false positives on code output
- Check blocked patterns before input patterns to prevent "EACCES:
  permission denied" matching INPUT_PATTERNS on the word "permission"
- Remove pgrep fallback in findClaudeProcess (could match wrong session)
- Fix extractCost double-counting: prefer costUSD, fall back to
  estimatedCostUsd only when costUSD is absent
- Trim ACTIVE_PATTERNS to stable indicators only
- Add comprehensive vitest tests (127 tests across 3 plugins)

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

* fix: address Codex review + lint fixes

- Use `ps -eo pid,tty,args` instead of `comm` for process detection so
  CLI wrappers (node, python) are correctly identified
- Coerce PID from handle.data with Number() + isFinite() to handle
  string-serialized PIDs
- Fix token double-counting: prefer `usage` object, only fall back to
  flat `inputTokens`/`outputTokens` when `usage` is absent
- Add `--` before Codex prompt to prevent prompts starting with `-`
  from being parsed as CLI flags
- Check blocked patterns before input patterns so "EACCES: permission
  denied" isn't misclassified as waiting_input
- Fix lint: merge duplicate imports, strict equality, remove non-null
  assertions
- Format with prettier

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

* fix: multi-pane tmux, EPERM handling, strict process matching

Codex review iteration 1 fixes:
- Iterate all tmux pane TTYs instead of only the first — prevents
  false "exited" in multi-pane sessions
- Handle EPERM from process.kill(pid, 0) as "process exists" — EPERM
  means the process is alive but we lack permission to signal it
- Use word-boundary regex for process name matching — prevents false
  positives on similar names like "claude-code" or paths containing
  the substring
- Add tests for EPERM handling, multi-pane detection, and strict
  name matching (134 tests total)

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

* fix: exclude next-env.d.ts from eslint

Auto-generated Next.js type file triggers triple-slash-reference rule.

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

* fix: address Bugbot review — JSON.parse guard, detectActivity pattern priority

- Guard parseJsonlFile against non-object JSON values (null, arrays,
  primitives) that would cause TypeError in downstream extractors
- Split null output (non-tmux → "active") from empty output (tmux → "idle")
  so non-tmux runtimes don't falsely report idle
- Reorder pattern matching: idle before blocked so stale errors in the
  tmux scrollback don't mask an idle prompt

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

* refactor: extract shellEscape to @agent-orchestrator/core

Move the duplicated POSIX shell-escaping utility from all three agent
plugins into packages/core/src/utils.ts and re-export from the package
entry point. Plugins now import { shellEscape } from the shared package.

Addresses Bugbot review comment on PR #5.

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

* fix: add execFileAsync timeouts, use satisfies for plugin exports

- Add { timeout: 30_000 } to all execFileAsync calls (tmux, ps) per
  CLAUDE.md convention to prevent hanging on stuck processes
- Replace `const plugin: PluginModule<Agent>` with inline
  `export default { ... } satisfies PluginModule<Agent>` to preserve
  narrow literal types on manifest fields

Addresses Bugbot review comments on PR #5.

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

* refactor: rename introspect → getSessionInfo, detectActivity uses JSONL

- Rename Agent.introspect() → getSessionInfo(), AgentIntrospection → AgentSessionInfo
- Claude Code detectActivity: replace tmux screen-scraping with JSONL-based
  detection (file mtime + last entry type)
- Remove terminal pattern constants (ACTIVE_PATTERNS, IDLE_PATTERNS, etc.)
- Update all tests: JSONL-based activity tests, renamed introspect blocks
- waiting_input/blocked states deferred to hooks-based implementation (#16)

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

* feat: add OpenCode agent plugin, integration tests, and CI workflow

- Add agent-opencode plugin with getLaunchCommand, detectActivity,
  isProcessRunning, getSessionInfo (27 unit tests)
- Add integration test suite for all 4 agents (claude-code, codex,
  aider, opencode) using real binaries in tmux sessions
- Add GitHub Actions CI workflow for integration tests
- Add test:integration script to root package.json

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

* fix: update core test mocks — introspect → getSessionInfo + isProcessing

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

* fix: address Bugbot review — Windows paths, bytesRead, hardcoded paths

- toClaudeProjectPath: handle Windows backslashes and drive letters
- readLastJsonlEntry: use bytesRead to avoid null character corruption
- Remove duplicate next-env.d.ts eslint ignore entry
- Remove hardcoded developer-specific binary paths from integration tests
- Add isProcessing limitation comments with issue references (#17-19)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 11:28:42 +05:30