Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(review): harden inline rewrite, delegation trust, and reconciliation

jkomynod5b425bd56c2
diff --git a/.github/workflows/build-cli-binaries.yml b/.github/workflows/build-cli-binaries.yml
index bee0a1dc6..b93b7e873 100644
--- a/.github/workflows/build-cli-binaries.yml
+++ b/.github/workflows/build-cli-binaries.yml
@@ -357,9 +357,9 @@ jobs:
export PATH="$COMPOSIO_BIN_DIR:$PATH"
```
- After a manual installation, run `composio install` to add the CLI to your
- shell's `PATH` permanently (or `composio install --shell zsh|bash|fish` to
- target a specific shell).
+ After a manual installation, run `composio install --shell zsh|bash|fish`
+ (with your shell in place of `zsh|bash|fish`) to add the CLI to your
+ shell's `PATH` permanently.
## Usage
diff --git a/.github/workflows/cli.install-health-check.yml b/.github/workflows/cli.install-health-check.yml
index 433a0145d..ea7d650dd 100644
--- a/.github/workflows/cli.install-health-check.yml
+++ b/.github/workflows/cli.install-health-check.yml
@@ -60,6 +60,18 @@ jobs:
# automatic shell setup (the default infers the shell from $SHELL; the idempotent rc
# edit on this ephemeral runner is harmless). Asset-aware and self-healing, so it is a
# coverage net rather than the primary signal.
+ #
+ # This leg is also the canary for the auto shell-setup default itself: shell-setup
+ # failure is non-fatal in install.sh (exit 0 + warning), so without asserting the
+ # actual contract below, a broken default would install a working binary and still
+ # report green. SHELL=/bin/bash pins deterministic auto-resolution on this runner, and
+ # the assertions mirror cli.test-installation.yml's checks — the managed PATH block in
+ # ~/.bashrc, plus that a login shell can actually resolve the binary.
+ #
+ # Deployment coupling: like the production legs in cli.install-e2e.yml, this installs
+ # from the PRODUCTION installer (composio.dev/install), so the shell-setup assertions
+ # only pass once the auto-default ships there. This workflow is schedule/workflow_dispatch
+ # only (no pull_request trigger), so it never runs against a pre-deploy PR or branch.
- name: Install via default no-arg flow
run: |
set -euo pipefail
@@ -76,11 +88,30 @@ jobs:
"$HOME/.composio/services" \
"$HOME/.composio/acp-adapters" \
"$HOME/.composio/local-tools-binaries"
- curl -fsSL https://composio.dev/install | sh
+ curl -fsSL https://composio.dev/install | SHELL=/bin/bash sh
test -x "$HOME/.composio/composio"
test -L "$HOME/.local/bin/composio"
"$HOME/.local/bin/composio" --version
+ # Assert the auto shell-setup contract: the managed PATH block landed in ~/.bashrc.
+ if grep -Fqx '# Composio CLI' "$HOME/.bashrc" \
+ && grep -Fqx 'export PATH="$HOME/.local/bin:$PATH"' "$HOME/.bashrc"; then
+ echo "✅ ~/.bashrc gained the managed Composio PATH block via automatic shell setup"
+ else
+ echo "❌ ~/.bashrc missing the managed Composio PATH block after the no-argument install"
+ echo "=== ~/.bashrc contents ==="
+ cat "$HOME/.bashrc" || true
+ exit 1
+ fi
+
+ # Assert a login shell actually resolves the binary through that PATH block.
+ if bash -ilc 'command -v composio' && bash -ilc 'composio --version'; then
+ echo "✅ composio resolves via a login bash shell"
+ else
+ echo "❌ composio did not resolve via a login bash shell"
+ exit 1
+ fi
+
- name: Send Slack Notification (Failure)
if: failure()
uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
diff --git a/install.sh b/install.sh
index d180675d7..4745206ef 100755
--- a/install.sh
+++ b/install.sh
@@ -369,16 +369,25 @@ write_path_block() {
if [ ! -f "$write_path_file" ]; then
touch "$write_path_file" 2>/dev/null || return 1
fi
- if path_block_current "$write_path_file" "$write_path_line"; then
+ # Dotfile managers keep startup files as symlinks; rewrite the physical
+ # target so the tmp+rename replace below cannot detach the symlink.
+ write_path_target=$(resolve_physical_path "$write_path_file")
+ if path_block_current "$write_path_target" "$write_path_line"; then
info "$(tildify "$write_path_file") is already up to date."
return 0
fi
- write_path_tmp=$write_path_file.composio.tmp
+ write_path_tmp=$write_path_target.composio.tmp.$$
+ # cp -p seeds the tmp with the original permission bits; the awk rewrite
+ # below truncates its content while the copied mode survives the rename.
+ if ! cp -p "$write_path_target" "$write_path_tmp" 2>/dev/null; then
+ rm -f "$write_path_tmp"
+ return 1
+ fi
if ! awk '
pending { pending = 0; next }
$0 == "# Composio CLI" { pending = 1; next }
{ print }
- ' "$write_path_file" >"$write_path_tmp" 2>/dev/null; then
+ ' "$write_path_target" >"$write_path_tmp" 2>/dev/null; then
rm -f "$write_path_tmp"
return 1
fi
@@ -386,7 +395,7 @@ write_path_block() {
rm -f "$write_path_tmp"
return 1
fi
- if ! mv "$write_path_tmp" "$write_path_file" 2>/dev/null; then
+ if ! mv "$write_path_tmp" "$write_path_target" 2>/dev/null; then
rm -f "$write_path_tmp"
return 1
fi
@@ -419,6 +428,33 @@ inline_shell_setup() {
return 0
}
+# Succeeds when one startup file already holds the current managed block.
+delegated_file_current() {
+ [ -f "$1" ] && path_block_current "$1" "$2"
+}
+
+# Stable CLI --shell implementations skip any startup file that already
+# carries the managed marker, so a delegated exit 0 can leave a stale block
+# naming an old bin dir. Confirm every target startup file of the requested
+# shell names the current bin dir before trusting the delegation.
+delegated_setup_verified() {
+ delegated_rendered=$(render_bin_dir "$resolved_bin_dir")
+ case $requested_shell in
+ zsh) delegated_file_current "$HOME/.zshrc" "$(path_block_line zsh "$delegated_rendered")" ;;
+ fish) delegated_file_current "$HOME/.config/fish/config.fish" "$(path_block_line fish "$delegated_rendered")" ;;
+ bash)
+ delegated_line=$(path_block_line bash "$delegated_rendered")
+ delegated_file_current "$HOME/.bashrc" "$delegated_line" || return 1
+ if [ -f "$HOME/.bash_profile" ]; then
+ delegated_file_current "$HOME/.bash_profile" "$delegated_line"
+ elif [ -f "$HOME/.bash_login" ]; then
+ delegated_file_current "$HOME/.bash_login" "$delegated_line"
+ fi
+ ;;
+ *) return 1 ;;
+ esac
+}
+
setup_requested_shell() {
if is_unsafe_path "$resolved_bin_dir"; then
warn "Skipping automatic shell setup: the executable directory \"$resolved_bin_dir\" contains unsupported characters."
@@ -426,7 +462,8 @@ setup_requested_shell() {
fi
if "$exe" install --help 2>&1 | grep -q -- '--shell'; then
debug "delegating shell setup to $exe install --shell $requested_shell"
- if COMPOSIO_CLI_INVOCATION_ORIGIN=installer COMPOSIO_BIN_DIR="$resolved_bin_dir" "$exe" install --shell "$requested_shell"; then
+ if COMPOSIO_CLI_INVOCATION_ORIGIN=installer COMPOSIO_BIN_DIR="$resolved_bin_dir" "$exe" install --shell "$requested_shell" &&
+ delegated_setup_verified; then
shell_configured=cli
info "Configured $requested_shell shell setup ($shell_configured)."
return 0
diff --git a/test/install-sh-release-resolution.test.sh b/test/install-sh-release-resolution.test.sh
index e4aa674f6..afc15d3c7 100755
--- a/test/install-sh-release-resolution.test.sh
+++ b/test/install-sh-release-resolution.test.sh
@@ -62,6 +62,11 @@ for script in "$repo_root/install.sh" "$repo_root"/install/*.sh; do
fi
done
+# Concurrent installer runs must not share one rc rewrite tmp file, so the
+# tmp suffix embeds the process id.
+grep -Fq '.composio.tmp.$$' "$repo_root/install.sh" ||
+ fail 'install.sh rc rewrites must use a per-process tmp suffix'
+
# The shell variants are served as standalone scripts, so their shared logic
# (including the URL-validation security checks) is intentionally copied.
# Enforce that they stay byte-identical except for the shell each hardcodes in
@@ -295,6 +300,32 @@ install)
if [ "${TEST_INSTALL_HINT:-0}" = 1 ]; then
printf '%s\n' '│ Restart your shell so composio is on PATH │'
fi
+ # Mirror the reconciling CLI: write the managed block to the same startup
+ # files the installer verifies. TEST_INSTALL_RECONCILE=0 models stable
+ # CLIs that exit 0 without reconciling (they skip marker-bearing files).
+ if [ "${TEST_INSTALL_EXIT:-0}" = 0 ] && [ "${TEST_INSTALL_RECONCILE:-1}" = 1 ]; then
+ write_block() {
+ if [ -f "$1" ] && grep -Fq "$2" "$1"; then
+ return 0
+ fi
+ printf '\n# Composio CLI\n%s\n' "$2" >>"$1"
+ }
+ case ${3:-} in
+ zsh) write_block "$HOME/.zshrc" "export PATH=\"$COMPOSIO_BIN_DIR:\$PATH\"" ;;
+ fish)
+ mkdir -p "$HOME/.config/fish"
+ write_block "$HOME/.config/fish/config.fish" "set --export PATH \"$COMPOSIO_BIN_DIR\" \$PATH"
+ ;;
+ bash)
+ write_block "$HOME/.bashrc" "export PATH=\"$COMPOSIO_BIN_DIR:\$PATH\""
+ if [ -f "$HOME/.bash_profile" ]; then
+ write_block "$HOME/.bash_profile" "export PATH=\"$COMPOSIO_BIN_DIR:\$PATH\""
+ elif [ -f "$HOME/.bash_login" ]; then
+ write_block "$HOME/.bash_login" "export PATH=\"$COMPOSIO_BIN_DIR:\$PATH\""
+ fi
+ ;;
+ esac
+ fi
exit "${TEST_INSTALL_EXIT:-0}"
fi
exit 98
@@ -323,7 +354,7 @@ EOF
unset CASE_GITHUB_URL CASE_API_BASE CASE_INSTALL_VERSION CASE_INSTALL_SHELL CASE_PLUGINS CASE_QUIET CASE_DEBUG CASE_HELP
unset CASE_ALLOW_HTTP_HOST CASE_CHECKSUM_MODE CASE_API_ASSET_URL CASE_BASE_MODE CASE_REDIRECT_DOWNGRADE
unset CASE_SHELL_CAPABILITY CASE_INSTALL_EXIT CASE_SETUP_EXIT CASE_VERSION_EXIT CASE_PATH_PREFIX CASE_UNSET_SHELL
- unset CASE_CURL_DELAY_URL CASE_CURL_DELAY_SECONDS CASE_SHELL_VALUE CASE_INSTALL_HINT
+ unset CASE_CURL_DELAY_URL CASE_CURL_DELAY_SECONDS CASE_SHELL_VALUE CASE_INSTALL_HINT CASE_INSTALL_RECONCILE
rm -f "$case_root/curl-parent.pid"
: >"$curl_log"
: >"$composio_log"
@@ -362,6 +393,7 @@ EOF
TEST_SHELL_CAPABILITY="${CASE_SHELL_CAPABILITY:-supported}" \
TEST_INSTALL_EXIT="${CASE_INSTALL_EXIT:-0}" \
TEST_INSTALL_HINT="${CASE_INSTALL_HINT:-0}" \
+ TEST_INSTALL_RECONCILE="${CASE_INSTALL_RECONCILE:-1}" \
TEST_SETUP_EXIT="${CASE_SETUP_EXIT:-0}" \
TEST_VERSION_EXIT="${CASE_VERSION_EXIT:-0}" \
TEST_CURL_DELAY_URL="${CASE_CURL_DELAY_URL:-}" \
@@ -393,6 +425,7 @@ EOF
TEST_CHECKSUM_MODE=missing \
TEST_SHELL_CAPABILITY="${CASE_SHELL_CAPABILITY:-supported}" \
TEST_INSTALL_EXIT="${CASE_INSTALL_EXIT:-0}" \
+ TEST_INSTALL_RECONCILE="${CASE_INSTALL_RECONCILE:-1}" \
TEST_CURL_DELAY_URL="${CASE_CURL_DELAY_URL:-}" \
TEST_CURL_DELAY_SECONDS="${CASE_CURL_DELAY_SECONDS:-1}" \
TEST_CURL_PARENT_PID_FILE="$case_root/curl-parent.pid" \
@@ -416,7 +449,8 @@ EOF
# for delegated CLI calls, but the ending must reflect only the PATH the
# invoking terminal inherited, which does not contain the bin dir here.
assert_tail "$output" "$case_b_tail" "$interpreter_name default auto Case B tail"
- [[ ! -e "$home/.bashrc" ]] || fail "$interpreter_name delegated default flow must not write rc files"
+ grep -Fq "export PATH=\"$bin_dir:\$PATH\"" "$home/.bashrc" || fail "$interpreter_name delegated default flow rc written by the CLI"
+ assert_not_contains "$output" 'Updated ~/.bashrc' "$interpreter_name delegated default flow must not rewrite rc files inline"
[[ $(wc -l <"$composio_log") -eq 3 ]] || fail "$interpreter_name default flow invoked extra CLI commands"
grep -Fq '|--version' "$composio_log" || fail "$interpreter_name version probe"
[[ ! -s "$case_root/git.log" ]] || fail "$interpreter_name must not use git"
@@ -607,7 +641,8 @@ EOF
assert_contains "$direct_output" 'Configured zsh shell setup (cli).' "$interpreter_name COMPOSIO_INSTALL_SHELL confirmation"
assert_not_contains "$direct_output" 'Required next step' "$interpreter_name COMPOSIO_INSTALL_SHELL must not print setup guidance"
assert_tail "$direct_output" "$case_b_tail" "$interpreter_name COMPOSIO_INSTALL_SHELL Case B tail"
- [[ ! -e "$direct_home/.zshrc" ]] || fail "$interpreter_name COMPOSIO_INSTALL_SHELL CLI path must not write rc files"
+ grep -Fq "export PATH=\"$direct_bin:\$PATH\"" "$direct_home/.zshrc" || fail "$interpreter_name COMPOSIO_INSTALL_SHELL CLI-written block"
+ assert_not_contains "$direct_output" 'Updated ~/.zshrc' "$interpreter_name COMPOSIO_INSTALL_SHELL CLI path must not rewrite rc files inline"
reset_case
CASE_INSTALL_SHELL=zsh
@@ -780,12 +815,14 @@ EOF
assert_contains "$shadow_output" "$shadow_dir/composio" "$interpreter_name shadow ending names the shadowing command"
assert_tail "$shadow_output" $'To use the newly installed CLI, run:\n\n '"$shadow_install/composio login" "$interpreter_name shadow tail avoids the shadowed bare command"
- # Pinned old CLI: supports --shell but ignores the invocation-origin hint and
- # prints its own boxed restart hint. A relative COMPOSIO_BIN_DIR must never
- # reach setup raw; startup files stay untouched; the installer's plain final
+ # Pinned old CLI: supports --shell but ignores the invocation-origin hint,
+ # prints its own boxed restart hint, and exits 0 without reconciling. A
+ # relative COMPOSIO_BIN_DIR must never reach setup raw; the installer must
+ # detect the unreconciled startup file and repair it inline; its plain final
# block prints after the old hint and supersedes it.
reset_case
CASE_INSTALL_HINT=1
+ CASE_INSTALL_RECONCILE=0
oldcli_home="$case_root/oldcli-home"
oldcli_work="$case_root/oldcli-work"
oldcli_install="$case_root/oldcli-install"
@@ -793,8 +830,9 @@ EOF
oldcli_output=$(cd "$oldcli_work" && run_installer "$oldcli_home" "$oldcli_install" "rel-bin" "$stable_tag" 2>&1)
grep -Fq "|installer|$oldcli_work/rel-bin|install --shell bash" "$composio_log" ||
fail "$interpreter_name old-CLI setup must receive the resolved absolute bin dir"
- [[ ! -e "$oldcli_home/.bashrc" && ! -e "$oldcli_home/.bash_profile" ]] ||
- fail "$interpreter_name old-CLI delegation must leave startup files unchanged"
+ grep -Fq "export PATH=\"$oldcli_work/rel-bin:\$PATH\"" "$oldcli_home/.bashrc" ||
+ fail "$interpreter_name old-CLI delegation must be reconciled inline with the absolute bin dir"
+ assert_contains "$oldcli_output" 'Configured bash shell setup (fallback).' "$interpreter_name old-CLI reconciliation disclosure"
assert_contains "$oldcli_output" '│ Restart your shell so composio is on PATH │' "$interpreter_name old-CLI restart hint passes through"
assert_tail "$oldcli_output" "$case_b_tail" "$interpreter_name old-CLI hint superseded by the installer tail"
@@ -853,6 +891,67 @@ EOF
grep -Fq 'alias reconcile-before=1' "$reconcile_home/.zshrc" || fail "$interpreter_name unmanaged content preserved (before block)"
grep -Fq 'alias reconcile-after=1' "$reconcile_home/.zshrc" || fail "$interpreter_name unmanaged content preserved (after block)"
+ # --- Symlinked startup files and mode preservation (managed dotfiles) ---
+
+ # Inline setup must write through a symlinked rc file: the symlink survives
+ # and its target receives the managed block (mirrors the CLI unit test
+ # 'preserves a symlinked .zshrc').
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/zsh
+ symlink_home="$case_root/symlink-home"
+ symlink_store="$case_root/symlink-store"
+ symlink_bin="$case_root/symlink-bin"
+ mkdir -p "$symlink_home" "$symlink_store"
+ printf '%s\n' 'alias dotfiles-managed=1' >"$symlink_store/zshrc"
+ ln -s "$symlink_store/zshrc" "$symlink_home/.zshrc"
+ symlink_output=$(run_installer "$symlink_home" "$case_root/symlink-install" "$symlink_bin" "$stable_tag" 2>&1)
+ assert_contains "$symlink_output" 'Updated ~/.zshrc' "$interpreter_name symlinked rc update disclosure"
+ [[ -L "$symlink_home/.zshrc" ]] || fail "$interpreter_name symlinked rc must stay a symlink"
+ [[ $(readlink "$symlink_home/.zshrc") == "$symlink_store/zshrc" ]] || fail "$interpreter_name symlinked rc target must not change"
+ [[ $(grep -Fc '# Composio CLI' "$symlink_store/zshrc") -eq 1 ]] || fail "$interpreter_name symlink target must hold one managed block"
+ grep -Fq "export PATH=\"$symlink_bin:\$PATH\"" "$symlink_store/zshrc" || fail "$interpreter_name symlink target managed line"
+ grep -Fq 'alias dotfiles-managed=1' "$symlink_store/zshrc" || fail "$interpreter_name symlink target unmanaged content preserved"
+
+ # The inline rewrite must preserve the startup file's permission bits.
+ reset_case
+ CASE_SHELL_CAPABILITY=unsupported
+ CASE_SHELL_VALUE=/bin/zsh
+ mode_home="$case_root/mode-home"
+ mkdir -p "$mode_home"
+ printf '%s\n' 'alias mode-check=1' >"$mode_home/.zshrc"
+ chmod 600 "$mode_home/.zshrc"
+ run_installer "$mode_home" "$case_root/mode-install" "$case_root/mode-bin" "$stable_tag" >/dev/null 2>&1
+ grep -Fq '# Composio CLI' "$mode_home/.zshrc" || fail "$interpreter_name mode-preservation run must write the block"
+ case $(uname) in
+ Darwin) mode_actual=$(stat -f '%Lp' "$mode_home/.zshrc") ;;
+ *) mode_actual=$(stat -c '%a' "$mode_home/.zshrc") ;;
+ esac
+ [[ $mode_actual == 600 ]] || fail "$interpreter_name inline rewrite must preserve the file mode (got $mode_actual)"
+
+ # --- Delegated setup verification (stale managed blocks) ---
+
+ # A delegated CLI that exits 0 without reconciling a pre-seeded stale block
+ # must not be trusted: the installer verifies the startup file, reconciles
+ # inline, and reports the fallback disclosure with the Case B ending.
+ reset_case
+ CASE_INSTALL_SHELL=zsh
+ CASE_INSTALL_RECONCILE=0
+ stale_home="$case_root/stale-delegated-home"
+ stale_bin="$case_root/stale-delegated-bin"
+ mkdir -p "$stale_home"
+ printf '%s\n' 'alias stale-guard=1' '' '# Composio CLI' 'export PATH="/stale/old-bin:$PATH"' >"$stale_home/.zshrc"
+ stale_output=$(run_installer "$stale_home" "$case_root/stale-delegated-install" "$stale_bin" "$stable_tag" 2>&1)
+ grep -Fq "|installer|$stale_bin|install --shell zsh" "$composio_log" || fail "$interpreter_name stale delegation still delegates first"
+ assert_contains "$stale_output" 'Configured zsh shell setup (fallback).' "$interpreter_name stale delegation reconciles inline"
+ [[ $(grep -Fc '# Composio CLI' "$stale_home/.zshrc") -eq 1 ]] || fail "$interpreter_name stale reconcile keeps one marker block"
+ grep -Fq "export PATH=\"$stale_bin:\$PATH\"" "$stale_home/.zshrc" || fail "$interpreter_name stale reconcile names the current bin dir"
+ if grep -Fq '/stale/old-bin' "$stale_home/.zshrc"; then
+ fail "$interpreter_name stale managed path must be replaced after delegation"
+ fi
+ grep -Fq 'alias stale-guard=1' "$stale_home/.zshrc" || fail "$interpreter_name stale reconcile preserves unmanaged content"
+ assert_tail "$stale_output" "$case_b_tail" "$interpreter_name stale delegation Case B tail"
+
# --- Unsafe resolved bin dirs under the default flow (KD3) ---
unsafe_auto_index=0
diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.md
index a489d2f4f..3c67657a0 100644
--- a/ts/packages/cli/CHANGELOG.md
+++ b/ts/packages/cli/CHANGELOG.md
@@ -4,6 +4,7 @@
### Minor Changes
+- The installer (`curl -fsSL https://composio.dev/install | sh`) now configures your shell automatically: `COMPOSIO_INSTALL_SHELL` defaults to `auto`, which infers the login shell from `$SHELL` (zsh, bash, or fish) and always runs idempotent PATH setup for it; `COMPOSIO_INSTALL_SHELL=none` keeps the old install-only behavior for CI, Docker, and dotfile managers. Startup-file setup failures no longer fail the install — the installer keeps the binary, warns, and prints a runnable absolute-path command. `composio install` now reconciles an existing managed PATH block whose bin directory changed (one block per physical file, symlink-aware) and suppresses its boxed restart hint when invoked by the installer, which owns the final message.
- `composio install` gains a `--shell <zsh|bash|fish>` flag that overrides `$SHELL` detection, in preparation for the mise-style installer rewrite. The bin-dir PATH target now resolves through `COMPOSIO_BIN_DIR`, an existing `~/.local/bin/composio`, or the real binary's own directory, in that order, instead of hardcoding `~/.composio`; rc blocks write only a PATH line (the `export COMPOSIO_INSTALL_DIR=...` line is gone, since that variable identifies the install bundle, not the PATH entry point). Bash now also writes the PATH line to `~/.bash_profile` or `~/.bash_login` when either already exists, so `bash -ilc` picks it up. The restart hint bug is fixed: bash now prints `source ~/.bashrc` instead of the literal string `exec $SHELL`.
### Patch Changes
diff --git a/ts/packages/cli/src/commands/install.cmd.ts b/ts/packages/cli/src/commands/install.cmd.ts
index fff170d29..079e90724 100644
--- a/ts/packages/cli/src/commands/install.cmd.ts
+++ b/ts/packages/cli/src/commands/install.cmd.ts
@@ -195,17 +195,35 @@ type ManagedPathBlockState =
| { readonly state: 'current' }
| { readonly state: 'stale'; readonly reconciled: string };
-const isAnyMarkerLine = (line: string): boolean => {
+/**
+ * A line this installer could have written as the managed PATH assignment:
+ * POSIX `export PATH="<dir>:$PATH"` or fish `set --export PATH "<dir>" $PATH`.
+ * Matched structurally on the prefix/suffix (any bin dir) so stale blocks
+ * recording another directory are still recognized as ours.
+ */
+const isManagedPathAssignment = (line: string): boolean => {
const trimmed = line.trim();
- return trimmed === MARKER || trimmed === COMPLETIONS_MARKER;
+ return (
+ (trimmed.startsWith('export PATH="') && trimmed.endsWith(':$PATH"')) ||
+ (trimmed.startsWith('set --export PATH "') && trimmed.endsWith('" $PATH'))
+ );
};
/**
* Reconcile the managed PATH block — the `MARKER` line plus the PATH
* assignment right below it — with the currently resolved bin directory.
- * A block recording a stale bin dir is replaced in place, duplicate managed
- * PATH blocks collapse into a single current block, and unmanaged content
- * (including the completions block) is left byte-for-byte untouched.
+ * A well-formed block recording a stale bin dir is replaced in place,
+ * duplicate managed PATH blocks collapse into a single current block, and
+ * unmanaged content (including the completions block) is left byte-for-byte
+ * untouched.
+ *
+ * A marker whose next line is not a recognizable managed assignment (a user
+ * annotation, a blank line, another marker) is malformed: only the marker
+ * line itself is removed, and the fresh block is appended after all remaining
+ * content instead of replacing in place. That guarantees no user content is
+ * ever deleted, and — because these prepend-style assignments make the
+ * last-sourced line win — the new bin dir still takes PATH precedence over
+ * any orphaned stale assignment left behind.
*/
const reconcileManagedPathBlock = (contents: string, pathBlock: string): ManagedPathBlockState => {
const lines = contents.split('\n');
@@ -213,7 +231,8 @@ const reconcileManagedPathBlock = (contents: string, pathBlock: string): Managed
const firstMarkerIndex = markerIndexes[0];
if (firstMarkerIndex === undefined) return { state: 'absent' };
- const expectedAssignment = (pathBlock.split('\n')[1] ?? '').trim();
+ const blockLines = pathBlock.split('\n');
+ const expectedAssignment = (blockLines[1] ?? '').trim();
if (
markerIndexes.length === 1 &&
(lines[firstMarkerIndex + 1] ?? '').trim() === expectedAssignment
@@ -221,21 +240,33 @@ const reconcileManagedPathBlock = (contents: string, pathBlock: string): Managed
return { state: 'current' };
}
- // Managed lines: each marker line and its assignment line, unless that next
- // line is itself a marker (never consume the completions block).
+ // Managed lines: each marker line, plus the next line only when it is a
+ // recognizable managed PATH assignment — anything else is not ours to delete.
const managedLineIndexes = new Set<number>(
markerIndexes.flatMap(markerIndex => {
const assignment = lines[markerIndex + 1];
- return assignment !== undefined && !isAnyMarkerLine(assignment)
+ return assignment !== undefined && isManagedPathAssignment(assignment)
? [markerIndex, markerIndex + 1]
: [markerIndex];
})
);
+ const hasMalformedBlock = markerIndexes.some(
+ markerIndex => !isManagedPathAssignment(lines[markerIndex + 1] ?? '')
+ );
- const reconciledLines = lines.flatMap((line, index) => {
- if (index === firstMarkerIndex) return pathBlock.split('\n');
- return managedLineIndexes.has(index) ? [] : [line];
- });
+ if (!hasMalformedBlock) {
+ const reconciledLines = lines.flatMap((line, index) => {
+ if (index === firstMarkerIndex) return blockLines;
+ return managedLineIndexes.has(index) ? [] : [line];
+ });
+ return { state: 'stale', reconciled: reconciledLines.join('\n') };
+ }
+
+ const keptLines = lines.flatMap((line, index) => (managedLineIndexes.has(index) ? [] : [line]));
+ const endsWithNewline = keptLines[keptLines.length - 1] === '';
+ const reconciledLines = endsWithNewline
+ ? [...keptLines.slice(0, -1), ...blockLines, '']
+ : [...keptLines, ...blockLines];
return { state: 'stale', reconciled: reconciledLines.join('\n') };
};
@@ -308,10 +339,16 @@ const atomicWriteWithMode = (
const tmpPath = `${writeTarget}.composio-tmp`;
yield* fs.writeFileString(tmpPath, contents);
- if (Option.isSome(existingTargetInfo)) {
- yield* fs.chmod(tmpPath, existingTargetInfo.value.mode & 0o7777);
- }
- yield* fs.rename(tmpPath, writeTarget);
+ // Mirror install.sh's write_path_block: when the chmod or rename step
+ // fails, remove the temp file before propagating the error so no
+ // `.composio-tmp` litter is left next to the target.
+ const promoteTmp = Effect.gen(function* () {
+ if (Option.isSome(existingTargetInfo)) {
+ yield* fs.chmod(tmpPath, existingTargetInfo.value.mode & 0o7777);
+ }
+ yield* fs.rename(tmpPath, writeTarget);
+ });
+ yield* promoteTmp.pipe(Effect.onError(() => fs.remove(tmpPath).pipe(Effect.ignore)));
});
/** Atomically rewrite each reconciled physical target, preserving its file mode. */
diff --git a/ts/packages/cli/test/src/commands/install.cmd.test.ts b/ts/packages/cli/test/src/commands/install.cmd.test.ts
index 09fb61911..f4ba6ea9b 100644
--- a/ts/packages/cli/test/src/commands/install.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/install.cmd.test.ts
@@ -593,6 +593,73 @@ describe('CLI: composio install', () => {
});
});
+ describe('[When] a user comment sits between the managed marker and the stale export', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the comment survives and the fresh assignment wins PATH precedence', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ '# Composio CLI\n# added by my dotfiles\nexport PATH="/stale/bin:$PATH"\n# user epilogue\n'
+ );
+
+ yield* install();
+
+ const contents = yield* fs.readFileString(rcPath);
+ // No user content may ever be deleted.
+ expect(contents).toContain('# added by my dotfiles');
+ expect(contents).toContain('# user epilogue');
+ // Exactly one marker, directly followed by the current assignment.
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ const newAssignment = `export PATH="${expectedBinDir}:$PATH"`;
+ const lines = contents.split('\n');
+ const markerIndex = lines.findIndex(line => line.trim() === '# Composio CLI');
+ expect(lines[markerIndex + 1]).toBe(newAssignment);
+ // Prepend-style exports make the last-sourced assignment win, so the
+ // fresh assignment must be removed-or-after any surviving stale one.
+ const staleIndex = contents.indexOf('export PATH="/stale/bin:$PATH"');
+ expect(contents.indexOf(newAssignment)).toBeGreaterThan(staleIndex);
+ })
+ );
+ });
+ });
+
+ describe('[When] a blank line sits between the managed marker and the stale export', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] nothing but the marker is removed and the fresh assignment wins', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+ const expectedBinDir = expectedRuntimeBinDir();
+
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.writeFileString(
+ rcPath,
+ '# user prologue\n# Composio CLI\n\nexport PATH="/stale/bin:$PATH"\n'
+ );
+
+ yield* install();
+
+ const contents = yield* fs.readFileString(rcPath);
+ expect(contents).toContain('# user prologue');
+ expect(contents.match(/^# Composio CLI$/gm)?.length ?? 0).toBe(1);
+ const newAssignment = `export PATH="${expectedBinDir}:$PATH"`;
+ const lines = contents.split('\n');
+ const markerIndex = lines.findIndex(line => line.trim() === '# Composio CLI');
+ expect(lines[markerIndex + 1]).toBe(newAssignment);
+ const staleIndex = contents.indexOf('export PATH="/stale/bin:$PATH"');
+ expect(contents.indexOf(newAssignment)).toBeGreaterThan(staleIndex);
+ })
+ );
+ });
+ });
+
describe('[When] .bashrc and .bash_profile alias one physical file with a stale managed block', () => {
layer(InstallTestLive())(it => {
it.scoped('[Then] the physical file ends with exactly one current block', () =>
@@ -630,6 +697,29 @@ describe('CLI: composio install', () => {
});
});
+ describe('[When] the atomic write cannot replace the target file', () => {
+ layer(InstallTestLive())(it => {
+ it.scoped('[Then] the error propagates and no .composio-tmp file is left behind', () =>
+ Effect.gen(function* () {
+ const os = yield* NodeOs;
+ const fs = yield* FileSystem.FileSystem;
+ vi.stubEnv('SHELL', '/bin/zsh');
+
+ // A directory at the rc path makes the final rename(file, dir) fail
+ // after the temp file was already written.
+ const rcPath = path.join(os.homedir, '.zshrc');
+ yield* fs.remove(rcPath, { force: true, recursive: true });
+ yield* fs.makeDirectory(rcPath);
+
+ const exit = yield* install().pipe(Effect.exit);
+
+ expect(Exit.isFailure(exit)).toBe(true);
+ expect(yield* fs.exists(`${rcPath}.composio-tmp`)).toBe(false);
+ })
+ );
+ });
+ });
+
describe('[When] COMPOSIO_CLI_INVOCATION_ORIGIN=installer delegates shell setup', () => {
layer(InstallTestLive())(it => {
it.scoped('[Then] keeps the Updated status line but suppresses the restart hint', () =>