Skip to content
Merged
Show file tree
Hide file tree
Changes from 48 commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
2480163
feat(daemon): guard cross-worktree Git mutations
wenshao Aug 7, 2026
2b0e8cd
fix(daemon): keep Git guard off serve fast path
wenshao Aug 7, 2026
107b5f6
Merge branch 'main' into feat/daemon-git-worktree-guard
wenshao Aug 7, 2026
b175cd7
fix(serve): close daemon Git guard parser bypasses
wenshao Aug 7, 2026
2af7419
Merge branch 'main' into feat/daemon-git-worktree-guard
qwen-code-dev-bot Aug 7, 2026
b1b7606
fix(serve): keep daemon Git guard out of serve fast-path closure
wenshao Aug 7, 2026
83428be
fix(serve): close re-reviewed daemon Git guard bypasses and subagent …
wenshao Aug 8, 2026
18e997a
fix(serve): restore lazy daemon Git guard import
wenshao Aug 8, 2026
ab1e3e2
fix(serve): close daemon Git guard shell front-end bypasses
wenshao Aug 8, 2026
45753e0
fix(serve): restore the shell-wrapper analysis return shape
wenshao Aug 8, 2026
c14ffc4
fix(serve): close the remaining daemon Git guard front-end gaps
wenshao Aug 8, 2026
7f66be6
fix(serve): resolve the repository Git discovers, not just the directory
wenshao Aug 8, 2026
b11585b
fix(serve): match chdir, brace-expansion and here-string semantics
wenshao Aug 8, 2026
dfeb461
fix(serve): treat relocated git describe as a target-repo write
wenshao Aug 8, 2026
af36eca
docs(serve): state what git describe actually rewrites
wenshao Aug 8, 2026
8112fae
test(serve): cover the provider-attached marker with a real handshake
wenshao Aug 8, 2026
338e0c7
fix(serve): close the round-3 shell and repository-discovery gaps
wenshao Aug 8, 2026
d9a3911
fix(serve): scope the relink invalidation to path-resolving Git runs
wenshao Aug 8, 2026
012d252
fix(serve): rebuild the relink defense and close the round-4 gaps
wenshao Aug 9, 2026
2bf64cd
fix(serve): carry relink and shell state across nested scopes
wenshao Aug 9, 2026
0a58fe7
fix(daemon): evaluate the guard against the directory the tool runs in
wenshao Aug 9, 2026
cbcde28
Merge branch 'main' into feat/daemon-git-worktree-guard
wenshao Aug 9, 2026
3a247f7
fix(daemon): reach the real guard path and close the round-6 escapes
wenshao Aug 10, 2026
a1652cc
fix(daemon): contain a sub-agent to an in-project agent worktree
wenshao Aug 10, 2026
581d2bb
test(acp): assert the session identity and cwd the guard now receives
wenshao Aug 10, 2026
6b755d1
fix(daemon): record ordinary targets a dynamic relinker re-points
wenshao Aug 10, 2026
8baf7a7
Merge branch 'main' into feat/daemon-git-worktree-guard
qwen-code-dev-bot Aug 10, 2026
0f970d4
fix(daemon): close the round-7 escapes, verified with the reported pa…
wenshao Aug 10, 2026
8e46dba
fix(daemon): repair the round-7 patch and bound what this guard promises
wenshao Aug 11, 2026
089c3e3
fix(daemon): close the round-9 critical forms an agent may actually emit
wenshao Aug 11, 2026
a2736b8
Merge remote-tracking branch 'origin/main' into work8687
wenshao Aug 11, 2026
cf2ea23
fix(daemon): replay an alias with the args its invocation appends
wenshao Aug 11, 2026
7f4746f
fix(daemon): carry a function/alias body's cwd and exports to the caller
wenshao Aug 11, 2026
6273464
fix(daemon): inherit the caller's allexport into a same-shell body
wenshao Aug 11, 2026
01587ab
fix(daemon): complete the same-shell state model for bodies and subst…
wenshao Aug 11, 2026
2f0b99f
fix(daemon): resolve shadowing and exported functions; isolate pipe s…
wenshao Aug 11, 2026
a2ae8bb
fix(daemon): close the interlocking gaps in my function-model work
wenshao Aug 11, 2026
6deb8bd
fix(daemon): deny relocations disguised by a redirection
wenshao Aug 11, 2026
a43faa8
fix(daemon): deny relocation hidden by a leading redirect or a backgr…
wenshao Aug 12, 2026
1203072
Merge remote-tracking branch 'origin/main' into work8687
wenshao Aug 12, 2026
e595f7b
fix(daemon): don't let a harmless or removed shadow mask a relocation
wenshao Aug 12, 2026
70f5162
fix(daemon): drop exported functions when env clears the child enviro…
wenshao Aug 12, 2026
68eb534
test(daemon): pin the sh-wrapper fail-closed contract and document it
wenshao Aug 12, 2026
3333331
fix(daemon): model shell-definition removal the way the real shell does
wenshao Aug 12, 2026
636602c
fix(daemon): bare unset keeps the function and env -u strips exported…
wenshao Aug 12, 2026
5fc219d
fix(daemon): fail closed when a removal builtin could retract a track…
wenshao Aug 13, 2026
6128e69
fix(daemon): skip leading redirections before the removal-builtin pre…
wenshao Aug 13, 2026
d95d87c
fix(daemon): replay a shadowed removal builtin and drop unset variables
wenshao Aug 13, 2026
a5f8099
fix(daemon): honor shadowed command/builtin prefixes and PATH-based r…
wenshao Aug 13, 2026
c7b6aa4
fix(daemon): catch delimiter-glued relocations and redirect-decoy pre…
wenshao Aug 14, 2026
a0427ae
fix(daemon): deny trailer/man/sendemail command-executing config keys
wenshao Aug 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
269 changes: 269 additions & 0 deletions docs/design/daemon-git-worktree-guard.md

