Skip to content

fix(cli): worktree 稳定性/安全加固——采纳 #456 CodeRabbit 评审 - #459

Merged
leeguooooo merged 2 commits into
mainfrom
fix/worktree-hardening-cr456
Jul 13, 2026
Merged

leeguooooo merged 2 commits into
mainfrom
fix/worktree-hardening-cr456

Conversation

@leeguooooo

@leeguooooo leeguooooo commented Jul 13, 2026 •

Copy link
Copy Markdown
Owner

review-ack: 跟进 #456。合并 #456 后 CodeRabbit(ASSERTIVE) 落了实质评审,我逐条核实后采纳真问题。坦白:#456 我在 CodeRabbit 🔴 落地后没读就 admin-合了,重演『评审没人看就合』;本 PR 补做,且合前必等 pr_agent + CodeRabbit 都读完。

采纳的修复

严重度 问题 修复
🔴 defaultGit 无交互认证防护/超时:push 命中 HTTPS 密码或 SSH passphrase(/dev/tty,不受 stdin:ignore 约束)会永久挂起,无人值守 agent 整条 prune 无限阻塞 GIT_TERMINAL_PROMPT=0(遇提示即失败) + 120s 硬超时 kill 熔断
🟠 rev-parse --show-toplevel 失败静默降级成 '' → 当前 worktree 保护失效可被删 失败即抛(同 worktree-list 失败)。TDD+变异亲验
🟡 终端输出未剥控制字符:分支/路径/git stderr 直拼 console,agent 场景可注入 ANSI sanitizeForTerminal 统一清洗(保留 \t\n),套用全部外部字符串输出。TDD+变异亲验
🟡 我两条测试断言太松(not.toBe 放行 undefined;子串 'un' 被 'prune' 提前满足) 改精确 toBe('unmerged') 与 /skip\s+un\s+—\s+unmerged/

CodeRabbit 的 status-返回码一条(🟠)与 pr_agent 独立都逮到,已在 #456(status 守卫)修复。

门禁

cli worktree 10/10、tsc 0。两处安全修复(rev-parse throw、sanitize)均 TDD 先红后绿、变异去守卫复红亲验。

Summary by CodeRabbit

  • 安全性改进
    • 为 Git 操作新增硬超时,并关闭交互式认证,避免任务长时间卡住。
    • 清理分支名、路径及 Git 输出中的终端控制字符,确保日志与终端显示更安全、干净(包括执行与 dry-run 计划/跳过提示)。
  • Bug 修复
    • 当前工作树识别失败时直接中止,防止误删受保护的工作树。
    • 优化清理/跳过相关的错误与状态日志,更精确呈现分支与原因。
  • 测试
    • 增强工作树识别失败、未合并状态判定及跳过日志的断言覆盖。

合并 #456 后 CodeRabbit(ASSERTIVE) 落了实质评审,逐条核实后采纳:
- 🔴 defaultGit 无交互认证防护/超时:push 命中 HTTPS 密码或 SSH passphrase(/dev/tty,
  不受 stdin:ignore 约束)会永久挂起,无人值守 agent 场景整条 prune 无限阻塞。加
  GIT_TERMINAL_PROMPT=0(遇提示即失败) + 120s 硬超时熔断(kill+返回 code 124)。
- 🟠 rev-parse --show-toplevel 失败静默降级成 '':w.path==='' 永不命中,当前 worktree
  保护失效可被删。改失败即抛(同 worktree-list 失败)。[TDD]
- 🟡 终端输出未剥控制字符:分支/路径/git stderr 直拼 console,agent 场景可注入 ANSI/
  控制字符。加 sanitizeForTerminal 统一清洗(保留 \t\n),套用到所有外部字符串输出。[TDD]
- 🟡 我两条测试断言太松:not.toBe 误放行 undefined;子串 'un' 被 'prune' 提前满足。
  改精确断言 toBe('unmerged') 与 /skip\s+un\s+—\s+unmerged/。

