* fix(core): sm.list() no longer writes terminated state to disk (#1735)
sm.list() was bypassing the lifecycle manager's probe decision matrix by
persisting terminated state immediately on a single isAlive() failure.
The dashboard's 3s poll via /api/sessions/patches called sm.list() ~10x
more often than the lifecycle manager, so a transient runtime failure
would permanently kill the session before the lifecycle manager could
evaluate all three probes (runtime, process, activity).
Changes:
- sm.list() now persists "detecting" instead of "terminated" when it
detects a dead runtime, so the lifecycle manager's resolveProbeDecision
pipeline remains the single authority on terminal decisions.
- /api/sessions/patches now calls listCached() instead of list(),
preventing the dashboard's 3s poll from probing runtimes directly.
The cache TTL (35s) aligns with the lifecycle manager's 30s poll.
- Updated CLAUDE.md invariants to reflect the new behavior.
* fix(core): skip re-persisting detecting state on subsequent list() calls
Check the on-disk lifecycle state (raw metadata) instead of the
in-memory state when deciding whether to persist. Enrichment already
sets detecting in-memory, so the previous guard always skipped the
persist block. Using the on-disk state ensures:
- First detection: persists detecting + lastTransitionAt
- Subsequent calls: skips re-write, preserving the original timestamp
* feat(core): add CI failure summary SCM contract
Add an optional SCM getCIFailureSummary hook and shared CIFailureSummary shape so providers can return failed jobs, failed steps, run URLs, and bounded log tails without changing existing SCM implementations.
* feat(scm-github): summarize failed CI logs
Use failed GitHub check URLs to locate Actions run/job IDs, fetch gh run view --log-failed output, parse the step column from the gh log format, and cap each failed-job log tail at 120 lines. Return null when no failed run logs can be fetched so lifecycle can fall back cleanly.
* feat(lifecycle): send actionable CI failure details
Prefer SCM CI failure summaries when composing ci-failed agent messages, including failed job/step, run URL, and log tail. Fall back to check names/statuses for SCM plugins without getCIFailureSummary, and remove the generic default ci-failed text so default handling relies on the lifecycle-composed payload.
State invariants preserved: this only changes ci-failed reaction payload composition and dispatch hashing. It does not change lifecycle status decisions, state-machine transitions, ci-failed persistence, retry/escalation thresholds, or stable-passing tracker reset semantics.
* fix(lifecycle): harden CI failure summaries
Address review feedback: escape log-tail lines that could close markdown fences, report the last failed-step column from gh failed logs, and pass already-known failed checks into getCIFailureSummary to avoid duplicate CI check fetches.
State invariants preserved: lifecycle transition decisions, retry/escalation budgets, persistent ci-failed tracker behavior, and stable CI passing reset semantics remain unchanged.
* refactor(lifecycle): centralize CI failure check lookup
Deduplicate CI failure check lookup, filtering, and fingerprint generation across transition-time enrichment and follow-up CI-failure dispatch while preserving the existing fetch/no-fetch split.
State invariants preserved: lifecycle transition decisions, reaction retry/escalation behavior, ci-failed tracker persistence, and stable-passing reset semantics are unchanged.
* fix(scm-github): fetch in-progress failed job logs
* fix(lifecycle): label CI failure URLs explicitly
---------
Co-authored-by: i-trytoohard <193449657+i-trytoohard@users.noreply.github.com>
* fix(core): clear terminal markers on non-terminal lifecycle transitions
Clear stale completedAt/terminatedAt whenever lifecycle helpers settle on a non-terminal session state, including restore-to-working paths.
Preserved invariants: terminal-state idempotence remains intact because done/terminated states keep their terminal markers; session state transitions still flow through existing code that updates lastTransitionAt before marker hygiene runs.
* fix(core): share terminal marker hygiene
Move non-terminal marker clearing into lifecycle-state so restore and lifecycle-transition paths use one terminal-state source of truth.
Preserved invariants: terminal-state idempotence still keeps done/terminated markers; existing transition code continues to update lastTransitionAt before marker hygiene runs.
---------
Co-authored-by: i-trytoohard <193449657+i-trytoohard@users.noreply.github.com>
* 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>
* refactor(release): split publish into two-repo model
Org compliance forbids npm publish credentials in public repositories.
Move the npm publish step out of this repo and into a private
ComposioHQ/ao-publisher repo, triggered via repository_dispatch.
Public repo (this one) now only:
- Bumps versions via changesets/action (no `publish:` argument)
- Creates git tags via `pnpm changeset tag`
- Creates the GitHub release (stable or prerelease)
- Dispatches `publish-npm-stable` / `publish-npm-nightly` to ao-publisher
The only secret needed here is PUBLISHER_DISPATCH_TOKEN, a fine-grained
PAT scoped to ao-publisher with `repository_dispatch:write`. NPM_TOKEN
lives in ao-publisher's secret store and never enters this repo.
Removed from both workflows: NODE_AUTH_TOKEN env, NPM_CONFIG_PROVENANCE
env, and `registry-url` on setup-node — none are needed when no npm
publish happens here. Canary also gains a skip-if-unchanged guard so
cron ticks during quiet stretches don't republish identical SHAs.
CONTRIBUTING.md "Release Setup" → "Release Architecture": documents the
two-repo split, secret layout, rotation procedure, and the stable vs.
nightly flows.
Requires PUBLISHER_DISPATCH_TOKEN secret + ao-publisher repo setup by
maintainers (out of scope for this PR — see PR description).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(release): address Greptile review findings on two-repo split
Three review findings on PR #1815:
1. (P1) canary.yml missing git commit before tagging
`pnpm changeset version --snapshot` modifies package.json but does
not commit. `pnpm changeset tag` would then tag the pre-snapshot
HEAD, so ao-publisher would check out un-bumped versions.
Add a "Commit snapshot version bumps" step with `git diff --cached
--quiet || git commit` (defensive: skip if nothing to commit) and
the `[skip ci]` marker. The commit is never pushed to main — only
the tags are pushed and the orphan commit travels with them.
2. (P2) release.yml `--target main` race condition
If a commit lands on main between `git push --follow-tags` and
`gh release create --target main`, the release commitish drifts
and auto-generated notes pull in unrelated commits.
Create an explicit `vX.Y.Z` git tag pointing at the version-bump
commit, push it, and drop `--target`. `gh release create` then
resolves the commitish from the existing tag — no race window.
3. (P2) canary.yml skip-guard suppresses post-stable nightlies
`gh release list --limit 1` returns the most recent release by
date, which could be a stable from `release.yml`. An explicit
`workflow_dispatch` nightly right after a stable cut would be
suppressed.
Filter to prereleases only:
gh release list --json tagName,isPrerelease \
--jq '[.[] | select(.isPrerelease)][0].tagName // empty'
If no prerelease exists yet, the jq returns empty and the guard
falls through naturally (LAST_SHA empty → condition false →
nightly proceeds).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* ci: retrigger checks (event dropped on previous push)
* fix(release): make release.yml idempotent and dispatch reachable on re-run
The previous design used a single `released` output (based on `after >
before` tag count) to gate both `Create GitHub release` and
`Dispatch npm publish`. On a re-run, all tags are already on the
remote and `fetch-depth: 0` brings them down, so `pnpm changeset tag`
adds nothing, `after == before`, `released=false`, and both steps are
skipped — breaking the "re-run recovers cleanly" claim, especially
the common case where the first run failed only at dispatch because
`PUBLISHER_DISPATCH_TOKEN` was missing.
Refactor into a `Determine release state` step that emits three
independent signals:
- `is_release_commit` — version-bump signal. Detected by comparing
`packages/ao/package.json` version against its value in HEAD^.
A Version Packages merge changes this; a regular commit does not.
This is the filter that prevents the dispatch from firing on every
commit to main (which all have `hasChangesets == 'false'`).
- `tag_on_remote` — whether the `vX.Y.Z` tag exists at origin.
- `release_exists` — whether the matching GitHub release exists.
Each downstream step is gated on its own piece of state:
- Tag push: `is_release_commit && !tag_on_remote`
- Release create: `is_release_commit && !release_exists`
- Dispatch: `is_release_commit` (always fires on a release commit)
The dispatch fires unconditionally on a release commit, even when
tag and release already exist on the remote. That guarantees recovery
from the most common failure mode (first run succeeded everywhere
except dispatch). The publisher must be idempotent against already-
published versions for this to be safe — `pnpm changeset publish`
already has this property since it skips packages whose current
version is already on the registry.
Update CONTRIBUTING.md → "Release Architecture":
- Add "Idempotency contract for ao-publisher" section spelling out the
no-op-on-already-published requirement.
- Add "Recovery" section explaining that re-running the failed
workflow is the canonical recovery path, plus a manual `gh api`
fallback for cases where re-running isn't practical.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(canary): skip-guard anchors on tag parent, not the orphan snapshot
The previous P1 fix added a "Commit snapshot version bumps" step before
`pnpm changeset tag`, which moved the snapshot tag onto an orphan
commit (the version-bump commit) rather than main HEAD. The
skip-if-unchanged guard still compared `git rev-list -n 1 "$LAST_TAG"`
against `GITHUB_SHA`, but `LAST_TAG` now resolves to the orphan
snapshot commit's SHA, never the main SHA. The two could never be
equal → `skip=true` was unreachable → every cron tick republished
regardless of whether main had advanced.
Use `${LAST_TAG}^` to anchor on the snapshot commit's first parent —
which is the main HEAD at the time the previous nightly ran — and
compare that against the current `GITHUB_SHA`. Now the guard fires
correctly when main hasn't advanced since the last nightly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(release): single umbrella tag per release, drop per-package tags
`pnpm changeset tag` creates one tag per publishable package (~27 here)
on every release. At 5 nightlies/week × 52 weeks × 27 packages that's
roughly 7 000 tags/year just from canary — pure decoration since
`ao-publisher` only consumes the umbrella `vX.Y.Z` tag. The per-
package tags also cause partial-recovery conflicts: `git push --tags`
on a re-run trips over tags that were pushed by the prior run.
Drop the `pnpm changeset tag` call from both workflows and replace
`git push origin --tags` with `git push origin "v$version"`. Push
exactly one umbrella tag per release.
CONTRIBUTING.md → "Release Architecture" updated:
- Flow diagram replaces "changeset tag → push" with "push vX.Y.Z tag"
- New paragraph spells out the single-tag-per-release policy and why
we skip `pnpm changeset tag`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(canary): workflow_dispatch bypasses skip-guard for recovery
When a nightly pushes the tag but fails at `gh release create` or
dispatch (e.g. `PUBLISHER_DISPATCH_TOKEN` missing), a re-run via
`workflow_dispatch` was silently skipped: `LAST_TAG` resolves to the
just-pushed nightly, `${LAST_TAG}^` equals `GITHUB_SHA`, and the
binary skip guard fires before any of the downstream steps we want
to retry.
`release.yml` handles the equivalent case by gating each step on
independent state. Canary has a single binary gate, so it needs a
different escape hatch: `workflow_dispatch` always proceeds. The
human trigger is itself the signal that we want to run regardless
of whether the source SHA looks unchanged. Cron-driven runs keep
the SHA-equality dedup so quiet stretches don't republish the same
SHA on every tick.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(release): replace ao-publisher dispatch with AO cron poll model
Remove the ao-publisher dispatch steps and PUBLISHER_DISPATCH_TOKEN from
both release.yml and canary.yml. npm publishing is now handled by an AO
cron job on a private server that polls GitHub releases and publishes
when a new tag is ahead of the current npm version.
Changes:
- release.yml: remove dispatch step, keep tag + GitHub release
- canary.yml: remove dispatch step, keep tag + GitHub prerelease
- CONTRIBUTING.md: rewrite Release Architecture for two-stage model
(public CI → GitHub release, private cron → npm publish)
* fix(release): address review — remove env/id-token, scope git add, fix wording
- Remove environment: release from both workflows (no npm publish here,
could block on required reviewers)
- Remove id-token: write permission (unused, no OIDC needed)
- Scope git add in canary to package.json and .changeset/ only (avoid
staging build artifacts)
- Fix 'orphan commit' wording → 'snapshot commit' (not actually orphan)
- Fix nightly version format 0.0.0-* → X.Y.Z-nightly-<sha>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: i-trytoohard[bot] <1484917231245856808@users.noreply.github.com>
* fix(cli): first-run startup creates global config with project registered
Regression from #1781: persistUpdateChannel() created an empty global config
({ projects: {} }) before autoCreateConfig() registered the project. Dashboard
loaded this empty config - zero projects - session not found.
Two-part fix:
1. autoCreateConfig() now calls registerProjectInGlobalConfig() after creating
the local yaml, so the global config is bootstrapped with the project
before maybePromptForUpdateChannel() or startDashboard() run.
2. persistUpdateChannel() and maybePromptForUpdateChannel() early-return when
no global config exists, preventing empty-husk creation.
Fixes#1766
* fix(cli): fix type error in persistUpdateChannel and update JSDoc
---------
Co-authored-by: AO Bot <ao-bot@composio.dev>
* 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>
* chore: add bug-triage skill for agent-driven issue triage
Add .skills/bug-triage/ with SKILL.md and push_fix_to_github.py script.
The skill provides a complete triage workflow:
- Gather bug context from chat/issues/live observation
- Search for duplicate GitHub issues
- File well-structured issues with root cause analysis
- Push fix PRs via GitHub API (no local checkout needed)
- Git archaeology (git log -S) for regression tracking
- NPM package regression diffing
- Remote code inspection without local clone
Reference the skill in AGENTS.md so any agent working on this repo
can discover and follow the triage workflow automatically.
Tested across 100+ real bug triages on ComposioHQ/agent-orchestrator.
* chore: add clickable issue/PR links as real-world examples
Add concrete examples with links to actual issues and PRs:
- #1129: deep diagnosis vs surface-level triage
- #1151: placeholder URL RCA
- #1391: CSS regression via git log -S archaeology
- PR #1523: optional TypeScript interface fields
- PR #1608: npm package regression diffing
* chore: add formatting rule — always linkify issue/PR references
Any agent following this skill must include clickable URLs when
mentioning issues or PRs. Bare '#123' without links is not allowed.
* fix: address review feedback — use existing skills/ dir, fix bugs
- Move .skills/ → skills/ (repo already has a skills/ directory)
- Fix label name: 'priority:medium' → 'priority: medium' (with space)
- Fix issue-assets branch naming: use slug instead of issue number
(issue doesn't exist yet at upload time)
- Fix base64 command: portable across Linux and macOS (tr -d '\n')
- push_fix_to_github.py: allow empty NEW_STRING for deletion edits
- push_fix_to_github.py: warn on multiple OLD_STRING matches
- push_fix_to_github.py: create branch before fetching file (SHA race)
- push_fix_to_github.py: configurable BASE_BRANCH (not hardcoded main)
- Update all path references in AGENTS.md and SKILL.md
* fix: correct stale .skills/ path in AGENTS.md How to load section
* feat: add cross-platform triage awareness (Windows/macOS/Linux)
Add Step 1b covering:
- When to ask for OS/shell/runtime/reproducibility
- Common Windows-specific bug patterns (paths, shell syntax, ConPTY,
named pipes, NTFS case-insensitivity, localhost IPv6 stalls)
- Key cross-platform files (platform.ts, CROSS_PLATFORM.md, etc.)
- Tagging OS-specific issues with 'to-reproduce'
Based on the actual Windows support implementation in #1025
(platform.ts, runtime-process, CROSS_PLATFORM.md).
* feat: add 6 triage improvements from real failure patterns
1. Environment Info Collection (Step 1):
- Standard template: OS, shell, runtime, AO version, Node version, install method
- Prevents wasted time tracing wrong code versions
2. Duplicate Search Strategy (Step 2):
- Search by symptom, component, AND error message
- Always search --state all (open + closed — bugs regress)
- Check PRs too (fixes sometimes land without issues)
3. Stop-and-Ask Triggers (Step 1c):
- Explicit criteria: 3 failed hypotheses, can't reproduce, upstream bug,
UI-only bug without screenshot, unknown environment
- Includes template for asking the reporter
4. Pre-Submission Checklist (Step 4.1b):
- Reporter attribution, commit hash, AO version, confidence score,
cross-links, concrete reproduction steps, screenshots ready
- Verify all before creating the issue
5. Confidence Scoring (Step 4.4):
- High/Medium/Low with clear criteria
- Maps to labels: bug only / to-explore / to-reproduce
- Example from PR #1608 where high confidence was wrong
6. Cross-Linking Related Issues (Step 4.5):
- Search by subsystem after filing
- Include Related section with one-line descriptions
- Helps maintainers see patterns across issues
7. Subsystem-Specific Triage Quick Reference:
- Table mapping subsystems to required info and key files
- Common misrouting patterns (terminal, stuck session, config)
* feat: add report gate, local diagnostics with ao events, deduplicate
New sections:
- Step 0a: Platform-specific context gathering (Discord/Slack/GitHub/live)
- Step 0b: Minimum Viable Report Gate — required fields (what/where/when)
plus 2-of-4 supporting (OS, version, reproducibility, steps)
- Step 0c: Local Diagnostics — auto-gather environment, process health,
AO event log (ao events list/search/stats), session state files,
reproducibility testing. Covers ao events commands with all flags.
Deduplication:
- Step 1b: removed repeated OS/shell/runtime questions (now in Step 1.2)
- Step 1c: removed 'environment unknown' and 'can't reproduce' triggers
(covered by report gate in Step 0b)
* refactor: compress bug-triage skill from 575→311 lines
Merge overlapping sections (Steps 0/0b/0c/1 → single Gather+Investigate flow),
move reference material to Appendix, deduplicate pitfalls, compress code blocks.
All factual content preserved: commands, file paths, labels, examples, links.
* docs: add skills/ README with agent-specific install instructions
Covers Claude Code, Codex CLI, Cursor, Windsurf, Copilot, Gemini CLI,
and Agent Orchestrator. Includes available skills table and how to write
new skills.
* docs: add Skills section to CLAUDE.md referencing skills/ directory
Links all 4 skills with when-to-load guidance, plus pointer to
skills/README.md for installing into other agents.
* fix: resolve PR review comments — remove Hermes-specific refs, portable base64
- Replace execute_code references with agent-agnostic 'Python script' wording
- Replace base64 -d (Linux-only) with python3 -c (portable across macOS/Linux/Windows)
---------
Co-authored-by: AO Bot <ao-bot@composio.dev>
* feat(web): add PWA manifest and wire mobile accordion on dashboard
- Add manifest.json with standalone display mode and theme colors
- Link manifest in layout.tsx generateMetadata
- Pass compactMobile, collapsed, onToggle to AttentionZone from Dashboard
so the mobile accordion (already implemented) is now activated
Closes#175
* fix(web): add missing PWA icons and split icon purposes
- Add icon-192.png and icon-512.png to public/ (were 404ing on PWA install)
- Split combined 'any maskable' into separate icon entries per W3C
best practice to avoid safe-zone cropping in non-maskable contexts
- Apply Prettier formatting to Dashboard.tsx (long SVG attribute lines)
* fix(web): resolve merge conflict, fix types, use dynamic icon routes
- Resolve Dashboard.tsx merge conflict with upstream refactored useSessionEvents
- Type handleZoneToggle as (level: AttentionLevel) per reviewer request
- Start all zones collapsed on mobile for better UX (collapsedZones init)
- Add scope to manifest.json per PWA best practice
- Switch manifest icons from static PNGs to dynamic /icon-192 and /icon-512
routes that use the existing renderIconElement system (branded icons)
- Remove static icon-192.png and icon-512.png black square placeholders
* fix(web): wire BottomSheet preview, fix mobile tests, update manifest
- Add onPreview to AttentionZone, opens BottomSheet on mobile tap
- Add previewSession state and bottom sheet handlers to Dashboard
- Default collapsedZones to done+working only, not all zones
- Fix isMergeReady to use server attentionLevels instead of client recompute
- Restore isMerged guard on DoneCard restore button
- Update manifest.ts with scope, orientation, maskable icon entries
- Update manifest.test.ts to expect new fields
- Update Dashboard.mobile.test.tsx for MobileSessionRow compact row structure
- Revert inverted Dashboard.doneBar.test.tsx assertion
* fix(web): add display:flex to kanban-board mobile override
* feat: enable workers to message orchestrator via AO_ORCHESTRATOR_SESSION_ID
Worker sessions can already be messaged by the orchestrator via `ao send`,
but the reverse direction was undiscoverable: workers had no way to learn
their orchestrator's session ID. The transport already exists (`ao send`
routes to any session in the project, and the orchestrator's ID is
deterministic at `${sessionPrefix}-orchestrator`) — only the discoverability
piece was missing.
Changes:
- Add `orchestratorSessionId?: SessionId` to `AgentLaunchConfig`.
- Populate it in spawnWorker and the worker restore path; deliberately
omit it for spawnOrchestrator (an orchestrator is not its own parent).
- Each agent plugin (claude-code, codex, opencode, aider, cursor, kimicode)
now injects `AO_ORCHESTRATOR_SESSION_ID` into the agent env when the
field is present.
- Worker prompt preamble teaches the new channel with two restraints:
(1) only ping when genuinely blocked, (2) always prefix with
`[from $AO_SESSION_ID]` because the orchestrator receives raw input
with no `from:` metadata.
No new CLI verb, no new file format, no new transport — just env wiring
plus prompt copy.
Closes#1786
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: only set AO_ORCHESTRATOR_SESSION_ID when orchestrator metadata exists
Greptile review on #1787: spawn() unconditionally injected the env var
for every worker, including ad-hoc `ao spawn` workers in projects that
never had an orchestrator running. The AgentLaunchConfig JSDoc claimed
the field was unset for ad-hoc sessions, but the implementation didn't
honor it — so a worker following the prompt's `ao send
$AO_ORCHESTRATOR_SESSION_ID …` instruction would get an opaque
"session does not exist" error.
Both spawn() and restore() now check `readMetadataRaw(sessionsDir,
"<prefix>-orchestrator")` and only propagate the field when the
orchestrator's metadata is actually on disk. Existence-on-disk is the
right signal: if metadata was ever written for the canonical
orchestrator ID, the orchestrator workflow is in play for this project.
Tests updated:
- spawn: split into two cases — "passes when orchestrator exists" (now
spawns the orchestrator first) and "omits for ad-hoc workers".
- restore: added a third case for ad-hoc worker restore (no orchestrator
metadata) alongside the existing worker-with-orchestrator and
orchestrator-restore cases.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: document orchestrator-send command for POSIX, PowerShell, and cmd.exe
Greptile review on #1787: the prompt's `ao send $AO_ORCHESTRATOR_SESSION_ID
"[from $AO_SESSION_ID] …"` example is bash-only. On Windows PowerShell
(the default shell), bare `$AO_ORCHESTRATOR_SESSION_ID` resolves to
$null, so the command silently sends to an empty session ID instead of
the orchestrator. CROSS_PLATFORM.md flags exactly this footgun.
Both prompt variants now show the correct form for the three shells AO
supports as a first-class platform: POSIX bash/zsh, PowerShell
(`$env:NAME`), and cmd.exe (`%NAME%`). The agent picks the form for its
shell. Quotes added around the POSIX expansion as a defensive measure
in case the env var ever expands to whitespace.
prompt-builder tests now assert all three syntaxes appear in both the
full and no-repo prompts.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: literal-render orchestrator ID in prompt; auto-prefix [from <id>] in ao send
Two simplifications collapsed into the same feature now that the
worker→orchestrator dialogue lives in the prompt + send.ts only:
1. **Drop AO_ORCHESTRATOR_SESSION_ID env var entirely.** The orchestrator
session ID is deterministic (`${sessionPrefix}-orchestrator`) and known
at prompt-build time, so prompt-builder just renders it literally:
ao send my-orchestrator "<your message>"
No env var, no AgentLaunchConfig field, no per-plugin wiring, no
PowerShell/cmd.exe/POSIX shell-syntax variants. The orchestrator
existence check moves into session-manager's buildPrompt call site —
one place instead of duplicated across env injection + prompt mention.
2. **Auto-prefix `[from $AO_SESSION_ID]` in `ao send` itself.** The prompt
no longer teaches the agent to self-identify because that's
infrastructure's job. send.ts wraps the message when AO_SESSION_ID is
set, which covers all session→session traffic (worker→orchestrator,
orchestrator→worker, worker→worker). Humans running ao send from
their own terminal stay unprefixed.
Net: 21 files changed, +174 / −249. Zero plugin code touched. No
cross-platform shell footgun.
Files:
- types.ts: drop orchestratorSessionId field
- session-manager.ts: drop spawn/restore field injection; pass
orchestratorSessionId into buildPrompt instead, gated on metadata
existence on disk
- 6 agent plugins: drop AO_ORCHESTRATOR_SESSION_ID env injection + tests
- prompt-builder.ts: add orchestratorSessionId to PromptBuildConfig;
conditionally emit "Talking to the Orchestrator" section with literal
ID; remove the section from the static base prompts
- send.ts: auto-prefix when AO_SESSION_ID is set
- send.test.ts: 3 new tests for prefix-set / prefix-unset / SessionManager
delivery; existing tests preserved by clearing AO_SESSION_ID in beforeEach
- changeset: scope drops to ao-core + ao-cli only
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(web): allow renaming worker sessions in the sidebar
Closes#1647
Adds an inline rename UX to each worker session row in the sidebar. A
small pencil button appears on row hover; clicking it swaps the label
for an input pre-filled with the current title. Enter persists via
PATCH /api/sessions/:id, Escape cancels, and an empty value clears the
field — reverting the session to its default title.
The rename writes to the existing displayName metadata field, which is
now the highest-priority signal in getSessionTitle so a user-chosen
label always beats PR/issue titles. The session ID (ao-N) remains
canonical — only display surfaces are affected.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(web): gate displayName promotion on user-set flag
PR review flagged that promoting `displayName` to the top of
`getSessionTitle` regressed every existing session: spawn-time
auto-derived `displayName` would shadow live PR/issue titles for
sessions the user never explicitly renamed.
Adds a `displayNameUserSet` boolean flag to SessionMetadata and
DashboardSession. The dashboard fallback chain promotes `displayName`
above PR/issue titles only when this flag is true; auto-derived
spawn-time values stay at their original position (below PR/issue,
above userPrompt).
PATCH /api/sessions/:id sets `displayNameUserSet=true` when the user
types a name, and clears it when they revert. Sidebar gates its
displayName preference on the flag too, so non-renamed rows keep the
existing branch-first behavior.
Also addresses review #3 (rename-while-pending pre-fill) and #4
(double-submit guard on Enter+blur).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(web): address review feedback on session rename PR
- ProjectSidebar: gate effective displayName on displayNameUserSet so
auto-derived spawn-time names no longer shadow live PR/issue titles
in the sidebar (mirrors the gate already in format.ts:getSessionTitle).
Adds a regression test.
- ProjectSidebar: drop unreachable `?? currentTitle` from startRename
initial value — the right side of the nullish-coalescing always returns
a string, so the fallback is already handled by the `|| currentTitle`
on the next line.
- ProjectSidebar: reveal rename pencil on `group-focus-within` so keyboard
users tabbing through the session links discover the affordance, not
just pointer users.
- globals.css: change rename button + input border-radius from 3px to 0
to match the repo's --radius-base: 0 design rule for UI controls.
- core/metadata: accept legacy "on"/"off" strings for displayNameUserSet
in readMetadata for parity with prAutoDetect (defensive — the storage
write path already converts to boolean via unflattenFromStringRecord).
Adds coverage for all six accepted forms.
- web/serialize: drop dead `=== "on"` check on displayNameUserSet —
Session.metadata is Record<string, string> and the value can only ever
be "true" / "false" after flattenToStringRecord.
Refs #1647.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: keep tmux session alive after agent exit (closes#1756)
Two related fixes:
1. runtime-tmux: append `exec "${SHELL:-/bin/bash}" -i` to the launch
command so the pane drops to an interactive shell when the agent
exits, instead of letting the empty pane take down the whole tmux
session. The lifecycle still detects agent termination via
`agent.isProcessRunning` and transitions the session to
`agent_process_exited` — the runtime just stays usable so the user
can run shell commands or manually re-launch the agent.
2. mux-websocket: add a `tmux has-session` guard at the top of
`pty.onExit`. When the tmux session is genuinely gone (e.g. `ao
stop` killed it out from under a still-subscribed dashboard), skip
the three doomed `attach-session` spawns introduced by the
MAX_REATTACH_ATTEMPTS bound in #1640 and notify subscribers
immediately. The bound from #1640 still covers transient
tmux-server hiccups where the session does still exist.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(mux): make tmuxHasSession async to avoid blocking the event loop
The has-session probe added in #1756 ran via execFileSync inside
node-pty's onExit callback, freezing every WebSocket connection,
HTTP request, and in-flight terminal for up to the 5 s subprocess
timeout whenever an agent exited and tmux was slow to respond.
Switch tmuxHasSession to promisified execFile and await it from the
onExit handler, mirroring the execFileAsync pattern in runtime-tmux.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(workspace-worktree): restore re-attaches existing branch instead of recreating with -b
Restoring a session whose worktree directory was cleaned up but whose
branch still existed locally would 422 with `fatal: a branch named <X>
already exists`. The recovery path in `restore()` unconditionally fell
through to `git worktree add -b`, even though `destroy()` deliberately
preserves session branches so the user's commits aren't lost.
When the local branch already exists, restore now clears any stale
worktree registration at the target path and retries `git worktree add
<path> <branch>` (no -b/-B). The existing -b fallback is preserved
verbatim for the case where the local branch is genuinely missing
(only the remote ref exists). -B is intentionally not used — it would
force-reset the branch back to the base ref and silently discard the
session's commits, which is the opposite of restore's intent.
Test coverage:
- 6 new unit tests covering the recovery path, cleanup tolerance,
error propagation, and "no -b/-B" invariants
- 2 updated existing unit tests (now mock the new refExists check)
- 2 new integration tests exercising real git: branch preservation
on clean restore, and recovery from a dirty teardown that left a
stale registry entry
Closes#1741
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(workspace-worktree): explicitly create main branch in restore integration tests
CI runs git with a different `init.defaultBranch` than the local dev
environment, so the bare clone has no `main` branch when the test
attempts to push. Mirror the existing tests in this file (which also
call `git switch -c <branch>` before the first commit).
Fixes integration-test failures on PR #1742.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(workspace-worktree): rmSync stale workspace dir before retry
Follow-up to the previous commit on this branch. The recovery path
cleared the git worktree registry but didn't touch the filesystem, so
when restore was triggered by a stale junk directory at the workspace
path (workspace.exists() returns false because rev-parse fails on a
non-working-tree dir), the retry would fail with the same error:
fatal: '<workspacePath>' already exists
Replace the inline `worktree prune` cleanup with a call to the existing
`clearStaleWorktreePath()` helper, which handles all three states:
- dir gone → no-op
- dir present and not registered → rmSync
- dir present and still registered after prune → throws (safety:
never delete a registered worktree)
This mirrors how create() already handles the same stale-state cases
upfront via clearStaleWorktreePath at the top of its flow.
Test coverage:
- 1 new unit test: rmSyncs a stale workspace directory before retry
- 1 new unit test: refuses to rmSync a still-registered worktree dir
(data safety — error must propagate, not be swallowed)
- 1 new integration test on real git: dir physically present as
non-working-tree leftover, restore must rmSync it before retry,
and the session commit must survive
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(workspace-worktree): extract restore helpers, drop redundant prune
Addresses review feedback on PR #1742:
1. Extract two named helpers, reattachExistingBranch and
createBranchFromBase, so restore()'s catch block reads as the
bifurcation it actually is — 2 lines per branch, no nested
try/catch hierarchy. Behavior is unchanged.
2. Drop the redundant `worktree prune` that ran inside the recovery
path (via clearStaleWorktreePath). The entry-point prune in
restore() is sufficient. reattachExistingBranch now inlines the
existsSync + isRegisteredWorktree + rmSync sequence directly,
keeping the data-safety guard ("refuse to rmSync a registered
worktree") intact but skipping the second prune call.
The catch block shrinks from ~46 lines to 12 (the rest moves into
the helpers, where the docstrings can explain WHY each branch exists
without cluttering the call site).
Tests: same 64 unit + 13 integration tests still pass — the mock
sequences in the recovery-path tests no longer expect a second prune
call, since the new code doesn't make one.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(workspace-worktree): address Copilot review on PR #1742
Two real concerns flagged in inline review:
1. isRegisteredWorktree did strict string equality on paths. If
`workspacePath` was passed in a non-canonical form (trailing slash,
".." segments) and git reported the canonical path, the check would
false-negative — and the subsequent rmSync in cleanupStaleWorkspacePath
would silently delete a still-registered worktree (data loss). Fix
by resolve()-normalizing both sides before comparison.
2. createBranchFromBase (the "branch missing locally" recovery path)
skipped the stale-path cleanup that reattachExistingBranch did. So
if `workspacePath` had a stale dir AND the branch was missing,
`git worktree add -b ...` would fail with the same "<path> already
exists" error this PR was fixing for the re-attach case. Fix by
factoring the cleanup into cleanupStaleWorkspacePath, called from
both helpers.
Test coverage:
- Unit: path normalization safety — workspacePath with trailing slash
vs canonical registered path must still throw "still registered"
(proves rmSync is NOT called)
- Unit: createBranchFromBase clears stale dir before -b add
- Integration: branch missing locally + stale dir at workspacePath →
restore must clean dir AND recreate branch from origin (commit
preserved end-to-end on real git)
Existing 2 "branch missing" tests updated to mock the new cleanup
calls in createBranchFromBase.
66 unit tests + 14 integration tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* ci: drop windows-latest from typecheck matrix
tsc is OS-agnostic; the windows-latest run duplicates the ubuntu pass
and adds ~5 min of CI time per push. Real Windows regressions surface
in the unit/web test matrix, which still runs on both OSes.
* ci: collapse typecheck matrix to a plain ubuntu-latest job
With windows-latest dropped, the single-OS matrix was just indirection
and produced a noisy 'Typecheck (ubuntu-latest)' job name. Use a direct
runs-on instead.
* 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>
* fix(cli): refuse to spawn when daemon is not polling the project
`ao spawn` and `ao batch-spawn` used to print a stderr warning and then
create the session anyway when the running AO daemon did not include the
target project in its polling set (or when no daemon was running at all).
The resulting sessions got full worktrees and tmux panes but no
lifecycle reactions — CI-failure routing, review comments, revive
transitions, and the event log were silently dead.
Promote the warning to a hard error so sessions are never created in a
state where the lifecycle manager won't run for them. The error message
tells the user which `ao start` invocation will fix it.
Closes#1455
* test(cli): cover batch-spawn daemon-polling enforcement
`spawn` and `batch-spawn` share the `ensureAOPollingProject` helper, but
only `spawn` had tests for the new fail-fast behavior. Add matching
tests for `batch-spawn` so a future refactor that breaks its guard is
caught.
---------
Co-authored-by: Prateek <karnalprateek@gmail.com>
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
* fix(web): disable xterm scrollback to prevent right-side clipping
FitAddon.proposeDimensions() reserves 14px (DEFAULT_SCROLL_BAR_WIDTH)
for the scrollbar when scrollback > 0. The custom CSS sets the actual
scrollbar to 5px with overflow-y: overlay (deprecated in Chrome 114+).
This mismatch causes the terminal to calculate the wrong number of
columns — content gets clipped under the scrollbar on the right side.
tmux already provides scrollback and copy-mode, so xterm's scrollback
is redundant. Setting scrollback: 0 eliminates the scrollbar entirely
and makes FitAddon's width calculation match the rendered output.
Fixes#1677
* chore(web): refresh stale scrollback comments per greptile
* fix(web): reset letter-spacing on .xterm to fix right-side char clipping
The body has letter-spacing: -0.011em (~-0.176px at 16px) for typography
refinement. xterm's DOM renderer measures cell width with that spacing
inherited (~7.83px), then sets an inline letter-spacing override on
.xterm-rows that cancels the body inherit, leaving glyphs to render at
their natural ~8.00px width.
The mismatch — measured 7.83px cells vs rendered 8.00px glyphs —
accumulates as cols grow, eventually overflowing .xterm-rows > div and
getting clipped by its overflow: hidden. At 124 cols the drift was
~21px, chopping ~3 chars off the right edge.
Resetting letter-spacing on .xterm makes both phases agree and reduces
the drift to sub-pixel rounding (~2px worst case at any reasonable
cols).
---------
Co-authored-by: AO Bot <ao-bot@composio.dev>
Co-authored-by: Prateek <karnalprateek@gmail.com>
* fix(web): drop = prefix from set-option in mux-websocket (closes#1714)
In tmux 3.4 the `=` exact-match prefix only works with `has-session` and
`attach-session`. For `set-option`, the prefix is silently ignored, so
`mouse on` and `status off` never get applied — breaking scroll wheel in
the dashboard terminal and leaving the tmux status bar visible.
Use the bare session id for the two `set-option` calls; keep `=` on
`attach-session` where it is correct.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(web): move exactTmuxTarget next to attach-session
Address review feedback: the `=`-prefixed target is only used by
attach-session, so declare it adjacent to that call. Comment now
sits above the set-option calls it actually explains.
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>
When `ao start` finds an existing daemon and the user picks "Add <dir>",
the project is written to the global config but the dashboard's cached
services (loaded once into globalThis) never see it, so visiting the new
project page renders notFound(). Call notifyProjectChange() after the
write — same pattern as attachAndSpawnOrchestrator — so the dashboard
invalidates its cache before the browser opens.
* fix(web): bound PTY re-attach loop with grace-period counter reset (#1639)
When `ao stop` (or any external action) kills a tmux session out from
under a still-subscribed dashboard, the mux server's PTY exit handler
attempts to re-attach. The MAX_REATTACH_ATTEMPTS=3 cap was supposed to
prevent unbounded respawning, but it was never engaging because the
counter was reset to 0 immediately after each "successful" `open()` —
where success only meant the new PTY was *spawned*, not that it
*survived*. When the underlying tmux session is gone, attach-session
exits ~40 ms after spawn, the exit handler fires again with counter=0,
and the loop runs at ~80 spawns/sec.
Diagnostic data captured on the issue: a single 1.5-second burst
produced 119 spawn↔exit cycles, raising the process's PTY fd count
from ~15 to ~153. Sustained for a few seconds, this exhausts the
macOS system PTY pool (kern.tty.ptmx_max=511), after which nothing
on the system can spawn a new PTY (tmux, VS Code terminal, ao spawn,
etc.) until the leaking process is killed.
Fix:
- Remove the `terminal.reattachAttempts = 0` reset inside the exit
handler.
- Schedule a delayed reset via setTimeout in `open()`, gated on the
closure-captured `pty` reference still being terminal.pty after
REATTACH_RESET_GRACE_MS (5 s).
Effect: tight crash loops cannot reset the counter (PTY exits before
grace expires) and hit MAX_REATTACH_ATTEMPTS within ~150 ms, after
which the server emits "exited" and stops respawning. A long-lived
PTY that crashes hours later still gets a fresh retry budget.
Adds an integration test that reproduces the runaway scenario by
killing the tmux session externally and asserting "exited" arrives
within 2 s. Without this fix the test hangs and times out — the
exact symptom of the bug.
Note: this addresses the dominant runaway behaviour. A separate
~1 fd/cycle leak in node-pty 1.1.0 itself (each spawn opens 3
PTY-class fds in the parent, each exit releases only 2) remains and
will be tracked separately — likely a node-pty upgrade.
Fixes: #1639
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fixup(web): track grace timer + add recovery test (#1639 PR review)
Address two PR review notes on #1640:
1. Greptile P2 — store the grace-period timer handle on ManagedTerminal
and clearTimeout it in the unsubscribe cleanup path. The closure
guard already prevented any incorrect counter reset, so this is
tidiness rather than a bug fix: it eliminates the up-to-5 s window
where the timer's closure kept the killed PTY and evicted terminal
object reachable. Also clears any prior timer when scheduling a new
one in open() so back-to-back re-attaches don't pile up dead closures.
2. Copilot — add an integration test for the recovery path. The
existing runaway test exercises the case where the counter must NOT
reset (PTY crashes inside grace); the new test exercises the case
where the counter MUST reset (PTY survives grace, then crashes
later). Without the grace timer firing correctly, a single transient
blip during startup would permanently consume the retry budget.
Test takes ~5.5 s because it uses the production grace period; per-test
timeout raised to 15 s. Vitest runs tests in parallel so this doesn't
serialize the suite.
Refs: #1639, #1640
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
* fix(runtime-tmux): disable tmux status bar at session creation
Closes#1709.
#1683 added `set-option ... status off` to `core/src/tmux.ts::newSession()`,
but no code in the workspace imports or calls that helper — worker sessions
are spawned by the `runtime-tmux` plugin, which was not modified. The green
status bar was therefore still visible at session creation, only being
suppressed once the web layer's WebSocket connection ran its own
`set-option` (with a flash window before that).
Add the same call to runtime-tmux immediately after `tmux new-session` so
the bar is hidden from the moment the session exists, regardless of
whether anyone ever attaches via the web terminal.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(core): remove unused newSession helper
The `newSession` function in `core/src/tmux.ts` and its `newTmuxSession`
re-export in `core/src/index.ts` had zero callers anywhere in the
workspace (verified via grep across packages/, excluding dist and tests).
Worker sessions are spawned by the `runtime-tmux` plugin, which has its
own implementation. The status-bar fix from #1683 lived only in this
helper and was therefore never executed — see #1709 and the prior
commit which moves the fix to the actual spawn path.
Removes:
- `newSession` and `NewSessionOptions` from core/src/tmux.ts
- `newSession as newTmuxSession` re-export from core/src/index.ts
- The corresponding test block in core/src/__tests__/tmux.test.ts
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(core): demote unused GhTraceResult export to internal
`GhTraceResult` was exported from `core/src/gh-trace.ts` but never
re-exported from `core/src/index.ts` and never imported anywhere in
the workspace. Its only consumer is `writeTraceEntry()` inside the
same file, where it's used as a parameter type. Demoted to a private
interface.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(runtime-tmux): kill session if set-option fails
Move the `set-option ... status off` call inside the existing try/catch
so a failure (e.g. the 5-second tmux command timeout firing on a slow
host) triggers `kill-session` cleanup instead of leaving an orphaned
tmux session behind. Renames the surfaced error to
"Failed to configure or launch session" since the try block now covers
both configuration and the launch send-keys.
Adds a regression test that asserts kill-session is called when
set-option throws.
Addresses review feedback on #1711.
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>
* feat(core): add per-project env block to ProjectConfig
Adds an optional `env: Record<string, string>` field to ProjectConfig
that forwards environment variables into worker session runtimes. Useful
for scoping per-project tokens like GH_TOKEN to pin gh auth per project.
The merge order in session-manager runtime.create environment is:
agent.getEnvironment → PATH/GH_PATH → AO_AGENT_GH_TRACE → project.env →
AO_* internals. AO-internal vars always win over user-supplied values.
Closes#169
* fix(core): protect PATH and GH_PATH from project.env override
Per greptile review on #1679: spreading `project.env` after PATH/GH_PATH
let a user-supplied PATH or GH_PATH silently clobber the carefully
constructed agent path. Apply the same "protected key" treatment as
AO_* internals — spread project.env BEFORE PATH/GH_PATH/AO_AGENT_GH_TRACE
at all three runtime.create call sites (worker spawn, orchestrator spawn,
restore). Extend the precedence test to assert PATH and GH_PATH still
win over a colliding project.env entry.
---------
Co-authored-by: Prateek <karnalprateek@gmail.com>
* rebase: forward branch onto main + resolve activity-events kind union conflict
* feat(core): wire scm/runtime/agent plugin-call failure events
Adds activity-event evidence for previously-silent failure paths in
lifecycle-manager.ts so the RCA agent can answer 'why did X happen?':
- scm.batch_enrich_failed (line 617 catch)
- scm.detect_pr_succeeded (line 658 success path)
- scm.detect_pr_failed (line 664 catch)
- scm.review_fetch_failed (line 1517 catch)
- scm.poll_pr_failed (line 1132 catch)
- runtime.probe_failed (line 938 catch)
- agent.process_probe_failed (lines 1054 + 1139 catches, with where field)
- agent.activity_probe_failed (line 1062 outer catch)
Plus 6 new tests covering the call shapes.
Invariants preserved (per CLAUDE.md):
- B1 state-mutate-before-emit: each emit follows existing observer call
- B2 never throws: recordActivityEvent best-effort by design
- B3 re-entrancy guard unchanged
- B4 Promise.allSettled semantics unchanged
* feat(core): wire reaction lifecycle activity events
Adds AE evidence around reaction triggers, escalations, and failures so
RCA can answer 'did AO try to auto-fix this? did it succeed?':
- reaction.action_succeeded (combined for send-to-agent / notify / auto-merge,
with data.action variant) — fires after each successful reaction action
- reaction.send_to_agent_failed — fires in the previously-silent catch when
sessionManager.send throws inside a send-to-agent reaction
- reaction.escalated — fires alongside the existing notifyHuman escalation
with data.escalationCause = 'max_retries' | 'max_duration'
Plus 3 new tests covering the call shapes.
Invariants preserved: emits land after the existing notifyHuman/return
paths so state mutation order is unchanged.
* feat(core): wire auto-cleanup, poll-cycle, detecting escalation events
Adds AE evidence around session destruction, poll loop failures, and the
detecting→stuck transition so RCA can answer 'when did my session get
cleaned up?', 'did the polling loop crash?', and 'why did AO mark this
session stuck?':
- session.auto_cleanup_deferred — agent busy, cleanup deferred
- session.auto_cleanup_completed — kill succeeded, runtime + worktree gone
- session.auto_cleanup_failed (level=error) — kill threw, session stays merged
- lifecycle.poll_failed (level=error) — pollAll outer catch fired
- detecting.escalated — first cycle that promotes detecting→stuck, with
cause = max_attempts | max_duration. Guarded by detectingEscalatedAt
metadata so it fires once per escalation, not on every poll while stuck.
Plus 5 new tests covering the call shapes and the idempotency guard.
Invariants preserved:
- Auto-cleanup events fire AFTER existing observer.recordOperation (B1)
- detecting.escalated emits ONCE per escalation (invariant B9 in
.context/lifecycle-manager-instrumentation.md)
- poll_failed emits inside the existing pollAll catch — flow unchanged
* feat(core): wire report_watcher.triggered activity event
Adds AE evidence when the report watcher fires (no_acknowledge / stale_report
/ agent_needs_input). RCA: 'AO thinks my agent is stuck — why?'
- report_watcher.triggered (level=warn) — emitted alongside the existing
observer.recordOperation, only when a trigger is non-null (per invariant
in .context/lifecycle-manager-instrumentation.md §B9)
Plus 1 test exercising the no_acknowledge trigger path.
* fix(core): one-shot guard on report_watcher.triggered AE emit
Live-observed regression: report_watcher.triggered fired 116 times in
production over a few hours because the emit was unguarded and re-fired
every 30s poll while a trigger stayed active. Symptom was massive event
flood for stuck/no-acknowledge/stale conditions.
Fix: gate the emit on the existing isNewTrigger variable (same one-shot
guard pattern used for detecting.escalated). The observer.recordOperation
above remains unguarded by design (it's a metric/heartbeat); the AE trail
is for actionable evidence only.
Adds a regression test that drives the same trigger across two polls and
asserts the AE event fires only on the first.
* fix(core): address Greptile feedback on PR #1620
Two findings from Greptile (issue same as Codex P2 #1):
1. scm.batch_enrich_failed omitted projectId/sessionId — when the
lifecycle worker is project-scoped (deps.projectId set), this event
is effectively project-scoped too. Without projectId, queries like
`ao events list --project todo-app --type scm.batch_enrich_failed`
return zero results, defeating the purpose of the instrumentation.
Fix: pass scopedProjectId when set. Unscoped (multi-project) supervisors
still leave projectId null because the batch crosses project boundaries.
2. Misleading field name pendingSinceMs in session.auto_cleanup_deferred
data — the local variable of the same name is a Unix epoch timestamp,
but the data field stored `Date.now() - pendingSinceMs` (an elapsed
duration). RCA agents would mis-interpret it as a timestamp and compute
a 1970-era "pending since" date. Renamed to pendingElapsedMs.
* fix(core): address Codex review on PR #1620
- lifecycle.poll_failed: keep summary generic, route raw error text
through `data.errorMessage` only. sanitizeSummary just truncates;
sanitizeData redacts credential URLs. Since FTS5 indexes summary,
interpolating subprocess error output (which can include
https://x-oauth-basic:TOKEN@github.com/... from git/gh) made
credentials persistently searchable.
- reaction.escalated: expand escalationCause to
"max_retries" | "max_attempts" | "max_duration" and mirror the
trigger checks. Numeric escalateAfter is an attempt-count gate, not
a duration; previously got misattributed to "max_duration" whenever
retries was unset (built-in defaults use {escalateAfter: 2}).
Adds two regression tests as guards for both behaviors.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(core): replace import() type annotation with import type to satisfy lint
CI's @typescript-eslint/consistent-type-imports rule rejects inline
`typeof import("../activity-events.js")` inside the vi.mock factory.
Hoist it to a top-level `import type * as ActivityEventsModule` so the
type lives in a proper import declaration; vi.mock factory resolution
is unaffected (type-only imports emit no runtime code).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(core): keep report_watcher.triggered summary generic to plug FTS leak
auditResult.message for the agent_needs_input trigger embeds the
free-form report.note supplied via `ao report --note "..."`. Since
sanitizeSummary only truncates and FTS5 indexes the summary column,
a note containing a credential URL would be persistently searchable
from the events DB. Same class of bug as the prior poll_failed fix.
Summary becomes generic ("<trigger> triggered"); the full message
continues to flow through `data.message` where sanitizeData redacts
credential URLs.
Adds a regression test that seeds a needs_input report with a
credential-bearing note and asserts the summary stays clean.
Reported by @ashish921998 in PR #1620.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(core): redact token-shaped secrets in activity-event data (P1)
Both `summary` and `data` columns are FTS5-indexed (events-db.ts:58-59).
Prior fixes moved raw error/report text from `summary` to `data.message` /
`data.errorMessage`, on the assumption that sanitizeData() would scrub it.
That assumption was incomplete: sanitizeData only redacted credential URLs
and entire values under sensitive *key* names. Token-shaped substrings
(`Bearer …`, `ghp_…`, `sk-…`, JWTs, `AKIA…`, ALL_CAPS_TOKEN=value) under
non-sensitive keys like `message`/`errorMessage` were stored as-is and
made searchable via FTS.
Adds a TOKEN_PATTERNS array applied to every string value during
sanitization, plus a 500-char per-string cap (matching sanitizeSummary's
existing precedent — limits blast radius if a new token format slips past
the patterns).
Patterns cover: Bearer headers, GitHub PATs (classic + fine-grained),
OpenAI/Anthropic sk- keys, Slack xox- tokens, AWS access key IDs, JWTs,
and ENV-style assignments scoped to ALL_CAPS keys ending in
TOKEN/PASSWORD/SECRET/etc.
Tests:
- 10 new sanitizeString unit tests (one per token shape + prose-preservation
regression guard + 500-char cap + nested array/object recursion)
- 1 new FTS5 integration test that drives recordActivityEvent → real SQLite
→ both direct row read and FTS MATCH must return zero token leakage
Test fixtures use string concatenation across the prefix boundary so
literal token shapes don't appear in source (gitleaks pre-commit guard).
Reported by @ashish921998 in PR #1620.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(core): bound credential-URL regex to prevent ReDoS (CodeQL alert)
CodeQL flagged CREDENTIAL_URL_RE as polynomial: input shaped like
`http://http://http://...` with no terminating `@` caused O(n²)
backtracking because the unbounded `[^@\s]+` greedily spanned multiple
`http://` prefixes before failing at end-of-string and walking back.
Two-part fix:
1. Exclude `/` from the userinfo character class — this is also semantically
correct since RFC 3986 userinfo cannot contain unencoded `/`.
2. Add a hard length cap (200 chars) on the userinfo segment as a belt-and-
braces guard against future pathological inputs.
The fix is observable: 14KB pathological input completes in single-digit
ms post-fix vs multiple seconds pre-fix. Adds a regression test that
runs the pathological input through the full sanitize pipeline and
asserts <100ms completion.
Reported by GitHub Advanced Security on PR #1620.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(core): replace CREDENTIAL_URL_RE regex with linear scan
The bounded {1,200} quantifier in CREDENTIAL_URL_RE let credential URLs
with >200-char userinfo pass through unredacted. Since data is FTS5-indexed,
those credentials became searchable (P1 from PR #1620 review).
Replace the regex with a simple linear scan (redactCredentialUrls) that:
- Has no length limit — scans until @, space, or /
- Is O(n) with no regex backtracking (fixes CodeQL polynomial-regex alert)
- Matches http:// and https:// case-insensitively (preserves old /gi behavior)
Adds regression tests for:
- >200-char userinfo bypass
- URLs without userinfo (no false positives)
- Multiple credential URLs in one string
- Pathological ReDoS-shaped input still completes in <100ms
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: AO Bot <ao-bot@composio.dev>
* fix(core): disable tmux status bar at session creation
The tmux green status bar was visible in web terminals because
newSession() never set status off. The global tmux config has
status on, and the web layer only disabled it on WebSocket connect.
Now we hide the status bar immediately after session creation so it's
never visible, regardless of when (or if) the web UI connects.
Fixes#1682
* test(core): update tmux newSession test for status off call
The new set-option status off call adds a 5th execFile invocation.
Update the test expectations to match the new call sequence.
---------
Co-authored-by: AO Bot <ao-bot@composio.dev>
* 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>
* feat(pipeline): v1.1 — DAG, parallel scheduling, Stage.routes (#1630)
Adds dependsOn-based DAG scheduling to the pipeline reducer:
- Stage.dependsOn: explicit dependency declarations between stages.
- Stage.routes.when: conditional activation predicate evaluated when all
referenced upstream stages reach a terminal state. Predicate forms are
a hardcoded minimal union (allSucceeded / anySucceeded / anyFailed); the
typed DSL lands in v1.3.
- Cycle detection runs at config load via Zod superRefine — bad configs
are rejected with an error that names the cycle (e.g. "a → b → a").
Unknown dependsOn / routes references and self-dependencies fail there
too, alongside duplicate stage-name detection.
- Parallel stage execution capped by Pipeline.maxConcurrentStages
(default still 1 per spec). Independent stages run concurrently when
the cap is lifted; declaration order is preserved as slot priority so
linear pipelines (no dependsOn) stay behaviorally identical to v0.
- Cascade skips run to fixpoint inside one reducer step: skipping a stage
can make a downstream stage's routes evaluate to false, marking it
skipped, and so on. Each transition emits a pipeline.stage.terminated
observation matching the existing schema.
Multi-pipeline support (N named pipelines per project, --pipeline flag) was
already wired by v0.3 and is preserved here; new tests verify cross-pipeline
config validation.
The new DAG logic lives in packages/core/src/pipeline/dag.ts so reducer.ts
stays focused on event-shape transitions. startableStageEffects is removed
from reducer-helpers.ts since scheduleAfterChange supersedes it.
Tests:
- 19 new vitest cases in pipeline-dag.test.ts cover cycle detection,
parallel scheduling, dependsOn gating, routes skip + cascade, and
multi-pipeline validation.
- All 1,152 existing core tests still pass.
Closes#1630
* fix(pipeline): close routes-graph deadlocks at config load (#1630)
Addresses three review findings on the v1.1 DAG validation:
- **Routes-only cycles deadlock the run.** `findFirstStageCycle` (renamed
from `findFirstDependencyCycle`) now traverses the union of `dependsOn`
and `routes.when.stages` edges. A pair of stages whose `routes` reference
each other but with empty `dependsOn` would otherwise leave both stages
waiting on each other in `arePreconditionsTerminal` forever — the cycle
finder caught nothing because there were no `dependsOn` edges.
- **Self-routes references hang the stage.** A stage with
`routes.when.stages` containing its own name can never see its runtime
state become terminal, so `arePreconditionsTerminal` returns false
indefinitely. Added an explicit "cannot route to itself" check that
mirrors the existing self-dependsOn check. The cycle detector skips
trivial self-loops (`[X, X]`) so operators get one clear error per
cause instead of two.
- **Empty `routes.when.stages` arrays produced surprising semantics.**
`allSucceeded: []` was vacuously true (stage ran unconditionally),
`anySucceeded`/`anyFailed: []` were vacuously false (stage skipped on
trigger). Schema now requires `.min(1)` per predicate kind.
Cycle error wording changed from "dependsOn cycle" to "stage dependency cycle"
since both edge kinds contribute. Existing tests updated; four new tests
cover routes-only cycles, mixed dependsOn+routes cycles, routes self-refs,
and empty-stages rejection.
All 1,156 core tests pass.
* fix(pipeline): resume cascade-skipped stages; engine cycle defense (#1630)
Self-review pass 2 follow-ups:
- **`RUN_RESUMED` revives cascade-skipped stages.** When `STAGE_FAILED`
cascade-skipped pending downstream stages via `terminateRunFromState`,
they previously stayed `skipped` forever — `scheduleAfterChange` only
considers `pending` stages, so a DAG branch was permanently lost across
resume. Resume now resets `skipped` stages (alongside `failed`) back to
`pending` and lets the scheduler re-evaluate. Routes-driven skips that
are still unsatisfied after a successful retry are re-applied
automatically — no risk of falsely reviving a predicate-skipped stage.
- **Engine validates DAG cycles for programmatic Pipelines.** Cycle
detection used to live only inside Zod's `superRefine`. Pipelines built
in code and handed to `engine.startRun` (or CLI `triggerRun`) skipped
Zod and would have deadlocked with every cycle member stuck `pending`
forever. Extracted `findFirstStageCycle` into `dag.ts` and added a
`validatePipelineDag` runtime check called from both call sites.
- **`anyFailed` predicate documented as v1.1-limited.** Because
`STAGE_FAILED` immediately terminates the run, a downstream stage with
`routes.when.kind === "anyFailed"` never gets to evaluate true; rollback
branches need failure-tolerant scheduling (v1.2/v1.3 scope). Added a
"Known limitation" section to the JSDoc on `StageRoutePredicate` so
operators don't expect run-on-failure semantics from this PR.
- **Test coverage gaps closed.** Added cases for STAGE_FAILED in a
parallel pipeline (sibling outdated, downstream skipped), RUN_RESUMED
reviving cascade-skipped stages and re-skipping when routes are still
unsatisfied, and engine-level rejection of cyclic programmatic
Pipelines. Tightened the 3-cycle assertion to the exact path string.
All 1,160 core tests + 644 CLI tests pass.
* fix(pipeline): guard resume hijacks; revive outdated; engine.dispatch validates (#1630)
Self-review pass 3 follow-ups:
- **`RUN_RESUMED` refuses to hijack a loop owned by a newer run.**
After a stalled run terminates, its loop key is freed, so a fresh
TRIGGER_FIRED can claim it. Resuming the old stalled run then silently
overwrote `currentRunByLoop[key]` and dispossessed the active run of
its loop pointer — NEW_SHA_DETECTED, CONFIG_CHANGED, and the triggerRun
guard would then track the wrong run. The reducer now returns
`invalidTransition` when resuming a run whose loop key already points
at a different active runId.
- **`RUN_RESUMED` revives `outdated` stages too, recovering parallel
branches.** When a sibling fails and `terminateRunFromState` runs, any
branch that was *running* gets marked `outdated` (not `skipped`).
Round 2 only revived `skipped`, so the outdated branch was permanently
lost and any downstream stage dependent on it cascade-skipped after
resume. Outdated stages now get a fresh stageRunId and bumped attempt
just like failed retries; the CLI service allocates IDs for both.
- **`engine.dispatch` validates TRIGGER_FIRED.** Validation lived only on
`engine.startRun`, so any direct dispatch (tests, future
config-watcher injection) bypassed cycle detection. Both
`validatePipelineAgentModes` and `validatePipelineDag` now run on the
public dispatch boundary; `startRun` keeps its early validation so
errors surface before runId/stageRunId allocation.
Tests: added cases for the loop-hijack guard, outdated-stage revival,
missing-stageRunId rejection on outdated, and direct
`engine.dispatch(TRIGGER_FIRED)` validation. All 1,164 core tests +
644 CLI tests pass.
* fix(pipeline): single-validate startRun; outdated does not consume retries; resume requires terminal (#1630)
Self-review pass 4 follow-ups:
- **`startRun` no longer double-validates and can't leak runMetadata.**
Round 3's dispatch-level validation reopened a window where startRun
would set `runMetadata` between two synchronous validations: if the
registry mutated in between, the second throw left an orphaned entry
forever. `startRun` now validates once and dispatches via
`withLock(() => dispatchInline(...))` directly, bypassing dispatch's
redundant check on the internal path while keeping it on the public
`dispatch()` boundary for direct callers.
- **External cancellations no longer consume `stage.retries`.** Round 3
treated `outdated` stages as retries (bumped attempt, checked the cap),
but `outdated` is set when `terminateRunFromState` cancels a *running*
stage due to NEW_SHA_DETECTED, CONFIG_CHANGED, or a parallel-sibling
failure — not a stage failure. With `retries: 1`, one real failure plus
one mid-flight CONFIG_CHANGED used to leave the user with zero retries
for actual failure recovery. The revival loop now splits: `failed`
bumps attempt and consumes the cap; `outdated` keeps attempt and skips
the cap check.
- **`reduceRunResumed` rejects non-terminal runs.** Previously the only
guard lived in the CLI service. Direct dispatch (tests, future
config-watcher / programmatic injection) could re-arm a `running` run.
The reducer now returns `invalidTransition` when `run.loopState` isn't
terminal, parallel to the existing active-loop guard.
Tests: added cases for the outdated-doesn't-consume-retries semantics
(retries=1 + 1 fail + 1 mid-flight cancel still allows another resume) and
direct-dispatch rejection on a `running` run. Updated the prior outdated
revival test to assert attempt=1 (not bumped). All 1,166 core tests +
644 CLI tests pass.
* fix(pipeline): include stageRunId in stage.started observation (#1630)
Self-review pass 5 follow-up. Round 4 changed `outdated` revival to keep
the `attempt` counter unchanged (so external cancellations don't consume
the retry budget). That's correct, but it broke the implicit uniqueness
of `pipeline.stage.started` observations: a stage that runs → mid-flight
cancel (outdated) → revive → run again now emits two `stage.started`
events with the same `(runId, stageName, attempt)` triple. Any future
observation consumer that dedupes by that natural key would silently drop
the second event.
Fix: add `stageRunId` to the observation payload. `stageRunId` rotates on
every retry/revival (the CLI service / engine allocate a fresh id each
time), so it's the only field that uniquely identifies *this* execution.
Surgical addition; no other consumer of the `stage.started` shape exists
yet, so this is a forward-compatible additive change.
* fix(core): adopt orphaned orchestrator worktrees (#1641)
* fix: address review feedback on worktree adoption
- Normalize CRLF line endings in parseWorktreeList for cross-platform support
- Collapse duplicate classifySpawnError payload blocks into single condition
- Filter prunable/deleted worktree entries in findManagedWorkspace
- Add GIT_TIMEOUT to git() helper for all execFileAsync calls
- Add tests for prunable entries and CRLF parsing
* fix: update test assertions for git() helper timeout
All git() calls now pass timeout: GIT_TIMEOUT to execFileAsync.
Update toHaveBeenCalledWith assertions to include the new option.
postCreate sh -c calls remain unchanged (direct execFileAsync).
* fix: mock existsSync in findManagedWorkspace tests
The existsSync(entry.path) filter added for prunable worktree detection
needs existsSync to return true for valid worktree paths in adoption tests.
* fix: use mockReturnValueOnce to prevent existsSync mock leaking
vi.clearAllMocks() does not reset mockReturnValue, only mock history.
Using mockReturnValueOnce ensures existsSync stubs don't leak to
subsequent tests and cause clearStaleWorktreePath to consume git mocks.
---------
Co-authored-by: AO Bot <ao-bot@composio.dev>
* refactor(core): extract hasRecentCommits helper into @aoagents/ao-core
Deduplicate the byte-identical hasRecentCommits(workspacePath) helper
that was copy-pasted between agent-aider and agent-cursor. Exposes the
helper from core with a parameterized window so future agent plugins
using git-commit-based activity detection can share it.
Closes#1423
* test(core): make hasRecentCommits custom-window test discriminate on the parameter
The previous assertion passed the default (60) to hasRecentCommits, so a
bug where windowSeconds was silently ignored would still have passed.
Use a commit backdated ~2 minutes and assert both a 30s window excludes
it and a 600s window includes it — proving the parameter is forwarded
to `git log --since=...`.
Addresses Greptile review on #1437.
---------
Co-authored-by: Prateek <karnalprateek@gmail.com>
* chore(cli): remove deprecated 'ao init' command
Delete the `init` command and its deprecation shim. `ao start` already
auto-creates the config on first run in an unconfigured repo, so the
separate entry point is redundant.
- Remove `packages/cli/src/commands/init.ts` and its test.
- Remove `registerInit` call from the CLI program.
- Drop `createConfigOnly()` from start.ts (only the init shim used it);
export `autoCreateConfig` so the existing default-config test can
invoke it directly.
- Update user-facing "Run `ao init` first" messages in `verify`/`status`
to point to `ao start`.
- Refresh stale `ao init` references in ao-doctor, onboarding test,
openclaw setup doc, and the config/types doc comments.
Closes#1420
* docs: remove ao init website docs
Agent-Logs-Url: https://github.com/ComposioHQ/agent-orchestrator/sessions/41663963-ca49-4673-982f-ca10dee68d31
Co-authored-by: miniMaddy <77185670+miniMaddy@users.noreply.github.com>
---------
Co-authored-by: Prateek <karnalprateek@gmail.com>
Co-authored-by: iamasx <adilshaikh4064@gmail.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: miniMaddy <77185670+miniMaddy@users.noreply.github.com>
* feat(pipeline): v0.3 — CLI surface for pipelines, stages, artifacts (#1629)
Adds the v0.3 CLI surface on top of the v0.1/v0.2 pipeline core:
- pipelines: block on ProjectConfigSchema (Zod, mirrors runtime Pipeline types)
- pipeline-service.ts — pure store/reducer adapter (testable, no engine dep)
- ao pipeline {list,runs,show,run,cancel,resume,migrate}
- ao stage show, ao artifact show
- Zsh tab completion for new verbs + pipelines / run ids / stage-run ids
CLI mutations route through the v0.1 reducer when possible (cancel) and
persist via the flat-file store. Stage execution is still owned by the
running orchestrator engine — CLI-triggered runs sit on disk until v0.4
lifecycle wiring picks them up.
Tested via vitest with a mocked store (35 new tests; full CLI 637/637,
core 1130/1130).
Closes#1629
* fix(pipeline): address self + greptile review on v0.3 CLI
Issues from the self-review:
1. resumeRun now dispatches a new RUN_RESUMED reducer event (symmetric with
RUN_CANCELLED) so CLI mutations stay reducer-routed.
2. triggerRun hydrates engine state from the store before dispatch and
throws LoopAlreadyActiveError when a non-terminal run already owns the
loop key.
3. resolveConfiguredPipeline accepts both the YAML map key and the `name`
field; pipeline run argument relabelled <pipeline> in help.
4. Tab-completion existsSync-gates the runs dir so it no longer materializes
empty pipelines/runs/stages/artifacts/loops directories per project.
5. `pipeline run` prints "v0.4 lifecycle integration will pick it up" and
warnIfAORunning surfaces a clear caveat when ao start is active.
6+7. errorMessage cleanup + retries cap are now reducer-owned: the new
RUN_RESUMED event refuses to bump attempt past stage.retries.
Greptile findings:
- P1: resumeRun rejects non-terminal runs (would double-spawn under v0.4).
- P2: cancelRun returns { run, alreadyTerminal }; the CLI surfaces a
yellow warning and suggests `ao pipeline resume` for stalled runs.
Tests: 6 new (reducer RUN_RESUMED happy path + retries cap + unknown run;
service trigger collision + stalled cancel + non-terminal resume reject +
retries cap reject; cancel-stalled CLI message). All suites green —
core 1133/1133, CLI 643/643.
* fix(lint): resolve ESLint errors in pipeline v0.3 files
- Merge duplicate ./types.js imports in config-schema.ts
- Add eslint-disable comment for consistent-type-imports in vi.mock
callbacks (matches pattern used in existing test files)
* fix(pipeline): address review issues from v0.3 CLI re-review
- Fix false success message when retries cap blocks resume: check
result.run.loopState !== "running" instead of resetStages.length === 0
so the yellow warning fires correctly on retry cap exhaustion
- Extract shared fail() to lib/cli-utils.ts; remove the three identical
copies from artifact.ts, stage.ts, and pipeline.ts
- Promote "manual" headSha sentinel to MANUAL_TRIGGER_SHA constant in
pipeline-service.ts with an explanatory comment
- Add test: ao pipeline resume warns on retry cap exhaustion
* fix(pipeline): fix --pipeline filter and JSDoc placement
- listRuns: accept pipelineId (map key) OR pipelineName in --pipeline
filter so tab-completion value always matches stored runs, even when
the pipeline's `name` field differs from the YAML map key
- Reorder MANUAL_TRIGGER_SHA + TriggerOptions before the triggerRun
JSDoc so the comment is adjacent to the function it documents
* fix(web): render empty-state in sidebar when no projects configured
A fresh-install user with zero projects saw a blank sidebar and had no
way to open AddProjectModal from it. The early-return was originally
projects.length <= 1 (#381), softened to === 0 in #927, but no empty-
state UI was added at the same time.
Replace the null branch with a small ProjectSidebarEmpty sibling that
reuses the existing header (with the + button wired to AddProjectModal),
shows a one-line explainer, and renders only the ThemeToggle in the
footer (the show-killed/show-done/settings buttons are meaningless with
zero projects).
* fix(web): mark sidebar + button SVGs aria-hidden
The decorative SVG inside the labeled + buttons (empty-state and
populated sidebar) should not be announced — screen readers should rely
on the button's aria-label. Adds aria-hidden="true" to both for
consistency.
* fix(web): always mount sidebar so empty-state renders on fresh installs
Dashboard previously gated the sidebar on projects.length >= 1, leaving
ProjectSidebarEmpty unreachable. ProjectSidebar handles both cases now,
so drop the gate and add a dashboard-level test for the zero-project
path.
* fix(web): honor collapsed prop in empty sidebar branch
ProjectSidebarEmpty discarded the collapsed prop, so on a fresh install
the wrapper shrank to 44px while the inner sidebar stayed 224px and
overlapped the main content. Render a 44px-wide rail with just the +
button when collapsed, matching the populated sidebar's collapse path.
* fix(qa): ISSUE-001 mobile kanban columns
* Fix terminal tmux targeting for session detail views
* fix(web): unblock event loop in tmux-name resolution and drop dup CSS
- mux-websocket: switch resolveExactTmuxName from execFileSync to
promisified execFile so a slow tmux call no longer stalls the
WebSocket message handler. Propagate async through TerminalManager.open
/ subscribe and the pty.onExit reattach path.
- globals.css: remove duplicate `.kanban-board { grid-template-columns:
minmax(0, 1fr) }` rule. The 767px breakpoint already covers it.
Addresses Greptile feedback on PR #1608.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(web): drop defensive tmux-name precheck
The has-session precheck in resolveExactTmuxName was UX padding around
the actual fix (using tmux's `=` exact-match prefix). Without the
precheck:
- attach-session fails naturally on a stale tmux name
- the existing reattach + exit-notify path surfaces the failure
- open()/subscribe() can stay sync — no event-loop concern, no async
cascade through the WS message handler
Net: -64 / +21 in mux-websocket.ts. Reverts the integration test that
relied on the precheck to its pre-PR id-based form.
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>
* feat(pipeline): v0.2 — agent executor, engine, supportedTaskModes validation
Bridges the v0.1 reducer to a real AO session:
- packages/core/src/pipeline/executors/agent.ts: spawns a fresh session
per stage via the existing SessionManager, injects a Layer 4 prompt
(stage descriptor + findings instructions), polls until the session
reaches `idle` AND the conventional findings file exists at
`{workspacePath}/.ao/pipeline-findings.jsonl`, parses the file as
ArtifactInput records, and kills the session through the normal
archive path. Sessions remain talk-to-able for their full lifetime.
- packages/core/src/pipeline/engine.ts: minimal wrapper that holds
EngineState, dispatches events through the v0.1 reducer, executes
the resulting effects (persist, append artifacts, START_STAGE,
CANCEL_STAGE), and exposes a re-entrant `tick()` the caller drives
off the existing 5s SSE poll (no new timer per C-14). v1.2's
command/builtin executors are out of scope: START_STAGE for those
kinds is synthesized into STAGE_FAILED so runs terminate cleanly.
- packages/core/src/pipeline/stage-prompt.ts: composes Layer 4 of the
prompt assembly — stage descriptor, mode, loop round, task body, and
schema-aware findings instructions.
- packages/core/src/pipeline/validation.ts +
PluginManifest.supportedTaskModes: agent plugins advertise the modes
they handle in their manifest (defaults to []). Pipelines fail at
load with PipelineConfigError when a stage routes to an agent that
doesn't claim the requested mode — never at runtime.
Vitest coverage: pipeline-agent-executor.test.ts (13 tests for spawn /
poll / harvest / cancel / error paths against a mocked SessionManager),
pipeline-validation.test.ts (mode validation), pipeline-engine.test.ts
(end-to-end run from trigger through findings persistence).
Out of scope (later sub-tasks): command/builtin executors (v1.2),
DAG/parallel scheduling (v1.1), CLI surface (v0.3), UI (v2.x).
Refs: #1628 — depends on v0.1 (#1636), targets pipelines branch.
* fix(pipeline): address Greptile review on v0.2 agent executor
Three review comments from Greptile, all valid:
1. P1 — `isFailedTerminalSession` was missing `"done"` from the
terminal-failure check, contradicting its own inline comment.
A session that hit `status === "done"` with `activity === "idle"`
and no findings file would have hung pollStage forever. Added
`done` to the guard and a regression test.
2. P2 — `coerceArtifactInput` validated severity only as a string,
not as the `"error" | "warning" | "info"` enum. Arbitrary values
like `"critical"` silently passed through, violating the type
contract. Added a generic `requireEnum` helper, applied it to
severity, and added a test that rejects an out-of-enum value.
3. P2 — `runMetadata` (engine-only side-table for projectId/issueId)
was populated in startRun but never pruned. Long-running orchestrator
processes would accumulate one entry per run forever. Added
`pruneTerminatedRunMetadata` that runs after every dispatch and
drops entries whose run has reached a terminal loop state, plus a
regression test that drives a second run on the same loop key
after the first terminated.
Refs: #1628 (PR #1638)
* fix(pipeline): address self-review on v0.2 agent executor
Folds the issues I called out in my own PR review into the engine
+ executor + stage-prompt:
Medium
1. dispatch is now serialized via a promise-chain lock. Top-level
callers (dispatch / tick / cancelRun) queue behind each other so
concurrent invocations cannot interleave reads/writes of the
in-memory state. Engine-internal recursive dispatches from
executeEffect (the saga) route through dispatchInline, which
bypasses the lock because it's already running inside it.
2. Layer 4 prompt now mandates the tmp-then-rename atomic write
pattern for .ao/pipeline-findings.jsonl. Without it, the executor
could harvest a torn JSONL file mid-write and classify the stage
as failed. Test asserts the prompt mentions both the .tmp file
and the rename.
Low / cosmetic
3. coerceArtifactInput now range-validates `confidence` to [0, 1] via
a new requireNumberInRange helper (FindingArtifactInput documents
the bound). Test exercises confidence=7.
4. Added a TODO on parseFindingsFile flagging that readFileSync is
unbounded — fine for v0.2 (engine + agent co-located) but needs
stream/cap once the engine moves out-of-process.
5. Moved runMetadata declaration above its use sites so the engine
reads top-down without forward references.
6. AgentExecutorSpawnError now uses the standard ErrorOptions{cause}
ctor instead of shadowing Error.cause with its own readonly field.
7. Dropped rebuildStateFromStore — leftover scaffolding for v0.3 that
shouldn't ship until v0.3 wires it in (CLAUDE.md: no half-finished
implementations).
8. Softened the blocks-merge prompt line: "findings will block merge
until they are resolved" (advisory) instead of "fail on critical
findings" (which implied non-existent enforcement).
Test gaps closed
- Multi-stage engine end-to-end (sequential under maxConcurrentStages=1).
- Concurrent dispatch test: cancelRun fired while tick is awaiting
pollStage observes the post-tick state, proving the lock serialized.
- New pipeline-stage-prompt.test.ts asserts the atomic-write contract,
blocks-merge wording, mode-aware shape instructions, and inputs block.
Tests: 71 pipeline / 1130 core total. Lint clean.
Refs: #1628 (PR #1638)
* feat(pipeline): v0.1 — core types, state machine, flat-file store
Implements the v0 foundation of the pipeline engine (issue #1627). Pure
data shapes, a synchronous reducer that returns intent-only effects, and
a flat-file store. No I/O, no executors, no driver — those land in
follow-up sub-tasks.
Modules in packages/core/src/pipeline/:
- types.ts: branded IDs (PipelineId, RunId, StageRunId, ArtifactId),
pipeline/stage/artifact configs, three-tier exit
(StageStatus / RunTerminationReason / LoopStateName),
EngineState + RunState two-level model.
- events.ts: PipelineEvent and PipelineEffect shapes.
- reducer.ts: pure reduce(state, event) → {state, effects} dispatch.
- reducer-helpers.ts: terminate/persist/materialize helpers.
- store.ts: flat-file persistence (runs/, stages/, artifacts/, loops/)
via atomicWriteFileSync; JSONL artifacts append-only.
- paths.ts: layout helpers; root is parameterized (callers pass
getProjectPipelinesDir(projectId) added to core/paths.ts).
Tests:
- pipeline-reducer.test.ts: 19 cases covering happy path, invalid
transitions, NEW_SHA outdating, RUN_CANCELLED variants, CONFIG_CHANGED,
loopRounds increments, and reducer purity (no clock reads, no mutation).
- pipeline-store.test.ts: 11 cases covering save/load roundtrips,
JSONL append semantics, and missing-file handling.
Locked design decisions from cluster planning:
- maxLoopRounds is per-stage (not pipeline-global).
- maxConcurrentStages defaults to 1 in v0.
- supportedTaskModes is a manifest field on agent plugins (no
executeTask interface method).
- Findings are surfaced via convention: stages drop pipeline-findings.jsonl
in {workspacePath}/.ao/ — exposed as PIPELINE_FINDINGS_FILENAME.
* fix(pipeline): address review feedback on store + paths
- store.ts: use path.join() in listRuns for cross-platform safety
- store.ts: docstring now distinguishes atomic JSON writes from
appendFileSync-backed JSONL artifact appends, and notes that
listArtifacts is not crash-safe against torn lines
- paths.ts: drop "V2 layout" tag from getProjectPipelinesDir JSDoc
* refactor(cli): collapse running/not-running fork via ensureDaemon (PR B.2)
Replaces the three branches that handled "AO is already running" cases in
start.ts (§3.2 URL/path-while-running, §3.3 project-id-while-running,
§3.5 non-human info dump) with a single attach pipeline that runs after
resolveOrCreateProject. The fork between attach and spawn is now a single
post-resolve decision point.
New module packages/cli/src/lib/daemon.ts owns the daemon side of that
fork:
- attachToDaemon(running) -> AttachedDaemon { port, pid,
notifyProjectChange() } — pure handle plus a typed
{ok}|{ok:false,reason} cache-invalidation result, replacing the
open-coded fetch + try/catch that lived in two places.
- killExistingDaemon(running) — SIGTERM -> waitForExit -> SIGKILL ->
unregister, used by the "Restart everything" menu option. Replaces
the inline restart code in §3.4.
resolve-project.ts gains an opt:
- { targetGlobalRegistry?: boolean } — when true, fromUrl and fromPath
register against the global config (the daemon's source of truth)
rather than into a cwd-local one. fromUrl's "register globally"
branch is a near-verbatim move of the §3.2 inline clone+register
block, including the global-registry dedup and the flat-local-config
write that §3.2 deliberately preferred over fromUrl's wrapped yaml.
fromCwdOrId short-circuits straight to the global registry for
project-id args while running.
The new dispatch in start.ts:
- Running + non-human + (no arg | URL | path) -> info dump, exit 0
(preserved §3.5 behavior; project-id args still fall through to
attach+spawn so automation can `ao start <id>` against a live
daemon).
- Running + human + no arg -> menu (preserved §3.4: open / quit /
add / new / restart). "restart" now routes through
killExistingDaemon and falls through to the spawn path; "new" sets
startNewOrchestrator and falls through to the attach path.
- resolveOrCreateProject(arg, deps, { targetGlobalRegistry: !!running })
- Running -> attachAndSpawnOrchestrator helper (§3.2 short-circuit
preserved: URL/path arg whose project is already in
running.projects skips the orchestrator-spawn and just opens the
dashboard).
- Not running -> existing runStartup + register + handlers.
attachAndSpawnOrchestrator unifies the §3.2/§3.3 messaging behind a
single justCreated discriminator:
- justCreated=true (URL clone or path register): "Spawning
orchestrator session..." -> "Project '...' registered in the global
config." -> "Orchestrator session ready: ..."
- justCreated=false (project id or already-registered path):
"Attaching to running AO instance..." -> "Orchestrator session
ready: ..." -> "Project '...' reattached to running daemon (PID
...)"
Both flows then notifyProjectChange (warns on failure, never throws —
the dashboard might be down), print the lifecycle-attach notice when
the project isn't yet supervised, and either openUrl (human) or print
the URL (non-human).
Subsumes the B.1 follow-up (migrate §3.2 inline clone+register to share
fromUrl): the inline block is deleted outright by the fork collapse and
fromUrl now owns both the not-running and the global-registry cases.
start.ts: -1126 / +131 lines. New daemon.ts: 105 lines. resolve-project.ts:
+167 lines (the global-registry branch + a moved-from-start.ts
detectClonedRepoDefaultBranch helper).
No behavior change. Test count and failure set are identical to
upstream/main; the 8 stop-command failures pre-exist on fad75b63.
8 new daemon.test.ts tests cover attachToDaemon (port/pid wiring,
notifyProjectChange success / non-2xx / fetch-throws) and
killExistingDaemon (SIGTERM happy path, SIGKILL escalation, throw on
both-fail, ESRCH-on-already-dead).
Step 2 of PR B in ao-118's start.ts refactor plan
(~/.ao/agent-orchestrator/ao-118/plan.md). startNewOrchestrator and the
§3.4 menu options remain intact — those land in PR B.3.
* fix(cli): canonicalize paths and guard reload in fromPath global branch
Two review fixes on resolve-project.ts:
1. Restore realpathSync canonicalization in fromPath's global-registry
branch. The original §3.2 inline block in start.ts canonicalized both
sides before comparing, so an `ao start /tmp/foo` against a daemon
whose global config stored /private/tmp/foo (macOS symlink) would
dedupe correctly. The B.2 collapse used plain resolve() and would
miss the match, calling addProjectToConfig and double-registering
the project. New canonicalize() helper mirrors the elsewhere-used
try-realpathSync-fallback pattern.
2. Add the missing null guard on reloaded.projects[addedId] in the same
branch, matching fromUrlIntoGlobal's existing guard. addProjectToConfig
could persist nothing on a write-permission error that doesn't throw,
in which case the undefined project would propagate into
generateOrchestratorPrompt with a useless stack trace; an explicit
"Failed to register" error is what the URL branch already raises.
* fix(cli): scope daemon test spy and correct add-menu comment
Two review fixes:
1. Move the process.kill spy in daemon.test.ts inside beforeEach +
afterEach (vi.restoreAllMocks). The previous module-scope spy could
leak into sibling test files when Vitest reuses worker threads,
silently mocking process.kill in unrelated suites and producing
confusing failures.
2. Rewrite the misleading comment on the "add" menu branch in start.ts.
The previous wording claimed the path "intentionally does not register
globally", but loadConfig() walks up from cwd and returns the global
config as a canonical fallback — so addProjectToConfig may register
globally in that common case. The new comment honestly describes the
canonical-aware behavior and the intentional skip of orchestrator
spawn (the "add" choice is distinct from "new").
* feat(core): add PreflightContext + optional preflight() to plugin interfaces
Foundation for PR 2 of the ao spawn refactor: lets plugins own their own
prerequisites instead of the CLI hardcoding 'if runtime === tmux check
tmux' / 'if tracker === github check gh auth' switches.
PreflightContext describes intent (willClaimExistingPR, role) rather
than CLI flag names, so plugins never learn about flags. New flags map
to new intent fields only when a plugin actually needs them.
Adds preflight?(ctx) as an optional method on Runtime, Agent, Workspace,
Tracker, SCM. Backwards-compatible: existing plugins keep working
unchanged. Subsequent commits move checkTmux into runtime-tmux and
checkGhAuth into the github plugins, then update spawn.ts to iterate
selected plugins instead of switching on plugin names.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(plugins): implement preflight() in runtime-tmux + tracker-github + scm-github
Each plugin now owns its own prerequisite checks (tmux binary, gh auth)
behind the optional PluginModule preflight() contract added in the
previous commit. The CLI no longer needs to know which plugin needs
which tool — it just iterates the selected plugins.
- runtime-tmux: checks 'tmux -V' and throws with platform-appropriate
install hint (brew / apt / dnf / WSL)
- tracker-github: checks 'gh --version' and 'gh auth status'
unconditionally (tracker is exercised on every spawn that has an
issueId AND on lifecycle polling for issue closure)
- scm-github: same gh auth checks but only when the spawn will exercise
PR-write paths — gates on context.intent.willClaimExistingPR
Subsequent commit refactors the CLI to iterate plugins instead of
hardcoded 'if runtime === tmux' switches.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(cli): make ao spawn iterate plugin preflight, collapse project resolution
Three small changes bundled because they all touch spawn.ts:
1. Plugin-iterating preflight: replaces the hardcoded
'if runtime === tmux check tmux' / 'if tracker === github check gh
auth' switches in runSpawnPreflight with a 4-line loop that walks the
selected plugins and calls each one's optional preflight(). Plugin
internals are no longer leaked into the CLI; new plugins only need to
declare their own preflight.
2. Project-resolution collapse: the prefix/no-prefix and issue/no-issue
paths previously had three near-duplicate code blocks each with its
own try/catch around autoDetectProject. Replaced by one
resolveProjectAndIssue() helper that uses resolveSpawnTarget's
fallback parameter — caller wraps in a single try/catch.
3. Micro-deletes: drop the unused 'return session.id' in spawnSession
(callers already ignore it; the SESSION=<id> stdout line is the
scriptable contract). Drop checkTmux/checkGhAuth from lib/preflight.ts
(now in their respective plugins) along with their orphaned tests.
LOC: roughly net-zero. Wins are structural — adding runtime-podman /
tracker-jira / scm-bitbucket no longer requires editing spawn.ts.
Pre-existing start.test.ts 'stop command' failures are unrelated (verified
on upstream/main bare).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* perf(plugins): dedupe gh-auth check across tracker-github + scm-github
Address greptile P2 on PR #1622: when a project has both tracker:
github and scm: github with --claim-pr, both plugin preflights ran
'gh --version' + 'gh auth status' independently — 4 execs where 2
suffice, and two identical error messages on failure.
Add memoizeAsync(key, fn) to core (process-scoped Promise cache) and
have both github plugins share the key 'gh-cli-auth'. Second caller
hits the in-flight (or resolved) promise — zero extra subprocess
overhead, one error on failure.
Caches both successes and rejections: failed checks should never
re-run within a process (cache dies with the CLI, user fixes the
underlying issue and re-invokes).
5 unit tests for memoizeAsync covering: single-fire dedup, value
identity, distinct keys, rejection caching, concurrent in-flight dedup.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(spawn): collect-all preflight + per-plugin tests + key-namespacing docs
Address self-review feedback on PR #1622:
1. **Collect-all preflight** (spawn.ts): runSpawnPreflight previously
aborted at the first plugin's failure, so a user with multiple broken
prereqs (tmux missing AND gh logged out) had to fix-and-retry to
discover the second one. Now collects every plugin's error and
reports them together ("2 preflight checks failed:\n 1. ...\n
2. ..."). Single-failure path is unchanged — that error throws as-is
without the wrapper. Test added: 'collects every plugin's preflight
failure into one combined error'.
2. **Drop redundant workspace literal fallback** (spawn.ts):
DefaultPluginsSchema in core/config.ts applies .default("worktree")
to workspace, same as runtime/agent. The literal '?? "worktree"'
was asymmetric defensive theater — dropped to match the runtime/agent
form.
3. **memoizeAsync key-namespacing convention** (process-cache.ts):
Added a JSDoc section documenting that two callers using the same
key get shared state (intentional for cross-cutting checks like
gh-cli-auth, dangerous for plugin-internal caching). Recommends
namespacing plugin-internal keys as 'plugin-name:thing'.
4. **Per-plugin preflight unit tests**:
- runtime-tmux: tmux-present resolves; tmux-missing throws with
platform-specific install hint (verified per-platform branch)
- tracker-github: happy path, gh-not-installed, gh-not-authenticated
- scm-github: no-op when willClaimExistingPR=false (zero gh calls),
full check when true, plus install/auth failure branches
Process cache cleared in beforeEach so each test starts fresh.
Required exporting _clearProcessCacheForTests from core/index.ts
(matches existing _testUtils pattern in gh-trace.ts).
Pre-existing start.test.ts 'stop command' failures unchanged
(verified on bare upstream/main).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(test): collapse duplicate @aoagents/ao-core import in tracker-github test
eslint no-duplicate-imports caught it on CI — combined the value and
type-only imports into one statement.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Replaces the per-arg-shape dispatch that lived inline in start.ts (URL,
path, project id, no arg) with a single resolveOrCreateProject(arg, deps)
call. The new module dispatches internally to fromUrl/fromPath/fromCwdOrId
helpers and returns a uniform { config, projectId, project, source,
justCreated, parsed? } shape.
Behavior preserved exactly — fromUrl is a near-verbatim move of
handleUrlStart's body (which is now deleted as it had no other callers),
fromPath mirrors the path branch's loadConfig/autoCreate/addProject
cascade, and fromCwdOrId carries over the registerFlatConfig recovery
path with the same semantics.
Dependencies that live in start.ts (addProjectToConfig, autoCreateConfig,
resolveProject, resolveProjectByRepo, registerFlatConfig, cloneRepo) are
passed in via a ResolveDeps object. This keeps the new module decoupled
from start.ts's other concerns (interactive prompts, agent detection,
project type detection) without creating a circular import.
Scope note: the "AO is already running + URL/path arg" branch in start.ts
still has its own inline clone+register block. That block deliberately
diverged from handleUrlStart (it writes a flat local config, not the
legacy wrapped one) — migrating it to share fromUrl is a small follow-up
before PR B.2 collapses the running-vs-not-running fork.
Step 1 of PR B in the start.ts refactor plan
(~/.ao/agent-orchestrator/ao-118/plan.md). Net diff: start.ts shrinks by
~146 lines, new file adds 294. Test count and failure set are identical
to upstream/main.
* 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>
* fix(web): source sidebar orchestrator from API field, not session list
PR #1615 merged the initial implementation but missed the follow-up
fix. The merged sidebar code looks up the orchestrator inside the
`sessions` prop, but /api/sessions/route.ts strips ALL orchestrators
from that array before returning (they're exposed via a separate
`orchestrators` field on the same response). Result: the new menu
entry — and the existing icon button next to the dashboard icon —
never render for any project.
Replace the broken in-sidebar derivation with a new `orchestrators`
prop on ProjectSidebar. Each parent passes the data it already has:
- Dashboard.tsx: passes `activeOrchestrators` (already in scope)
- PullRequestsPage.tsx: passes `orchestratorLinks` (already in scope)
- sessions/[id]/page.tsx: stores the `orchestrators` field already
returned by /api/sessions and threads it through SessionPageShell
and SessionDetail as `sidebarOrchestrators`
Tests refocused: the sidebar now just renders what the prop says, so
the live-vs-terminal selection lives in the API
(selectPreferredOrchestratorId) and is no longer the sidebar's
responsibility.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* style: fix indentation on sidebarOrchestrators prop in SessionPage
Addresses Greptile review comment on PR #1623.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(web): use DashboardOrchestratorLink for API response type
Addresses non-blocking review feedback on PR #1623. The /api/sessions
response actually returns DashboardOrchestratorLink shape (which
includes projectName), so use that as the response type instead of
the narrower ProjectSidebarOrchestrator. The sidebar prop type stays
narrow on purpose — it's the minimum the sidebar needs to render.
Also document the "one orchestrator per project" Map invariant.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(cli): extract runtime preflight and install helpers from start.ts
Pulls scattered preflight logic out of start.ts into two focused modules:
- lib/install-helpers.ts: shared install primitives (askYesNo,
runInteractiveCommand, tryInstallWithAttempts, genericInstallHints,
canPromptForInstall, InstallAttempt) — used by ensureGit/ensureTmux,
the agent runtime installer, and the optional gh install path.
- lib/startup-preflight.ts: the runtime checks themselves (ensureGit,
ensureTmux, warnAboutLegacyStorage, warnAboutOpenClawStatus) plus a
top-level runtimePreflight(config) that orchestrates tools + state
warnings + idle-sleep + OpenClaw credentials. Distinct from the
existing lib/preflight.ts, which validates dashboard build artifacts.
start.ts now calls runtimePreflight(config) once at the top of
runStartup instead of inlining 32 lines of orchestration; ensureGit is
imported for the three callsites that still need it directly (URL
clone, addProjectToConfig, URL-while-running branch).
No behavior change. Test count and failure set are identical to
upstream/main (8 pre-existing failures in the stop command tests).
Step 1 of PR A in the start.ts refactor plan
(~/.ao/agent-orchestrator/ao-118/plan.md). start.ts shrinks by 301
lines; net +55 LOC across the touched files (the abstractions cost
some interface overhead, as expected).
* refactor(cli): extract shutdown handler from start.ts
Moves the SIGINT/SIGTERM handler out of runStartup's closure into
lib/shutdown.ts as installShutdownHandlers({ configPath, projectId }).
The handler logic is identical: stop lifecycle workers, kill all
active sessions, record last-stop state for restore on next ao start,
unregister from running.json, await the bun-tmp janitor's final
sweep, then exit with the right code (130 for SIGINT, 0 for SIGTERM).
Also drops three now-unused start.ts imports (stopProjectSupervisor,
stopAllLifecycleWorkers, stopBunTmpJanitor) — they're consumed inside
the new shutdown module.
Note: the equivalent kill-and-record loop in `ao stop` is left
untouched. It has different verbosity (spinner, warnings, per-project
output) and different options (--purge-session) than the signal
handler. Unifying them is a behavior-shaping change that belongs with
the daemon/stop restructure in PR B, not this mechanical extraction.
Step 2 of PR A in the start.ts refactor plan
(~/.ao/agent-orchestrator/ao-118/plan.md). Test count unchanged (8
pre-existing stop-command failures from upstream/main, same set).
* refactor(cli): address PR review — idempotent shutdown + correct legacy count
Two P2 review comments from greptile-apps[bot]:
1. shutdown.ts: the 'idempotent' JSDoc claim was unbacked — shuttingDown
was a per-invocation closure, so calling installShutdownHandlers
twice would register duplicate listeners. Add a module-level
handlersInstalled guard and hoist shuttingDown to module scope so
the abstraction matches its docstring.
2. startup-preflight.ts: warnAboutLegacyStorage gates on the count of
non-empty hash dirs but printed hashDirs.length (total). Pre-existing
bug in the original start.ts code — a user with mostly-empty hash
dirs would see an inflated migration count. Renamed sessionCount →
nonEmptyDirCount (the variable always counted dirs, not sessions)
and used it in the message.
* refactor(core): replace spawn rollback ladder with CleanupStack
Replace the four nested try/catch + cleanupSpawnWorkspaceAndMetadata
helper in _spawnInner with a single LIFO CleanupStack. Each side
effect (reserved metadata, workspace, prompt files, runtime handle)
pushes its undo as soon as the resource exists; on success we
dismiss(), on failure we runAll().
Why: adding a new spawn step previously required extending every
prior cleanup block. Easy to forget; no compiler check. The stack
makes rollback structural — a new step pushes one cleanup, no risk
of leaving prior resources behind. runAll() is fault-tolerant by
design: a throwing cleanup never short-circuits the rest.
Behavior is preserved. Adds characterization tests for the worker
spawn rollback paths (none existed before — only spawnOrchestrator
was covered):
- workspace.create failure cleans reserved metadata
- runtime.create failure destroys worktree + cleans metadata
- postLaunchSetup failure destroys runtime + worktree + metadata
- one cleanup throwing does not skip subsequent cleanups
Refs #1603 (PR 1 of the ao spawn refactor plan).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(core): make CleanupStack runAll() terminal, symmetric with dismiss()
Address review feedback on PR #1616: previously `dismiss()` → `push()` was
a documented no-op but `runAll()` → `push()` would silently queue cleanups
that fired on a subsequent `runAll()`. Asymmetric and surprising.
Set `this.dismissed = true` at the top of `runAll()` so both terminal
states (success via dismiss, failure via runAll) reject further pushes
identically. Add a regression test pinning the new symmetric behavior.
The "idempotent runAll" test continues to pass (early-return path now
fires via the dismissed flag instead of the empty-stack short-circuit).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(core): surface CleanupStack errors and cover postCreate rollback
Address review feedback on PR #1616:
- Pass an onError callback to cleanupStack.runAll() in _spawnInner that
logs cleanup failures via console.error. The previous /* best effort */
pattern silently swallowed errors during rollback; now the same errors
are surfaced for debugging without changing behavior (cleanup errors
still don't propagate, subsequent cleanups still run).
- Add a characterization test for the workspace.postCreate failure path.
This was the only rollback path without a test — the stack handled it
correctly already, but pinning it down prevents regression.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>