Large diffs are not rendered by default.

74 changes: 37 additions & 37 deletions docs/developers/qwen-serve-protocol.md

Large diffs are not rendered by default.

65 changes: 65 additions & 0 deletions docs/users/qwen-serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,71 @@ Notes:
> matched case-sensitively by yargs `choices` (`--memory-project-scope
Workspace` is rejected). Use lowercase values when copying between the two.

### Built-in daemon Git relocation guard

Every managed daemon ACP session applies a built-in pre-execution guard for
model shell commands, independent of `--external-tool-guard-mode` and without
any capability advertisement. The daemon owns the bound workspace and the
session's current effective working directory; both are supplied from trusted
session state and never accepted from the ACP child.

The guard inspects the tools that run a shell command line — `run_shell_command`
and `monitor` — and denies a mutating Git
command before execution when its repository location resolves outside the
session's effective working directory. Relocation is recognized for literal
forms of `git -C <path>`, `git --git-dir[=]<path>`,
`git --work-tree[=]<path>`, leading
`GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR`/`GIT_INDEX_FILE` assignments (also
when made through `export`/`declare`/`readonly`, which keep them in the
environment of every later command in the chain),
directory-shifting wrapper flags (`env -C`, `sudo -D`), and `cd`, `pushd`, or
`popd` builtins earlier in the same command chain. Common wrapper prefixes
(`sh -c`, `bash -c`, `eval`, `sudo`, `nohup`, `timeout`, `exec`, `command`,
`builtin`,
`env`, path-qualified `git` binaries, and `{ …; }` / `! …` shell syntax) are
unwrapped so the same policy applies to the inner Git invocation, and `$(…)`
or backtick substitution bodies are analyzed as commands of their own.

A sub-agent pinned to its own worktree is contained to that worktree rather
than to the session's directory; a shell call whose execution directory the
daemon cannot place is denied.