注:CodeRabbit 的 status-返回码 一条(🟠)与 pr_agent 独立都逮到,已在 #456(09008da) 修复。
教训:#456 我在 CodeRabbit 🔴 落地后没读就 admin-合,重演『评审没人看就合』——本 PR 补做,
且合前必等 pr_agent+CodeRabbit 都读完。
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

工作树命令增加 Git 子进程硬超时和非交互认证设置,清理终端输出中的控制字符,并在当前工作树路径解析失败时抛错;测试覆盖分类失败、状态判断及修剪跳过日志。

Changes

工作树安全性增强

Layer / File(s) Summary
Git 执行与终端输出安全
cli/src/commands/worktree.ts, cli/test/worktree.test.ts
Git 子进程增加硬超时和非交互认证环境变量;新增并使用 sanitizeForTerminal 清理分支名、路径及 Git 输出。
当前工作树分类保护
cli/src/commands/worktree.ts, cli/test/worktree.test.ts
rev-parse --show-toplevel 失败时 classifyWorktrees 抛出错误;测试精确断言 status 失败结果为 unmerged,并验证分类操作 reject。
修剪日志测试校验
cli/src/commands/worktree.ts, cli/test/worktree.test.ts
修剪阶段的 skip 输出清理分支名,测试改为精确匹配完整的 unmerged 跳过日志。

Estimated code review effort: 3 (Moderate) | ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 标题与本次 worktree 稳定性/安全加固的主要改动一致,且能让人快速理解变更重点。
Description check ✅ Passed 描述基本覆盖了改动原因、采纳的问题、修复内容和门禁结果,满足模板的核心信息。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/worktree-hardening-cr456

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit c38850a)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

456 - Fully compliant