Relative targets resolve from the command's effective starting directory
(`arguments.directory` when present, otherwise the session's current effective
working directory) after canonical path resolution, including `.git` gitfile
redirects, symlinks, and per-worktree administrative directories. A relocated
target that cannot be fully resolved before execution — a dynamic target
(`$VAR`, backticks, `~`, globs), a path that does not exist yet, or an
unreadable indirection — is denied for mutating or unclassifiable subcommands.
A relocated target that cannot be resolved is denied whatever the subcommand
is — including the read-only ones. Relocated commands whose subcommand is one
of a small verified read-only set (`rev-parse`, `cat-file`) remain allowed
once the target resolves, unless the command carries command-executing `-c`
config, or
it carries a `--output`, `--textconv`, or `--filters` flag: those write a file
or run the target repository's configured drivers. Commands with no recognized
relocation keep their existing behavior.
Denials are final and are reported to the model as
`Daemon shell guard denied a mutating Git command…` for a resolved, dynamic,
or unresolvable repository location, and as
`Daemon shell guard denied a shell command…` when the command could not be
parsed, its payload could not be resolved, or an unrecognized program may run
a relocated Git command.

The guard is reliable against Git relocation written in the literal forms
above — the mis-targeted command this control exists for — and is
**best-effort, not a boundary**, against shell text written to defeat it:
constructions that hide the relocation from a static reader may pass, and new
ones will keep being found. Do not grant a daemon broader trust on the
strength of it. It does not interpret script files,
track environment variable values across commands, or analyze heredoc bodies
(Git-shaped text inside a heredoc can be denied even though the shell never
executes it). `/fork` and agent-backed workspace memory remember/dream remain
available under the built-in guard; they are only restricted while the
external provider mode below is active. An optional external tool guard
remains an additional policy and receives the same request only after the
built-in policy allows it.

### Required external Tool Guard

This opt-in is for managed ACP deployments that need an external allow/deny
Expand Down
112 changes: 112 additions & 0 deletions packages/acp-bridge/src/bridgeClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,10 +250,14 @@ describe('BridgeClient — managed external tool guard', () => {
});
const entry: {
sessionId: string;
workspaceCwd: string;
effectiveCwd: string;
promptActive: boolean;
activePromptId?: string;
} = {
sessionId: 'session-1',
workspaceCwd: '/workspace',
effectiveCwd: '/workspace/worktree',
promptActive: true,
activePromptId: 'prompt-1',
};
Expand All @@ -278,9 +282,117 @@ describe('BridgeClient — managed external tool guard', () => {
toolCallId: 'call-1',
toolName: 'write_file',
arguments: { path: 'README.md' },
effectiveCwd: '/workspace/worktree',
});
});

it('ignores a forged effective directory in the child payload', async () => {
const handler = vi.fn<ExternalToolGuardHandler>().mockResolvedValue({
allowed: true,
});
const entry: {
sessionId: string;
workspaceCwd: string;
effectiveCwd: string;
promptActive: boolean;
activePromptId?: string;
} = {
sessionId: 'session-1',
workspaceCwd: '/workspace',
effectiveCwd: '/workspace/worktree',
promptActive: true,
activePromptId: 'prompt-1',
};
const client = makeClient(undefined, {
resolveEntry: (sessionId) =>
sessionId === entry.sessionId ? entry : undefined,
handler,
});

await expect(
client.extMethod(SERVE_CONTROL_EXT_METHODS.externalToolGuardPrepare, {
sessionId: 'session-1',
promptId: 'prompt-1',
toolCallId: 'call-1',
toolName: 'write_file',
arguments: { path: 'README.md' },
effectiveCwd: '/forged/effective',
}),
).resolves.toEqual({ allowed: true });
expect(handler).toHaveBeenCalledWith({
sessionId: 'session-1',
promptId: 'prompt-1',
toolCallId: 'call-1',
toolName: 'write_file',
arguments: { path: 'README.md' },
effectiveCwd: '/workspace/worktree',
});
});

it('accepts a prompt-less shell check validated by session ownership', async () => {
const handler = vi.fn<ExternalToolGuardHandler>().mockResolvedValue({
allowed: true,
});
const entry: {
sessionId: string;
workspaceCwd: string;
effectiveCwd: string;
promptActive: boolean;
activePromptId?: string;
} = {
sessionId: 'session-1',
workspaceCwd: '/workspace',
effectiveCwd: '/workspace/worktree',
promptActive: false,
};
const client = makeClient(undefined, {
resolveEntry: (sessionId) =>
sessionId === entry.sessionId ? entry : undefined,
handler,
});

await expect(
client.extMethod(SERVE_CONTROL_EXT_METHODS.externalToolGuardPrepare, {
sessionId: 'session-1',
toolCallId: 'call-1',
toolName: 'run_shell_command',
arguments: { command: 'pwd' },
}),
).resolves.toEqual({ allowed: true });
expect(handler).toHaveBeenCalledWith({
sessionId: 'session-1',
toolCallId: 'call-1',
toolName: 'run_shell_command',
arguments: { command: 'pwd' },
effectiveCwd: '/workspace/worktree',
});
});

it('rejects an empty prompt id in a guard request', async () => {
const handler = vi.fn<ExternalToolGuardHandler>().mockResolvedValue({
allowed: true,
});
const client = makeClient(undefined, {
resolveEntry: () => ({
sessionId: 'session-1',
promptActive: true,
activePromptId: 'prompt-1',
}),
handler,
});

await expect(
client.extMethod(SERVE_CONTROL_EXT_METHODS.externalToolGuardPrepare, {
sessionId: 'session-1',
promptId: '',
toolCallId: 'call-1',
toolName: 'run_shell_command',
arguments: {},
}),
).rejects.toThrow('Invalid external tool guard request');
expect(handler).not.toHaveBeenCalled();
});

it('rejects a stale prompt without contacting the host', async () => {
const handler = vi.fn<ExternalToolGuardHandler>().mockResolvedValue({
allowed: true,
Expand Down
31 changes: 25 additions & 6 deletions packages/acp-bridge/src/bridgeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,8 @@ function sliceLineRange(
*/
export interface BridgeClientSessionEntry {
sessionId: string;
workspaceCwd: string;
effectiveCwd: string;
events: EventBus;
artifacts: SessionArtifactStore;
recordingDegraded: boolean;
Expand Down Expand Up @@ -1297,8 +1299,8 @@ export class BridgeClient implements Client {
if (
typeof sessionId !== 'string' ||
sessionId.length === 0 ||
typeof promptId !== 'string' ||
promptId.length === 0 ||
(promptId !== undefined &&
(typeof promptId !== 'string' || promptId.length === 0)) ||
typeof toolCallId !== 'string' ||
toolCallId.length === 0 ||
typeof toolName !== 'string' ||
Expand All @@ -1310,32 +1312,49 @@ export class BridgeClient implements Client {
'Invalid external tool guard request',
);
}
// Context-less shell checks (subagents, cron turns, resumed background
// agents) carry no prompt binding; they are validated by session
// ownership alone. The host handler decides whether its policy can run
Comment thread
wenshao marked this conversation as resolved.
Resolved
// without a live prompt.
const promptScoped = promptId !== undefined;
if (!this.ownsSession(sessionId)) {
throw RequestError.invalidParams(
undefined,
'External tool guard session is not owned by this connection',
);
}
const entry = this.resolveEntry(sessionId);
if (!entry || !entry.promptActive || entry.activePromptId !== promptId) {
if (
!entry ||

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Critical] R2-16: Prompt-less guard requests accept any sibling sessionId owned by the same multiplexed BridgeClient channel.

Failure scenario: Context-less work originating in session A supplies session B's id; channel ownership passes, and the guard receives B's trusted effectiveCwd, allowing mutation of B's checkout.

Suggested fix: Bind every context-less request to host-owned originating-session state rather than trusting a child-supplied sessionId.

中文说明

无 prompt 的守卫请求会接受同一复用 BridgeClient 通道中属于其他会话的任意 sessionId。

失败场景:来自会话 A 的无上下文工作可提交会话 B 的 ID;通道所有权检查会通过,守卫随后使用 B 受信任的 effectiveCwd,从而允许修改 B 的 checkout。

建议修复:将每个无上下文请求绑定到宿主持有的发起会话状态,不要信任子进程提供的 sessionId。

— gpt-5.6-sol via Qwen Code /review (v0.21.9)

(promptScoped &&
(!entry.promptActive || entry.activePromptId !== promptId))
) {
Comment on lines 1326 to +1331

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Suggestion] R6-S3: On the new prompt-less path (promptScoped=false) both rejection messages reference a prompt the request does not carry: a missing entry is rejected with 'External tool guard prompt is not the active prompt' and a replaced entry with '…no longer active' — the actual cause is session-entry lifecycle. — Failure scenario: An operator diagnosing denied subagent/cron/resumed-agent shell calls is pointed at prompt binding when the cause is a missing or changed session entry.

Suggested fix: When !promptScoped, use entry-scoped messages ('session has no live entry' / 'session entry changed during evaluation').

中文说明

新的无 prompt 路径(promptScoped=false)上,两条拒绝消息都在引用请求根本未携带的 prompt:条目缺失被拒为 'External tool guard prompt is not the active prompt',条目被替换被拒为 '…no longer active'——真实原因是会话条目生命周期。后果:排查子代理/cron/恢复后台代理 shell 调用被拒的运维会被引向 prompt 绑定而非会话条目状态。修复:!promptScoped 时改用会话条目语义的消息('session has no live entry' / 'session entry changed during evaluation')。

— qwen3.8-max via Qwen Code /review (v0.21.10)

throw RequestError.invalidParams(
undefined,
'External tool guard prompt is not the active prompt',
);
}
const invocationCwd = params['invocationCwd'];
const decision: unknown = await this.externalToolGuard({
sessionId: entry.sessionId,
promptId: entry.activePromptId,
...(promptScoped ? { promptId } : {}),
toolCallId,
toolName,
arguments: args,
effectiveCwd: entry.effectiveCwd,
Comment thread
wenshao marked this conversation as resolved.
Resolved
// Forwarded verbatim and explicitly untrusted: the host policy decides
// whether it can establish this scope from state it owns.
...(typeof invocationCwd === 'string' && invocationCwd.length > 0

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Critical] R2-3: A child-reported invocationCwd is accepted by containment alone instead of being bound to the invoking agent's assigned worktree.

Failure scenario: An agent assigned to worktree A reports sibling worktree B as invocationCwd; the daemon accepts the session-owned path and authorizes a mutating Git command against B.

Suggested fix: Derive the invocation boundary from host-owned agent/session state and reject child-reported directories that do not exactly match that assignment.

中文说明

子进程上报的 invocationCwd 只经过包含关系检查,没有绑定到调用 agent 被分配的 worktree。

失败场景:分配到 worktree A 的 agent 可将兄弟 worktree B 上报为 invocationCwd;daemon 会接受这个会话拥有的路径,并授权针对 B 的 Git 修改命令。

建议修复:从宿主持有的 agent/session 状态推导调用边界,并拒绝与该分配不完全一致的子进程上报目录。

— gpt-5.6-sol via Qwen Code /review (v0.21.9)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Suggestion] R2-14: Bridge tests do not verify invocationCwd reaches the daemon handler together with effectiveCwd.

Concrete cost: A transport regression can drop or rename invocationCwd while lower-layer guard tests remain green and worktree-pinned agents are checked against the wrong boundary.

Suggested fix: Add a bridge-level regression test asserting both cwd fields and their session binding at the handler.

中文说明

Bridge 测试没有验证 invocationCwd 与 effectiveCwd 一起到达 daemon handler。

具体代价:传输层回归可能丢弃或重命名 invocationCwd,而底层 guard 测试仍通过,导致固定到 worktree 的 agent 使用错误边界检查。

建议修复:增加 bridge 层回归测试,在 handler 处断言两个 cwd 字段及其 session 绑定。

— gpt-5.6-sol via Qwen Code /review (v0.21.9)

? { invocationCwd }
: {}),
});
const currentEntry = this.resolveEntry(sessionId);
if (
!this.ownsSession(sessionId) ||
currentEntry !== entry ||
!currentEntry.promptActive ||
currentEntry.activePromptId !== promptId
(promptScoped &&
(!currentEntry.promptActive ||
currentEntry.activePromptId !== promptId))
) {
throw RequestError.invalidParams(
undefined,
Expand Down
17 changes: 16 additions & 1 deletion packages/acp-bridge/src/bridgeOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,25 @@ export type BridgeSessionLifecycle = (
*/
export interface ExternalToolGuardPrepareRequest {
readonly sessionId: string;
readonly promptId: string;
/**
* Runtime-owned active-prompt binding. Absent for context-less shell
* checks: subagent reasoning loops, cron turns, background notifications,
* and resumed background agents run without an invocation context by
* design. A host policy that requires a live prompt must fail closed when
* the binding is missing.
*/
readonly promptId?: string;
readonly toolCallId: string;
readonly toolName: string;
readonly arguments: Readonly<Record<string, unknown>>;
/** Daemon-owned current session working directory. */
readonly effectiveCwd?: string;
/**
* Directory the child will actually run the tool in, when it differs from
* the session's own. Untrusted: the host validates it against state it
* owns before using it as a containment basis.
*/
readonly invocationCwd?: string;
}

export type ExternalToolGuardPrepareResult =
Expand Down
32 changes: 32 additions & 0 deletions packages/acp-bridge/src/externalToolGuard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@
export const PRIVATE_EXTERNAL_TOOL_GUARD_ENV =
'QWEN_CODE_PRIVATE_EXTERNAL_TOOL_GUARD';

/**
* Private, non-secret marker passed from `qwen serve` to its ACP child only
* when a real external tool guard provider is attached. Without it the child
* still installs the managed guard plumbing (the daemon's built-in policy
* needs it), but resolves every non-shell tool locally and keeps `/fork` and
* agent-backed workspace memory available: those features are only disabled
* for the external provider's v1 contract, which cannot observe hidden-agent
* execution.
*/
export const PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV =
'QWEN_CODE_PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER';

/**
* ACP initialize-response metadata proving that the child consumed the
* private activation marker and installed the required executor callback.
Expand All @@ -26,6 +38,26 @@ export const EXTERNAL_TOOL_GUARD_READY_META_KEY =
*/
export const EXTERNAL_TOOL_GUARD_REQUIRED_VALUE = 'required-v1';

/**
* The provider-attached marker value `qwen serve` passes to the child when a
* real external tool guard provider is configured.
*/
export const EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE = 'attached-v1';

/**
* Tools whose arguments carry a shell command line the host runs on the
* session's behalf. The daemon's built-in policy inspects exactly these, and
* the ACP child resolves every other tool locally when no external provider
* is attached. Pinned to `ToolNames.SHELL`/`ToolNames.MONITOR` in
* `@qwen-code/qwen-code-core`, which this package deliberately does not
* depend on; `daemon-git-worktree-guard.test.ts` asserts the values still
* match so a rename cannot silently unhook a tool from the guard.
*/
export const SHELL_EXECUTING_TOOL_NAMES: ReadonlySet<string> = new Set([
'monitor',
'run_shell_command',
]);

/** Daemon-local bearer token for the loopback external Tool Guard provider. */
export const EXTERNAL_TOOL_GUARD_TOKEN_ENV =
'QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN';
Expand Down
Loading
Loading