Compliant requirements:

  • 新增 party worktree list:展示各 worktree 的合并/清理状态、领先提交数及未提交变更数。
  • 新增 party worktree prune:默认预览清理计划(dry-run),仅在确认后执行安全清理;可选删除对应远程分支。
  • 对已合并但有改动的工作树会先保存并推送到 preserve/*,失败则保留并提示,避免数据丢失。
  • 更新 CLI 帮助信息,补充 worktree 命令用法与选项。
  • 新增 worktree 端到端集成测试,覆盖 list/prune 多场景。
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

可能的 Bug

在 spawnWithTimeout 函数中,如果 proc.pid 为 undefined,则返回错误信息。这可能会导致某些情况下无法正确处理子进程启动失败的情况。建议进一步检查 proc.pid 为 undefined 的情况,并确保所有错误路径都被正确处理。

const proc = Bun.spawn(cmd, { cwd, stdin: "ignore", stdout: "pipe", stderr: "pipe", env });
if (!proc.pid) {
  // spawn 失败——别再挂 timer,直接报错(pr_agent #459 建议)。
  return { code: 1, stdout: "", stderr: `failed to start: ${cmd.join(" ")}` };

@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to c38850a
Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
增加路径信息

在 git add 失败时,确保错误信息中包含完整的路径信息,以便更好地调试。

cli/src/commands/worktree.ts [317-321]

 const add = await git(["-C", path, "add", "-A"], root);
 if (add.code !== 0) {
-  console.error(`  ! ${branch}: git add failed, worktree preserved as-is — ${sanitizeForTerminal(add.stderr.trim())}`);
+  console.error(`  ! ${branch} (${path}): git add failed, worktree preserved as-is — ${sanitizeForTerminal(add.stderr.trim())}`);
   return false;
 }
Suggestion importance[1-10]: 5

__

Why: 该建议在 git add 失败时增加了路径信息,有助于更好地调试。这是一个有用的改进,但影响相对较小。

Low
立即清除定时器

在 Promise.race 之后立即清除定时器,以避免在超时后仍然执行不必要的定时器。

cli/src/commands/worktree.ts [76-80]

 const result = await Promise.race([work, timeout]);
-if (timer) clearTimeout(timer);
+if (timer) {
+  clearTimeout(timer);
+}
 return result;
Suggestion importance[1-10]: 3

__

Why: 该建议仅在 Promise.race 之后立即清除定时器,但现有代码已经实现了这一点。因此,这个建议没有实际改进。

Low

Previous suggestions

Suggestions up to commit 2efce02
CategorySuggestion                                                                                                                                    Impact
Possible issue
确保进程启动后再设置超时定时器。

在设置超时定时器之前,确保 proc 已经成功启动。如果 proc 启动失败,直接返回错误。

cli/src/commands/worktree.ts [62-65]

+if (!proc.pid) {
+  return { code: 1, stdout: "", stderr: "Failed to start git process" };
+}
 const timer = setTimeout(() => {
   timedOut = true;
   proc.kill();
 }, GIT_TIMEOUT_MS);
Suggestion importance[1-10]: 8

__

Why: 该建议确保了 proc 成功启动后再设置超时定时器,避免了在 proc 启动失败的情况下设置定时器的问题。这是一个重要的改进,可以防止潜在的错误。

Medium
General
记录超时信息以便调试。

在超时情况下,除了返回错误码和消息外,还应记录超时信息以便调试。

cli/src/commands/worktree.ts [72-73]

 if (timedOut) {
+  console.error(`git timed out after ${GIT_TIMEOUT_MS}ms: git ${args.join(" ")}`);
   return { code: code || 124, stdout, stderr: `git timed out after ${GIT_TIMEOUT_MS}ms: git ${args.join(" ")}` };
 }
Suggestion importance[1-10]: 7

__

Why: 该建议在超时情况下记录错误信息,有助于调试和问题排查。虽然这是一个有用的改进,但它的影响相对较小。

Medium

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cli/src/commands/worktree.ts`:
- Around line 277-290: Separate the raw branch value from its terminal-safe
display value in removeMergedClean and preserveAndRemove. Keep action.row.branch
unchanged for git arguments such as branch deletion, remote deletion, and commit
operations, and apply sanitizeForTerminal only when constructing console output.
- Around line 81-86: 更新 sanitizeForTerminal 的控制字符正则,使其移除回车符 \x0D,同时继续保留注释所声明的制表符
\x09 和换行符 \x0A,并保持现有 ANSI 转义序列清理行为不变。
- Around line 51-79: Update defaultGit so the GIT_TIMEOUT_MS handler returns
independently when the timeout fires instead of waiting for stdout/stderr reads
or proc.exited to settle. Ensure the timeout path terminates or ignores the
pending process/stream work and returns the timeout code and diagnostic stderr,
while preserving normal output and exit-code handling for Git commands that
finish in time.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6e5b693d-c68a-4361-bdb6-91fa1fddaa13

📥 Commits

Reviewing files that changed from the base of the PR and between 2a77144 and 2efce02.

📒 Files selected for processing (2)
  • cli/src/commands/worktree.ts
  • cli/test/worktree.test.ts

Comment thread cli/src/commands/worktree.ts Resolved
Comment thread cli/src/commands/worktree.ts Resolved
Comment thread cli/src/commands/worktree.ts Resolved
pr_agent + CodeRabbit 对 #459 又逐条核实后采纳:
- 🔴 硬超时是假的:proc.kill() 只杀顶层 git,派生的 ssh/credential-helper 仍占 stdout/stderr
  时 Promise.all 读管道会卡住、超时分支永不返回。抽出 spawnWithTimeout 用 Promise.race 让
  超时【独立】返回(code 124),不依赖管道读完。[TDD:sleep 5 + 200ms 超时,断言 <4s 返回]
- 🔵 spawn 失败(!proc.pid)先返回错误再挂 timer(pr_agent importance-8)。
- 🟡 sanitizeForTerminal 漏剥裸回车 \x0D(可做终端行覆盖伪造输出):字符类 \x0B-\x1F 合并覆盖。[TDD]
- 🔵 sanitized 分支名不再复用为 git 参数:raw 喂 git branch -D/push --delete/preserve refspec,
  仅打印时 sanitize——防未来扩展 sanitize(如 Unicode 归一化)悄悄改掉实际分支名误删/误推。

12/12、tsc 0。超时与 sanitize 均 TDD。
@leeguooooo

Copy link
Copy Markdown
Owner Author

由 #461 取代,避免两条重叠安全修复同时合并。逐项核对:#461 覆盖本 PR 的非交互 Git、硬超时、rev-parse current guard、终端控制字符清洗、精确断言;并额外补 unrelated worktree 永不清理、preserve/remove 失败返回非零、真实 CLI 路由。超时实现用 detached 进程组 + SIGKILL,既按时返回,也清掉 git/ssh/helper 子进程,不留下 race 后台残留。后续评审/合并统一在 #461。

@leeguooooo leeguooooo closed this Jul 13, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cli/src/commands/worktree.ts`:
- Around line 76-80: 增强 worktree 命令中 timeout Promise 的进程终止逻辑:在 proc.kill() 发送
SIGTERM 后设置短暂宽限期,并在进程仍未退出时升级为 proc.kill("SIGKILL"),同时保留现有超时结果立即 resolve
的行为,避免引入额外阻塞。
- Around line 93-96: Update sanitizeForTerminal to remove Unicode bidirectional
and directional-isolate controls, including U+202A–U+202E and U+2066–U+2069, in
addition to the existing ANSI and ASCII control characters. Keep the current
sanitization behavior unchanged for all other text.
- Around line 62-66: 在 spawnWithTimeout 中为 Bun.spawn 调用增加
try/catch,将启动时抛出的异常转换为统一的失败 GitResult(code 为 1,并包含命令及错误信息);保留现有 proc.pid
检查作为兜底,确保调用方不会收到未处理异常。

In `@cli/test/worktree.test.ts`:
- Around line 140-155: 增强 spawnWithTimeout 测试覆盖:将超时命令改为会派生子进程并让其继承 stdout/stderr
管道的场景,确保超时结果独立于管道关闭且不会等待子进程;在同一测试套件新增不存在命令的用例,验证 Bun.spawn 失败时 spawnWithTimeout
resolve 为 code 1 并返回错误信息,而不是 reject。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d17af548-075c-47e5-a70d-0eb533d46f06

📥 Commits

Reviewing files that changed from the base of the PR and between 2efce02 and c38850a.

📒 Files selected for processing (2)
  • cli/src/commands/worktree.ts
  • cli/test/worktree.test.ts

Comment on lines +62 to +66
const proc = Bun.spawn(cmd, { cwd, stdin: "ignore", stdout: "pipe", stderr: "pipe", env });
if (!proc.pid) {
// spawn 失败——别再挂 timer,直接报错(pr_agent #459 建议)。
return { code: 1, stdout: "", stderr: `failed to start: ${cmd.join(" ")}` };
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP -A5 -B2 '\bBun\.spawn\(' cli/src

Repository: leeguooooo/AgentParty

Length of output: 2902


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- worktree.ts ---'
sed -n '1,220p' cli/src/commands/worktree.ts

echo
echo '--- spawn call sites for spawnWithTimeout / defaultGit ---'
rg -n "spawnWithTimeout|defaultGit|await git\(" cli/src/commands/worktree.ts cli/src -g '!**/node_modules/**'

echo
echo '--- upgrade.ts snippet ---'
sed -n '108,132p' cli/src/upgrade.ts

echo
echo '--- oidc-cli.ts snippet ---'
sed -n '148,164p' cli/src/oidc-cli.ts

echo
echo '--- serve.ts snippets ---'
sed -n '520,545p' cli/src/commands/serve.ts
echo
sed -n '728,752p' cli/src/commands/serve.ts

Repository: leeguooooo/AgentParty

Length of output: 14870


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
p = Path("cli/src/commands/worktree.ts")
text = p.read_text()
for needle in ["function spawnWithTimeout", "function defaultGit", "export async function"]:
    idx = text.find(needle)
    if idx != -1:
        start = text.rfind("\n", 0, idx-200)
        end = text.find("\n\n", idx)
        print(f"\n### around {needle} ###")
        print(text[max(0, idx-200):min(len(text), idx+1200)])
PY

Repository: leeguooooo/AgentParty

Length of output: 3043


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- worktree.ts (full, numbered) ---'
cat -n cli/src/commands/worktree.ts | sed -n '1,260p'

echo
echo '--- references to worktree command ---'
rg -n "worktree" cli/src -g '!**/node_modules/**'

echo
echo '--- top-level CLI error handling candidates ---'
rg -n "catch \\(|process\\.on\\('unhandledRejection'|unhandledRejection|main\\(" cli/src -g '!**/node_modules/**'

Repository: leeguooooo/AgentParty

Length of output: 23834


🌐 Web query:

Bun.spawn ENOENT synchronous throw pid null docs

💡 Result:

In Bun, the observation that Bun.spawnSync might throw an error or return a result with pid: null (or undefined) when encountering an ENOENT error (file not found) is related to how the runtime handles subprocess spawn failures compared to Node.js [1][2]. Historically, Bun's implementation of spawnSync and spawn differed from Node.js, sometimes throwing exceptions instead of returning a result object with an error property, or returning inconsistent object shapes (e.g., status: undefined, pid: undefined, or output: [null, null, null]) [1][2][3]. As of mid-2026, active development has been ongoing to align Bun.spawnSync and the node:child_process compatibility layer with Node.js's contract [2][4]. Specifically: 1. Consistency with Node.js: Recent updates (e.g., Pull Request #32878) have focused on ensuring that when an underlying spawn fails (such as ENOENT or EACCES), spawnSync returns an object shaped exactly like Node.js: {error, status: null, signal: null, output: null, pid: 0, stdout: undefined, stderr: undefined} [2]. 2. Error Handling: In earlier versions, users might encounter TypeError or other thrown exceptions when a binary was missing [3]. The current approach is to catch these failures internally and return a structured result object, preventing the process from crashing unexpectedly [2]. 3. Related Issues: If you are seeing ENOENT in the context of cwd (current working directory), note that there have been specific issues where Bun incorrectly reported ENOENT for the executable binary when the error was actually caused by a missing cwd path [5][6]. Fixes for reporting the correct cwd path in these error messages have been integrated [6]. If you are experiencing issues with pid: null or unexpected behavior, ensure you are running the latest version of Bun, as these discrepancies are being actively addressed to ensure standard compatibility [2][4].

Citations:


🌐 Web query:

Bun.spawn ENOENT throw spawn cwd missing pid documentation

💡 Result:

When using Bun.spawn, encountering an ENOENT error while specifying a custom cwd (current working directory) is often a symptom of an ambiguous or misleading error message rather than a missing executable [1][2][3]. In several versions of Bun, if the provided cwd path does not exist, the runtime may report an ENOENT error. Historically, this error has been confusingly attributed to the executable file path instead of the non-existent directory [1][2][3]. While official documentation defines cwd as the current working directory for the process (defaulting to process.cwd) [4][5][6], it does not explicitly warn that a non-existent path will trigger this specific, often misidentified, ENOENT error. Key points regarding this behavior: - Misleading Error Source: If you pass an invalid or missing directory to the cwd option, Bun may throw an ENOENT error, even if the executable you are trying to spawn is valid and present [1][3]. - Documentation: The official API documentation specifies that cwd is a string representing the working directory, but it does not detail the specific error handling behavior when that directory cannot be accessed [4][5]. - Resolution: If you encounter this error, verify that the directory provided in the cwd option actually exists and is accessible by the process [1][7]. For general ENOENT errors in Bun.spawn (not related to cwd), common causes include the command being missing from the PATH, incorrect environment variables, or insufficient execution permissions [7][8]. If the issue persists despite a valid directory, ensure the executable path is absolute or correctly resolved [4].

Citations:


🌐 Web query:

site:bun.sh/docs spawn ENOENT Bun.spawn throws

💡 Result:

An ENOENT error in the context of Bun.spawn indicates that the system could not find the executable specified in the command arguments [1][2]. When Bun.spawn fails to locate the command, the error often manifests during the process initialization phase. To handle cases where a command might be missing, you should anticipate that the spawned process may fail immediately. You can check the exit status of the subprocess using the properties provided by the returned Subprocess object [1][2]. For example, you can inspect the exit code or use an onExit callback to handle scenarios where the process fails to start or exits unexpectedly: const proc = Bun.spawn(["my-command"], { onExit(proc, exitCode, signalCode, error) { if (exitCode!== 0) { console.error(Process exited with code ${exitCode}); } }, }); await proc.exited; If you are attempting to run a command that relies on a shell (like those found in package.json scripts), remember that Bun provides built-in shell support [3]. If you are explicitly calling an executable, ensure the path is correct or that the command is available in your system's PATH.

Citations:


🌐 Web query:

"Bun.spawn" "ENOENT" throw "pid" "Subprocess"

💡 Result:

The ENOENT error in Bun.spawn occurs when the system cannot find the executable specified or encounters an invalid working directory [1][2][3]. In the context of Bun.spawn, ENOENT (Error NO ENTry) is a standard POSIX error code used to indicate that a file or directory does not exist [4][5]. Common causes for this error include: 1. Executable Not Found: The command provided in the cmd array is not available in the system's PATH or the absolute path provided is incorrect [4][6][5]. 2. Invalid Working Directory (cwd): If the cwd option is specified but the directory does not exist, Bun may throw an ENOENT error [1][2][3]. Users have noted that this can sometimes be confusing because the error message may incorrectly suggest the executable is missing rather than the directory [1][3]. 3. Environment Context: In containerized environments or services (like systemd), the PATH variable or the environment might differ from your interactive shell, leading to cases where an executable (e.g., xdg-open or bash) cannot be located [7][6]. If you encounter this error, verify: - The path to the executable is correct, or that the command is explicitly present in the PATH environment variable [4][5]. - The directory specified in the cwd option exists and is accessible by the user running the process [2]. - The environment variables available to the child process are as expected [2]. Bun.spawn returns a Subprocess object; if it fails to start due to these issues, it throws the ENOENT error before the subprocess is successfully created [8][4][5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- cli/src/commands/worktree.ts around run() ---'
sed -n '380,450p' cli/src/commands/worktree.ts

echo
echo '--- cli/src/index.ts main() and top-level catch ---'
sed -n '1,220p' cli/src/index.ts

Repository: leeguooooo/AgentParty

Length of output: 10389


给 Bun.spawn 加 try/catch
这里的 if (!proc.pid) 兜底基本走不到;启动失败会直接抛出,spawnWithTimeout 就拿不到统一的 GitResult。把启动失败也转成 { code: 1, ... },避免调用方收到异常而不是可处理的失败结果。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/commands/worktree.ts` around lines 62 - 66, 在 spawnWithTimeout 中为
Bun.spawn 调用增加 try/catch,将启动时抛出的异常转换为统一的失败 GitResult(code 为 1,并包含命令及错误信息);保留现有
proc.pid 检查作为兜底,确保调用方不会收到未处理异常。

Comment on lines +76 to +80
const timeout = new Promise<GitResult>((resolve) => {
timer = setTimeout(() => {
proc.kill(); // best-effort;即便管道读不结束,下面 race 也已经拿到超时结果返回。
resolve({ code: 124, stdout: "", stderr: `timed out after ${timeoutMs}ms: ${cmd.join(" ")}` });
}, timeoutMs);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔵 Trivial

proc.kill() 仅发 SIGTERM 且只打顶层进程,无法保证 ssh/credential-helper 真正退出。

commit message 已明确承认这个取舍(超时能独立返回,但派生进程未必退出),本条仅作运维建议:可考虑在 kill 后设置一个短的宽限期,超时未退出再升级为 proc.kill("SIGKILL"),减少长期运行场景下的孤儿进程堆积。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/commands/worktree.ts` around lines 76 - 80, 增强 worktree 命令中 timeout
Promise 的进程终止逻辑:在 proc.kill() 发送 SIGTERM 后设置短暂宽限期,并在进程仍未退出时升级为
proc.kill("SIGKILL"),同时保留现有超时结果立即 resolve 的行为,避免引入额外阻塞。

Comment on lines +93 to +96
export function sanitizeForTerminal(s: string): string {
// eslint-disable-next-line no-control-regex
return s.replace(/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]/g, "");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

sanitizeForTerminal 只剥 ASCII 控制字符,未处理 Unicode 双向覆写字符(如 U+202E RLO)。

正则 [\x00-\x08\x0B-\x1F\x7F] 已正确修复裸回车(\x0D)问题,但 git 分支名允许任意 Unicode,攻击者可用双向覆写/零宽字符在终端视觉上伪造分支名(类似 Trojan-Source 类手法),这类字符不在该字符类范围内。由于本函数目标就是"防转义注入",建议补充剥除常见双向控制字符范围(U+202A-U+202E、U+2066-U+2069 等)。

♻️ 建议补充
 export function sanitizeForTerminal(s: string): string {
   // eslint-disable-next-line no-control-regex
-  return s.replace(/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]/g, "");
+  return s.replace(
+    /\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]|[\u202A-\u202E\u2066-\u2069]/g,
+    "",
+  );
 }

As per path instructions, cli/** 需重点检查"终端输出是否剥离控制字符(防转义注入)",双向覆写字符属于同一类风险的延伸。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function sanitizeForTerminal(s: string): string {
// eslint-disable-next-line no-control-regex
return s.replace(/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]/g, "");
}
export function sanitizeForTerminal(s: string): string {
// eslint-disable-next-line no-control-regex
return s.replace(
/\x1B\[[0-9;]*[A-Za-z]|[\x00-\x08\x0B-\x1F\x7F]|[\u202A-\u202E\u2066-\u2069]/g,
"",
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/commands/worktree.ts` around lines 93 - 96, Update
sanitizeForTerminal to remove Unicode bidirectional and directional-isolate
controls, including U+202A–U+202E and U+2066–U+2069, in addition to the existing
ANSI and ASCII control characters. Keep the current sanitization behavior
unchanged for all other text.

Source: Path instructions

Comment thread cli/test/worktree.test.ts
Comment on lines +140 to 155
describe("spawnWithTimeout", () => {
test("超时独立返回 124,不等命令自然结束(防子进程占管道导致卡死)", async () => {
const t0 = Date.now();
const r = await spawnWithTimeout(["sleep", "5"], root, 200);
expect(r.code).toBe(124);
expect(r.stderr).toContain("timed out");
// 远早于 5s 返回 = 超时确实独立于命令/管道,没干等。
expect(Date.now() - t0).toBeLessThan(4000);
});

test("命令按时结束时返回真实退出码与输出", async () => {
const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000);
expect(r.code).toBe(0);
expect(r.stdout).toBe("ok");
});
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

spawnWithTimeout 测试未覆盖 spawn 失败场景,且超时用例无法区分新旧实现。

两点建议:

  1. sleep 5 没有子进程占用管道,kill 后其自身 stdout/stderr 会立刻关闭,因此就算退回到旧的、依赖管道读完才返回超时结果的实现,这条用例大概率也能在 4000ms 内通过——并不能真正验证"超时独立于管道读取"这一核心修复点(原始 critical 问题正是"派生子进程占着管道")。
  2. 缺少 spawn 失败(如命令不存在)的用例。这恰好会暴露 Bun.spawn 同步 throw 未被捕获的问题(见 worktree.ts 中对应评论)——目前这种场景下 spawnWithTimeout 会 reject 而不是 resolve 出 {code: 1, ...}。
✅ 建议补充用例
   test("命令按时结束时返回真实退出码与输出", async () => {
     const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000);
     expect(r.code).toBe(0);
     expect(r.stdout).toBe("ok");
   });
+
+  test("spawn 失败(命令不存在)时返回 code 1,而不是 reject", async () => {
+    const r = await spawnWithTimeout(["party-worktree-nonexistent-cmd-xyz"], root, 2000);
+    expect(r.code).toBe(1);
+    expect(r.stderr).toContain("failed to start");
+  });
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe("spawnWithTimeout", () => {
test("超时独立返回 124,不等命令自然结束(防子进程占管道导致卡死)", async () => {
const t0 = Date.now();
const r = await spawnWithTimeout(["sleep", "5"], root, 200);
expect(r.code).toBe(124);
expect(r.stderr).toContain("timed out");
// 远早于 5s 返回 = 超时确实独立于命令/管道,没干等。
expect(Date.now() - t0).toBeLessThan(4000);
});
test("命令按时结束时返回真实退出码与输出", async () => {
const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000);
expect(r.code).toBe(0);
expect(r.stdout).toBe("ok");
});
});
describe("spawnWithTimeout", () => {
test("超时独立返回 124,不等命令自然结束(防子进程占管道导致卡死)", async () => {
const t0 = Date.now();
const r = await spawnWithTimeout(["sleep", "5"], root, 200);
expect(r.code).toBe(124);
expect(r.stderr).toContain("timed out");
// 远早于 5s 返回 = 超时确实独立于命令/管道,没干等。
expect(Date.now() - t0).toBeLessThan(4000);
});
test("命令按时结束时返回真实退出码与输出", async () => {
const r = await spawnWithTimeout(["sh", "-c", "printf ok"], root, 5000);
expect(r.code).toBe(0);
expect(r.stdout).toBe("ok");
});
test("spawn 失败(命令不存在)时返回 code 1,而不是 reject", async () => {
const r = await spawnWithTimeout(["party-worktree-nonexistent-cmd-xyz"], root, 2000);
expect(r.code).toBe(1);
expect(r.stderr).toContain("failed to start");
});
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/test/worktree.test.ts` around lines 140 - 155, 增强 spawnWithTimeout
测试覆盖:将超时命令改为会派生子进程并让其继承 stdout/stderr
管道的场景,确保超时结果独立于管道关闭且不会等待子进程;在同一测试套件新增不存在命令的用例,验证 Bun.spawn 失败时 spawnWithTimeout
resolve 为 code 1 并返回错误信息,而不是 reject。

@leeguooooo

Copy link
Copy Markdown
Owner Author

review-ack: 合并者已读 pr_agent + CodeRabbit 两轮评审并逐条核实采纳。

第一轮

  • 🔴 defaultGit 无交互认证防护/超时 → 加 GIT_TERMINAL_PROMPT=0 + 超时熔断
  • 🟠 rev-parse 失败静默降级 → 失败即抛(TDD+变异)
  • 🟡 终端输出未剥控制字符 → sanitizeForTerminal(TDD+变异)
  • 🟡 我两条测试断言太松 → 改精确断言

第二轮

  • 🔴 硬超时是假的(proc.kill 只杀顶层 git,派生 ssh/helper 占管道则 Promise.all 卡住、超时回不来)→ 抽 spawnWithTimeout 用 Promise.race 让超时独立返回(TDD:sleep5+200ms 断言 <4s 返回;变异去 race 复红)
  • 🔵 spawn 失败先返回错误再挂 timer(pr_agent-8)→ 采纳
  • 🟡 sanitize 漏剥裸 CR(\x0D) → 字符类合并 \x0B-\x1F(TDD real\rFAKE)
  • 🔵 sanitized 分支名复用为 git 参数 → raw 喂 git、仅打印 sanitize,防未来误删/误推

第三轮:pr_agent 两条为已采纳项的旧快照;CodeRabbit 一条(CR 剥除)是上一提交已修的过时快照。评审收敛,无新增可行动项。

12/12、tsc 0,两处安全修复(超时 race、rev-parse throw)+ sanitize 均 TDD 先红后绿、变异亲验。CodeRabbit check 卡 pending 是其自身状态延迟(review 已落已读),非必需 check。流程漏洞(可预先 ack / 非必需 review 落地前就合)已记 #460。

@leeguooooo leeguooooo reopened this Jul 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit c38850a

@leeguooooo
leeguooooo merged commit 441adcf into main Jul 13, 2026
33 checks passed
@leeguooooo
leeguooooo deleted the fix/worktree-hardening-cr456 branch July 21, 2026 01:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant