Skip to content

feat(cli): group daemon channel workers by workspace (phase 4b) - #6635

Merged
doudouOUC merged 13 commits into
QwenLM:mainfrom
doudouOUC:feat/daemon-multi-workspace-phase4b-channel-workers
Jul 11, 2026
Merged

doudouOUC merged 13 commits into
QwenLM:mainfrom
doudouOUC:feat/daemon-multi-workspace-phase4b-channel-workers

Conversation

@doudouOUC

Copy link
Copy Markdown
Collaborator

What this PR does

A qwen serve daemon that binds multiple workspaces can now host daemon-managed channels for each of them. Previously the channel worker assumed a single workspace and was always bound to the primary, so channels configured for a non-primary workspace could not run. This change groups the requested channels by their owning workspace and starts one worker per trusted workspace that owns a selected channel, each bound to that workspace's directory, its daemon-workspace environment marker, and its own effective environment overlay.

Ownership is resolved implicitly from a channel's configured working directory: a channel belongs to the registered workspace its resolved cwd matches, which is exactly the rule the worker already enforces for itself, so the serve-layer grouping and the worker's own validation always agree. A selected channel that resolves to no registered workspace, to more than one (an ambiguous user/system-scope entry with no explicit working directory), or to an untrusted workspace fails fast at daemon startup rather than half-enabling.

The channel service pidfile and the daemon status response grow an additive per-workspace worker list, while the existing single-worker fields stay populated (the union of channels, and the primary worker's live pid) so older readers keep working. --channel all stays primary-only in this version to avoid implicit cross-workspace process fan-out. Single-workspace behavior is intentionally unchanged and byte-identical: no per-workspace worker list, no workspace-prefixed log lines, and the same pidfile and status shape as before.

Why it's needed

This is the channel-workers slice of the multi-workspace daemon work (RFC in the linked issue). Multi-workspace session serving already landed in earlier phases, but daemon-managed channels were still single-workspace, so operators running one daemon across several repositories could not host a channel that belongs to a non-primary workspace. Grouping workers by workspace closes that gap while keeping the single-workspace path exactly as it is today.

Reviewer Test Plan

How to verify

Single-workspace (regression): run the daemon with a configured channel and confirm behavior is unchanged — one worker starts after the runtime is ready, the pidfile keeps the original { channels, servePid, workerPid } shape with no worker list, GET /daemon/status reports the existing runtime.channelWorker with no channelWorkers, and the daemon log lines carry no workspace prefix.

Multi-workspace: start the daemon with repeated --workspace values and select a channel that belongs to a non-primary workspace (define it in that workspace's own settings, or set an explicit working directory pointing at it). Confirm a worker starts bound to that workspace, that the pidfile now carries an additive per-workspace workers[] entry, and that GET /daemon/status exposes runtime.channelWorkers[] annotated with workspace id / cwd / primary while runtime.channelWorker still reflects the primary.

Failure paths: a selected channel that is not configured in any registered workspace, that is ambiguous across workspaces (a global entry with no working directory), or that targets an untrusted workspace should fail daemon startup with a clear error; --channel all on a multi-workspace daemon should host only the primary workspace's channels.

Local checks run: cd packages/cli && npx tsc --noEmit (typecheck clean), ESLint and Prettier clean on the touched files, and the affected unit suites green — the new grouping and worker-group suites plus the channel supervisor, daemon-worker, pidfile, daemon-status, server, and serve orchestration suites (936 tests passing). New unit tests cover the grouping rules (explicit cwd, workspace-scope, ambiguous, unregistered, untrusted, --channel all, single-workspace) and the worker-group lifecycle.

Evidence (Before & After)

N/A — no user-visible / TUI change; the surface is the daemon CLI, pidfile, and status JSON.

Tested on

OS Status
🍏 macOS ✅
🪟 Windows ⚠️
🐧 Linux ⚠️

Environment (optional)

Unit tests only (vitest). A full npm run build was not completed locally because web-shell / webui have pre-existing, unrelated typecheck errors; the cli package typechecks cleanly on its own.

Risk & Scope

  • Main risk or tradeoff: channel worker creation moved from the listen callback into runtime startup so it can read the workspace registry and per-workspace env overlays; mitigated by keeping the single-workspace path unchanged and by the existing serve-startup regression suite (startup failure still rejects runQwenServe, closes the listener, and clears the pidfile reservation).
  • Not validated / out of scope: workspace-qualified voice and dynamic workspace add/remove (later phases); full multi-OS run (CI covers Windows/Linux); a full repo build (blocked by unrelated web-shell / webui typecheck errors).
  • Breaking changes / migration notes: none. The pidfile workers[] and status channelWorkers[] fields are additive and only appear in multi-workspace mode; single-workspace output is byte-identical to before.

Linked Issues

Refs #6378 — this is the Phase 4b channel-workers slice of that umbrella RFC and does not close it.

中文说明

这个 PR 做了什么

绑定多个工作区的 qwen serve daemon 现在可以为每个工作区托管 daemon 管理的 channel。此前 channel worker 假设只有一个工作区、且始终绑定 primary,因此配置在非 primary 工作区的 channel 无法运行。本次改动把所请求的 channel 按其归属工作区分组,为每个"拥有被选 channel 且受信"的工作区各启动一个 worker,分别绑定该工作区的目录、daemon-workspace 环境标记以及各自的 effective env overlay。

归属由 channel 配置的工作目录隐式判定:channel 归属于"其解析后的 cwd 命中的已注册工作区",这与 worker 自身对工作区的校验规则完全一致,因此 serve 层的分组与 worker 自校验始终一致。若被选 channel 解析不到任何已注册工作区、解析到多个(user/system 作用域且未显式设 cwd 的歧义项)、或指向未受信工作区,则在 daemon 启动时快速失败,而不是半启用。

channel 服务 pidfile 与 daemon 状态响应新增一个"按工作区"的 worker 列表(additive),同时保留原有的单-worker 字段(channels 的并集,以及 primary worker 的存活 pid),以兼容旧读端。--channel all 本版仍保持 primary-only,避免隐式跨工作区进程扩散。单工作区行为刻意保持不变、字节等价:没有按工作区 worker 列表、没有带工作区前缀的日志、pidfile 与状态形状与此前一致。

为什么需要

这是多工作区 daemon 工作(见关联 issue 的 RFC)的 channel-workers 分片。多工作区会话服务已在前序阶段落地,但 daemon 管理的 channel 仍是单工作区,导致跨多个仓库运行同一 daemon 的用户无法托管归属非 primary 工作区的 channel。按工作区分组 worker 弥补了这一缺口,同时让单工作区路径与今天完全一致。

复核测试计划

如何验证

单工作区(回归):用配置好的 channel 启动 daemon,确认行为不变——运行时就绪后启动一个 worker,pidfile 保持原有 { channels, servePid, workerPid } 形状且无 worker 列表,GET /daemon/status 报告已有的 runtime.channelWorker 且无 channelWorkers,日志行无工作区前缀。

多工作区:用重复的 --workspace 启动 daemon,并选择一个归属非 primary 工作区的 channel(在该工作区自身 settings 定义,或显式设置指向它的工作目录)。确认启动一个绑定该工作区的 worker,pidfile 新增按工作区的 workers[] 条目,GET /daemon/status 暴露带 工作区 id/cwd/primary 标注的 runtime.channelWorkers[],而 runtime.channelWorker 仍反映 primary。

失败路径:未在任何已注册工作区配置的 channel、跨工作区歧义(无工作目录的全局项)、或指向未受信工作区,应让 daemon 启动失败并给出清晰错误;多工作区下 --channel all 应只托管 primary 工作区的 channel。

本地检查:cd packages/cli && npx tsc --noEmit(typecheck 通过);触及文件的 ESLint 与 Prettier 干净;受影响单测全绿——新增的分组与 worker-group 套件,加上 channel supervisor、daemon-worker、pidfile、daemon-status、server 与 serve 编排套件(936 用例通过)。新增单测覆盖分组规则(显式 cwd、workspace 作用域、歧义、未注册、未受信、--channel all、单工作区)与 worker-group 生命周期。

证据(前/后)

N/A —— 无用户可见 / TUI 变更;影响面是 daemon CLI、pidfile 与状态 JSON。

测试环境

OS 状态
🍏 macOS ✅
🪟 Windows ⚠️
🐧 Linux ⚠️

仅单元测试(vitest)。本地未完成完整 npm run build,因为 web-shell / webui 存在预先存在、与本次无关的 typecheck 报错;cli 包单独 typecheck 通过。

风险与范围

  • 主要风险/取舍:channel worker 的创建从 listen 回调移入运行时启动阶段,以便读取工作区注册表与按工作区的 env overlay;通过保持单工作区路径不变以及既有 serve 启动回归套件(启动失败仍会拒绝 runQwenServe、关闭监听、清理 pidfile 预留)来缓解。
  • 未验证 / 范围外:工作区限定的 voice 与动态工作区增删(后续阶段);完整多 OS 运行(由 CI 覆盖 Windows/Linux);完整仓库构建(被 web-shell / webui 无关的 typecheck 报错阻塞)。
  • 破坏性变更 / 迁移说明:无。pidfile workers[] 与状态 channelWorkers[] 均为 additive,且仅在多工作区模式出现;单工作区输出与此前字节等价。

关联 issue

Refs #6378 —— 本 PR 是该总 RFC 的 Phase 4b channel-workers 分片,不关闭该 issue。

Multi-workspace `qwen serve --channel` now runs one channel worker per owning workspace instead of a single primary-bound worker. Each worker binds to its workspace's directory, daemon-workspace env marker, and effective env overlay. Channels are grouped implicitly by their configured working directory: a channel belongs to the registered workspace its resolved cwd matches, mirroring the worker's own workspace validation. Unknown, ambiguous, or untrusted targets fail fast at startup.

The pidfile and daemon status grow an additive per-workspace worker list while keeping the existing single-worker fields for older readers; single-workspace daemons stay byte-identical to before. `--channel all` stays primary-only.

Refs QwenLM#6378
Comment thread packages/cli/src/serve/daemon-status.ts Resolved
Comment thread docs/users/qwen-serve.md Resolved
Comment thread packages/cli/src/serve/daemon-status.ts Resolved
@wenshao

wenshao commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /resolve

…channel reload

Integrate origin/main's channel_reload feature (reloadChannelWorker +
createDisabledChannelWorkerSupervisor) with the phase 4b
ChannelWorkerGroup refactoring:

- run-qwen-serve.ts: keep ChannelWorkerGroup declarations, adapt
  reloadChannelWorker to stop/start the group and return the primary
  snapshot; drop createDisabledChannelWorkerSupervisor (unused under
  the group model); wire both getChannelWorkerSnapshots and
  reloadChannelWorker into the server deps.
- server.ts: keep both getChannelWorkerSnapshots (multi-workspace
  listing) and reloadChannelWorker (per-route reload capability) on
  the deps interface.

Co-authored-by: Qwen-Coder <[email protected]>
@qwen-code-dev-bot

Copy link
Copy Markdown
Collaborator

Qwen Code resolved the merge conflicts and pushed the branch update.

Merge Conflict Resolution Summary — PR #6635

Branches

  • PR branch: feat/daemon-multi-workspace-phase4b-channel-workers
  • Base branch: main (merged origin/main into PR branch)

Conflicted Files

1. packages/cli/src/serve/run-qwen-serve.ts (3 conflict regions)

Conflict A — createDisabledChannelWorkerSupervisor factory (~line 582):

  • HEAD (PR): Empty — no such function.
  • origin/main: Added a createDisabledChannelWorkerSupervisor() stub for the single-supervisor model.
  • Resolution: Dropped origin/main's addition. The PR's ChannelWorkerGroup model uses channelWorkerGroup?.primarySnapshot() ?? { enabled: false, state: 'disabled', channels: [] } instead, making the factory unnecessary.

Conflict B — Variable declarations and writeChannelWorkerPidfile (~line 2125):

  • HEAD (PR): Declared channelWorkerGroup: ChannelWorkerGroup | undefined, getChannelWorkerSnapshot, getChannelWorkerSnapshots, isLiveWorker, and a parameterless writeChannelWorkerPidfile.
  • origin/main: Declared single channelWorker: ChannelWorkerSupervisor, getChannelWorkerSnapshot, reloadChannelWorker, and a parameterized writeChannelWorkerPidfile.
  • Resolution: Kept HEAD's multi-workspace declarations. Added reloadChannelWorker adapted for the group model — it stops and restarts the group, then returns the primary snapshot:
    const reloadChannelWorker = async (): Promise<ChannelWorkerSnapshot> => {
      if (!channelWorkerGroup) {
        return { enabled: false, state: 'disabled' as const, channels: [] };
      }
      await channelWorkerGroup.stop();
      await channelWorkerGroup.start();
      return channelWorkerGroup.primarySnapshot();
    };

Conflict C — Server deps wiring (~line 3244):

  • HEAD (PR): Passed getChannelWorkerSnapshots.
  • origin/main: Conditionally spread reloadChannelWorker.
  • Resolution: Kept both — getChannelWorkerSnapshots for multi-workspace listing

@wenshao wenshao left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Superseded by review 4668658395 — this one was submitted with a malformed body (the review payload was posted as the body text, and its inline comments were never attached).

wenshao added a commit to wenshao/qwen-code that referenced this pull request Jul 10, 2026
The severity definitions lived once, in Step 6 — after every severity had
already been assigned. Step 3's finding format asked each agent for
`Severity: Critical | Suggestion | Nice to have` and never said what the words
meant. The agents that fill that field are separate subagents with separate
priors and no shared definition between them, so each fell back on its own, and
the priors disagree.

Observed on a live review of PR QwenLM#6635 — a run of the skill as it stands on main,
whose Step 3 and Step 6 text this branch inherits unchanged. One review,
CHANGES_REQUESTED, ten inline comments. Six were Critical, and four of those six
were coverage gaps: "zero test coverage", "no references to `workers`", "no test
exercises this". Two Suggestions in the same review were the identical class.
The verdict is computed from Criticals alone, so that PR was blocked partly on
the strength of findings its own reviewer had, elsewhere, called suggestions.
The two genuine Criticals — a fail-fast that no longer fires before the daemon
reports healthy, and a startup failure path that never closes the HTTP server —
would have blocked it on their own.

The definitions now sit in the finding format that every agent is handed, they
are listed among the things every agent prompt must carry, and Step 6 points
back at them rather than restating them. A missing test is a Suggestion: "this
file has zero references to X" is a coverage statistic, not a defect. Two shapes
stay Critical because something is genuinely wrong — a test asserting the
opposite of the intended behaviour, and a test weakened or deleted in the diff
so new behaviour passes. If a missing test would let a specific incorrect
behaviour ship, report that behaviour and cite the gap as evidence.
@doudouOUC doudouOUC self-assigned this Jul 10, 2026
@wenshao
wenshao dismissed their stale review July 10, 2026 12:57

Duplicate of 4668658395; malformed body, no inline comments attached.

@wenshao

wenshao commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /resolve

…ebhook routes

Merge origin/main into feat/daemon-multi-workspace-phase4b-channel-workers.

Conflicts in run-qwen-serve.ts and server.ts arose from main adding
channel webhook routes (enqueueChannelWebhookTask, rate limiter
repositioning, deferred webhook auth) while the PR replaced the inline
channel worker startup with workspace-grouped supervisors
(startChannelWorkerGroup / ChannelWorkerGroup).

Resolution:
- Combined imports from both sides (ServiceInfoWorker, findCliEntryPath,
  sanitizeLogText, ChannelWorkerSupervisor, ChannelWorkerGroupSnapshot)
- Merged ChannelWorkerRuntime interface and loader to include both
  loadChannelsConfig (PR) and findCliEntryPath (main)
- Kept createDisabledChannelWorkerSupervisor from main
- Kept PR's deferred channel worker startup via startChannelWorkerGroup;
  main's inline startup block is superseded
- Added getChannelWorkerSnapshots to createServeApp deps (PR)
- Added enqueueChannelWebhookTask field to ServeAppDeps (main); wiring
  from run-qwen-serve.ts deferred until ChannelWorkerGroup exposes
  enqueueWebhookTask
@qwen-code-dev-bot

Copy link
Copy Markdown
Collaborator

Qwen Code resolved the merge conflicts and pushed the branch update.

Merge conflict resolution summary — PR #6635

Conflicted files

  1. packages/cli/src/serve/run-qwen-serve.ts (6 conflicts)
  2. packages/cli/src/serve/server.ts (2 conflicts)

Root cause

The PR branch (feat/daemon-multi-workspace-phase4b-channel-workers) replaced the inline single-workspace channel worker startup with a deferred, workspace-grouped approach (startChannelWorkerGroup / ChannelWorkerGroup). Meanwhile, main added channel webhook routes (enqueueChannelWebhookTask, deferred webhook auth, rate limiter repositioning, createDisabledChannelWorkerSupervisor). The two feature sets touched the same files and regions.

Resolution per conflict

run-qwen-serve.ts

# Region HEAD (PR) main Resolution
1 Imports (~L123) ServiceInfoWorker, findCliEntryPath sanitizeLogText Combined all three imports
2 ChannelWorkerRuntime interface (~L570) loadChannelsConfig findCliEntryPath() Both fields — the PR uses loadChannelsConfig for multi-workspace grouping; main uses findCliEntryPath for CLI path resolution
3 loadChannelWorkerRuntime loader (~L582) Dynamic import of runtime.js Dynamic import of cli-entry-path.js Both imports; destructured 4-tuple [supervisor, pidfile, channelRuntime, cliEntryPath]
4 createDisabledChannelWorkerSupervisor (~L605) (absent) Full function Kept main's addition — used by tests
5 createServeApp deps (~L3389) getChannelWorkerSnapshots enqueueChannelWebhookTask: (task) => channelWorker.enqueueWebhookTask(task) Kept getChannelWorkerSnapshots (PR). Did not wire enqueueChannelWebhookTask — channelWorker (main's single supervisor variable) doesn't exist in the PR; it was replaced by channelWorkerGroup which doesn't yet expose enqueueWebhookTask. The field remains declared in ServeAppDeps (optional), so webhook routes won't be registered until `ChannelWorkerGr

@wenshao wenshao left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed — no blockers. Suggestions are inline.

— qwen3.7-max via Qwen Code /review

Comment thread docs/users/qwen-serve.md Resolved
pull Bot pushed a commit to mcx/qwen-code that referenced this pull request Jul 10, 2026
…QwenLM#6612)

* feat(review): give every line of a large diff an accountable reviewer

Review agents were handed the diff *command* and left to run it themselves.
Shell tool output is capped at 30 000 characters and split head-1/5 / tail-4/5,
so on a large changeset every agent received a few hundred lines off the top of
the first file, the tail of the last file, and a truncation marker in place of
everything between. Measured on a 211 000-character diff: 14.4% of the
changeset, the same 14.4% for all ten agents. Nineteen of the twenty defects
maintainers eventually confirmed on that PR lay in the hidden 85.6%. The
ten-way dimension fan-out multiplied redundant reads of the visible sliver
rather than adding coverage, and each review round sampled a different subset
of the bugs depending on which files an agent happened to open on its own.

The diff is now captured to a file and partitioned. `read_file` still caps a
single read at ~25 000 characters, so writing the diff out is necessary but not
sufficient — a whole-file read of that diff returns its first 611 lines. Chunks
are therefore bounded by both a line budget (attention) and a character budget
(what one un-truncated read returns), split on hunk boundaries, and never
through the middle of a function. They tile the diff exactly, which is what
makes the new coverage receipts checkable: past 500 diff lines each chunk gets
one agent that owns it and must account for it, and a chunk with no receipt is
re-reviewed before the run proceeds. "No blockers" can no longer be reported
over code nobody read.

Coverage alone did not close the gap. Chunk agents held every state-machine
defect in that PR inside their assigned territory and reported none of them:
the bugs were not inside any hunk but between new lines sitting two thousand
lines apart, and what the agents lacked was not the lines but the question. A
heavily rewritten file now also gets three whole-file agents that walk a fixed
invariant checklist — mutable fields cleared on every exit path, timers
cancelled on every close without discarding captured data, map inserts matched
by deletes, retry counters incremented at every entry, status returns actually
checked, error codes classified permanent versus transient, config honoured on
every path, early returns that skip a required side effect. The checklist is
split three ways deliberately: one agent asked to run all eight checks over a
2 400-line file runs one of them properly.

Verification is sharded at eight findings per agent, because one verifier
re-reading code for sixty findings degrades on the tail of its list. A verifier
may now downgrade a Critical but never delete one — a rejected Critical is
invisible to every later stage, a downgraded one still reaches a human. The
reverse audit fans out per chunk instead of asking a single context-starved
agent to re-read the whole diff, no longer skips verification, and stops after
two consecutive dry rounds rather than one: on the PR that motivated this, the
review reported "no blockers" twice and the next round surfaced five Criticals,
three of them in code present since the first commit.

* fix(review): keep small-diff reads inside the read_file cap

Step 3A told every agent to read the whole diff in one call. `read_file`
truncates a single call at ~25 000 characters, so a 500-line diff of long lines
would come back short — the same blind spot the chunk plan removes, reintroduced
at a smaller scale. Across the last 39 merged PRs that take the Step 3A path the
largest diff is 23 570 characters, so this never fired in practice, but the
margin is six percent. Step 3A now walks the chunk ranges, which are sized to
fit one un-truncated read: one or two calls at this size.

Derive a file's pre-change line count from the diff instead of measuring it with
a second `git show` per file. `git show <base>:<newpath>` returns nothing for a
renamed file, reporting zero pre-change lines and classifying a wholesale
rewrite as light. The identity holds exactly for creations, deletions, renames
and ordinary edits, and halves the process spawns.

* fix(review): choose the topology from source lines, not diff lines

Diff size is a bad proxy for review risk because test code dominates it. Across
this repo's last 40 merged PRs the median diff is 41% test code and 14 of the 40
are more than half tests; PR QwenLM#6457, which motivated the territory fan-out, is
itself 58% tests. Gating on raw diff lines therefore carved small production
changes into territories: a change of 173 source lines shipping 489 lines of new
tests went to the chunked topology, where its production code ended up owned by
a single agent, when the dimension fan-out would have read it through eight
lenses. Territory fan-out is worth it when there is a lot of risky code to
divide, not a lot of lines.

The gate is now `srcDiffLines > 500`, with `diffLines > 2400` as a second clause
— a delivery bound rather than a risk one, since past that point chunking uses
fewer agents than the ten-lens topology anyway and reading a diff that large
dilutes all ten. On the 40-PR sample six PRs move back to the dimension fan-out,
for about 5% more agents in total across the sample.

Paths are classified as source, test, or generated, and the per-kind line counts
ship in the fetch report. Chunking is unchanged: the plan still tiles every
line, tests and generated files included. What the gate decides is how many
reviewers there are and what each is asked to do. Heaviness is likewise
restricted to source files — the invariant checklist asks about fields, timers,
collections, and error taxonomies, and a rewritten test file has none of those.

* fix(review): decode C-quoted diff paths as bytes

`git diff` C-quotes any path with a control character or a non-ASCII byte, so a
file named `sub/中文文件.ts` arrives as `"b/sub/\344\270\255..."`. The chunk
planner stripped the backslashes, turning it into `sub/344270255...ts` — a name
that exists nowhere. Every downstream use of the path then failed silently: the
line count came back zero, the file could never be classified as heavy, and the
chunk agent was told it was reviewing a file that does not exist. Reuse core's
`unquoteCStylePath`, which reassembles the octal escapes as UTF-8 bytes, rather
than keeping a second, wrong decoder here.

Coverage was never affected — line ranges stayed correct — but this repo has
non-ASCII paths, so the mislabelling was reachable.

Also correct two places that claimed hunks are never split. They are: a hunk
larger than the chunk target is split at a top-level declaration, because a
brand-new file arrives as one enormous hunk and treating it as atomic would hand
a single agent a 50 000-character territory.

* fix(review): make diff capture and header parsing robust to git config

Four defects, all found in review of this branch.

Diff capture obeyed whatever the user's git config said. With `color.diff=always`
every `diff --git` line arrives wrapped in ANSI escapes, the parser recognises
none of them, and the plan comes back with zero files and zero chunks — the
coverage guarantee silently evaluates to nothing. `diff.mnemonicPrefix` renames
the `a/`/`b/` prefixes to `i/`/`w/` and every path is then wrong; `diff.external`
and textconv filters emit output that is not a unified diff at all. Capture now
pins `--no-ext-diff --no-textconv --no-color --unified=3` and the two prefixes.

The `diff --git` header was split with a greedy regex. Git separates the two
paths with a space and does not quote a path merely for containing one, so
`a/img with space.png b/img with space.png` split into `space.png`. Usually the
`---`/`+++` headers disambiguate, but a binary or mode-only section has neither.
For a non-rename both paths are the same string, so the split point is
arithmetic; a rename states its new path outright in `rename to`.

A chunk boundary could land on a `-` line. Those exist only on the old side, so
the "starts at a top-level declaration" guarantee did not hold for the
post-change file an invariant agent later reads. Split points are now restricted
to lines present on the new side.

An `oversized` chunk — one hunk with no safe interior boundary — can exceed what
a single `read_file` returns. Chunks now carry their character count, and a
chunk agent is told to page when a read reports truncation. A `Covered:` receipt
for a range the agent only half read is worse than no receipt at all.

* fix(review): split past a distant boundary, and stop probing GitHub for anchors

Both defects surfaced running the new review against PR QwenLM#6591.

A 1431-line React component was emitted as a single 45 675-character chunk —
nearly twice what one `read_file` returns — because the splitter looked for a
safe boundary only inside the 400-line budget window, found none, and gave up on
the entire remainder. Twenty-seven boundaries existed further along; the first
sat 460 lines in. It now reaches past the window for the next one, so a single
distant boundary can no longer collapse a whole file into one chunk. That PR
goes from 15 chunks with one over the read cap to 18 with none.

Step 7 validated comment anchors by trial. GitHub rejects an entire review with
a 422 if any comment's line falls outside every hunk of its file, and the skill
offered no cheap way to check, so a run against a real PR submitted five
throwaway reviews carrying the bodies `Test`, `Test`, `t`, `t`, `t` to discover
which anchors would stick. Those are permanent, public reviews on someone else's
pull request. The fetch report now carries each file's hunks as new-side line
ranges, which turns the check into a lookup, and the skill states plainly that
a review is never submitted to test an anchor.

* fix(review): stop reading hunk payload as metadata, and harden the plan

Eleven defects from review of this branch. The worst two were silent.

A unified diff emits a removed line whose content starts with `-- ` as
`--- ...`, and an added line whose content starts with `++ ` as `+++ ...`. SQL,
Lua and Haskell comments start with `-- `. The parser read those payload lines
as file headers: the path was overwritten by the line's text, and the line
vanished from the add/remove counts. A two-file diff — one SQL file losing a
comment, one text file gaining a `++ ` line — came back with the second file
named `plus line`. Metadata is now only recognised before a file's first hunk.

The tiling invariant — every diff line belongs to exactly one chunk, which is
what makes a missing coverage receipt mean something — was asserted only in
tests. `buildDiffPlan` now checks it and refuses to return a plan with a hole.

The rest: a split point could take a *deleted* blank line as evidence of the
blank line before a declaration, though that blank exists only in the old file;
whole-file invariant agents were pointed at `chunks[].files[]`, which merges
hunks at lines 10 and 900 into one `10-902` span and would have had them report
pre-existing defects as new; pure-deletion hunks were exported as the inclusive
range `[N, N]`, so a right-side comment could be anchored where GitHub has no
line and the 422 would sink the whole review; a deleted file could be marked
heavy and send three agents to read a post-image that does not exist; a chunk
holding a single line longer than one `read_file` can never be fully read by
paging, and must now report itself uncoverable rather than receipt a lie;
capture did not pin rename detection or `--no-relative`; `gitRaw` had no
timeout, so a credential prompt on headless CI would hang forever; a failed
base fetch was swallowed, leaving a stale merge-base and a structurally
complete report describing the wrong diff; and local reviews still captured
with a bare `git diff`, which `color.diff=always` alone renders unparseable.

Adds an integration test that drives the real capture against a real repository
under hostile git config, covering the paths synthetic fixtures cannot: renames
and binaries and mode-only changes with spaces in their names, C-quoted
non-ASCII names, and payload lines that impersonate headers.

* fix(review): pin submodule output, and separate written lines from hunk spans

Four defects from review of this branch.

Diff capture left submodules to user config. `diff.ignoreSubmodules=all` hides a
changed gitlink completely — a silent coverage hole in the file that is now the
review's source of truth — and `diff.submodule=log` replaces the whole
`diff --git` section with prose no parser can read. Both are pinned now, and the
integration test asserts a bumped gitlink survives them.

Whole-file invariant agents were handed `files[].hunks[]` as "the changed
lines". A hunk spans the three context lines git prints either side of every
change: on PR QwenLM#6457's `QQChannel.ts` those spans cover 1 962 new-side lines of
which only 1 403 were written. The agent would have reported defects in 559
lines that predate the PR. The report now also carries `addedRanges[]` — the
exact lines the change wrote — and the skill gates invariant agents on those,
keeping `hunks[]` for the one thing it is right for, GitHub anchor validation.

`Uncoverable:` was introduced as a chunk agent's answer for a chunk holding a
line longer than one read, but the receipt accounting still demanded a
`Covered:` line from every chunk and relaunched any chunk lacking one — so an
uncoverable chunk would have been retried forever. It is now a first-class
terminal status: accepted by the accounting, carried into Step 6 under "Not
reviewed", and it blocks an Approve verdict. Step 3A, which also walks the
chunk plan, is covered by the same rule.

The integration test built its fixture repository inside the developer's git
environment, so a global `core.hooksPath` or `commit.gpgsign` ran during the
test and `~/.gitconfig` decided what the "clean" baseline was. It now disables
system and global config, hooks and signing, and sets the executable bit through
the index rather than shelling out to `chmod`, which does nothing on Windows.

* feat(review): plan any captured diff, and stop the report outgrowing one read

Seven items from review of this branch. None blocking; two of them were the
skill promising a topology it could not deliver.

Step 3B's chunk agents are "one per entry in `chunks[]`", and only `fetch-pr`
produced a chunk plan. A local-diff review, and a cross-repo review in
lightweight mode, therefore routed into the territory fan-out with no chunk
list, no receipts and no tiling guarantee. `qwen review plan-diff <diff-file>`
now emits the same plan from any captured diff; redirecting `git diff` or
`gh pr diff` to a file already sidesteps the shell's character cap, so all four
review paths share one mechanism. A bare diff has no tree to read a post-image
from, so it gets chunk agents but no invariant agents, and says so by omission.

The fetch report is read with the same `read_file` that truncates at 25 000
characters — and for a seven-file PR it was already 28 056. The tail of
`chunks[]` was being silently lost: the coverage hole this design closes,
reappearing one level up. `addedRanges[]` now ships only on `heavy` files, its
only consumer, which brings that report to 24 992; the skill says to page the
read; and the command prints a note when the report exceeds one read. It stays
pretty-printed on purpose — a compact one-line JSON cannot be paged by line.

The tiling assertion threw inside `fetch-pr` after the worktree existed and
before any report was written, so an unforeseen diff shape killed the review
outright. It now degrades to the documented diff-less report with a loud
warning, keeping both the loudness and the review.

`gitOpt` and `git` had no timeout, and `resolveMergeBase` uses `gitOpt` for a
network fetch — the exact path whose credential prompt the `gitRaw` timeout was
added to survive. All three wrappers now share a deadline and
`GIT_TERMINAL_PROMPT=0`.

Markdown under `docs/` or at the repository root classifies as `docs` and stays
out of `srcDiffLines`, so a translation PR does not trip the territory gate.
Markdown inside a source tree stays `source` — the bundled skill prompts are
behaviour, not prose.

Also: the user docs stated the gate without its `diffLines > 2400` clause, and
`READ_FILE_CHAR_CAP` was exported but never used. It now backs the report-size
warning.

* test(review): unit-test the merge-base and plan-report seams

The last open review thread asked for `resolveMergeBase`, `fileMetrics` and
`gitRaw` to be testable with git mocked out. Three of the four functions it
named have since moved: `classifyHeavy` is a pure function with unit tests,
`fileMetrics` became `buildPlanReport`, which already takes an injected
post-image resolver, and `gitRaw`'s output path is exercised by the real-git
integration test. `resolveMergeBase` was still private and untested.

It now lives behind a three-method `GitProbe` — fetch, refExists, mergeBase —
that `fetch-pr` fills from the real wrappers. Seven tests cover the branches
that matter and that no end-to-end run reaches: the tracking ref preferred over
the local branch, the fall-through when the tracking ref shares no history, and
above all the dangerous one — a failed fetch that still resolves a merge-base
from a stale local ref, which produces a structurally complete report describing
a diff nobody wrote.

`buildPlanReport` gains seven of its own: the injected resolver is asked once
per file and never for a binary, a null resolver means "no tree, decide nothing"
rather than a guess, `addedRanges` ship only where an invariant agent will read
them, and a pure-deletion hunk never reaches the anchorable ranges.

* fix(review): see deletions, survive suppressBlankEmpty, and stop approving unread code

Seven findings from review of the merged head. Three of them were the design
contradicting itself.

`diff.suppressBlankEmpty` prints a blank context line as a physically empty
record rather than a lone space, and there is no command-line flag to override
it — only `-c`. The parser advanced its new-side cursor for space-prefixed
context alone, so every `addedRanges` entry after the first blank line shifted
up by one, and the split-point heuristic stopped recognising blank lines. The
capture now pins the config, and the parser treats an empty hunk-body record as
context regardless, because a diff from `gh pr diff` or a hand-captured file
never passes through that pin.

A whole-file invariant agent was given the post-change file and the ranges the
PR wrote. A deletion appears in neither. Removing a `clearTimeout()`, a
`Map.delete()`, or a retry-counter increment is exactly what the checklist
hunts, and the text it was handed cannot show a line that is no longer there —
telling it to "cite the surrounding hunk" pointed at data it never received.
Heavy files now carry a `diffRange` into the report, and the agent reads its own
slice of the diff, where the `-` lines are.

The receipt accounting demanded exactly one per chunk and said it applied to
Step 3A, where nine dimension agents each walk every chunk: literal execution
yields nine receipts or none. Territory ownership is a Step 3B idea. What both
paths share is the uncoverable rule, and that needs no agent — a chunk is
uncoverable iff its `maxLineChars` exceeds the read cap, which the orchestrator
reads out of the plan before launching anything.

That rule was also never threaded into Step 7, so a green PR with an unread
chunk could receive a public LGTM. Any uncoverable chunk now downgrades APPROVE
to COMMENT and must be named in the body.

Also: the capture recipes redirected into `.qwen/tmp` before anything created
it; a file-path review of an unchanged file produced an empty plan that no agent
could read, and the skill now branches to a full-file read instead; and the docs
classifier called `website/src/App.tsx` prose while calling
`packages/cua-driver/docs/*.md` source — it now matches prose extensions under a
documentation directory at any depth.

* fix(review): tell agents what a severity means before asking for one

The severity definitions lived once, in Step 6 — after every severity had
already been assigned. Step 3's finding format asked each agent for
`Severity: Critical | Suggestion | Nice to have` and never said what the words
meant. The agents that fill that field are separate subagents with separate
priors and no shared definition between them, so each fell back on its own, and
the priors disagree.

Observed on a live review of PR QwenLM#6635 — a run of the skill as it stands on main,
whose Step 3 and Step 6 text this branch inherits unchanged. One review,
CHANGES_REQUESTED, ten inline comments. Six were Critical, and four of those six
were coverage gaps: "zero test coverage", "no references to `workers`", "no test
exercises this". Two Suggestions in the same review were the identical class.
The verdict is computed from Criticals alone, so that PR was blocked partly on
the strength of findings its own reviewer had, elsewhere, called suggestions.
The two genuine Criticals — a fail-fast that no longer fires before the daemon
reports healthy, and a startup failure path that never closes the HTTP server —
would have blocked it on their own.

The definitions now sit in the finding format that every agent is handed, they
are listed among the things every agent prompt must carry, and Step 6 points
back at them rather than restating them. A missing test is a Suggestion: "this
file has zero references to X" is a coverage statistic, not a defect. Two shapes
stay Critical because something is genuinely wrong — a test asserting the
opposite of the intended behaviour, and a test weakened or deleted in the diff
so new behaviour passes. If a missing test would let a specific incorrect
behaviour ship, report that behaviour and cite the gap as evidence.

* fix(review): walk cross-file edges in both directions

Cross-file impact analysis only ever asked "will the existing callers break?"
Every bullet was about signature compatibility, and the budget rule told agents
in so many words to "skip unchanged-signature modifications". A field added to
an interface changes no signature and breaks no caller, so the analysis was
blind to it by construction.

The failure that exposed this, on PR QwenLM#6621: the diff added `deviceFlowRegistry?`
to WorkspaceRuntime and passed it into the dispatcher for every secondary ACP
mount, and nothing anywhere assigned it. The reviewing agent saw the
declaration, found no writer, wrote "intentionally deferred to a later
milestone", and filed a Suggestion to fix the JSDoc. The reader was AcpDispatcher
— a file the diff never touched — where `if (!this.deviceFlowRegistry)` turned
`auth/device_flow/start` into an INTERNAL_ERROR and `auth/status` into an empty
list on every non-primary workspace. Workspace-qualified ACP shipped its
authentication dead, and the review called it a documentation nit. A second
reviewer filed the same observation as Critical; the author fixed it with code
and dropped the field.

Reading cannot find this. The declaration, the pass-through, and the read sit in
three different places, and the read is outside the diff, so no agent reaches it
by paging through hunks. Only a grep for the read sites does.

So: for every field, option, or optional parameter the diff adds, grep its read
sites, including outside the diff, and ask what happens when it arrives
undefined. Severity is decided at the read site, not the declaration. And an
agent must not explain an unpopulated field with author intent it cannot
observe — "reserved for future use" is a claim about a person, not about code,
and reaching for one means filling a hole in your own field of view.

* fix(review): pin the diff base, and make the review body checkable

Three defects, all found by reading what live reviews actually posted.

The diff base. Agents were handed a diff command and left to choose a base.
`main..HEAD` and `main...HEAD` differ by one character and by the entire meaning
of the review: a two-dot diff against a main that has moved shows main's later
commits reversed, so main's fixes read as the branch's regressions. A review of
PR QwenLM#6626 approved the four files the PR actually changed, then warned the author
publicly that their branch carried "typo regressions" in a file the PR never
touched and should be rebased. main had corrected `compatability` to
`compatibility` after the fork point. The branch had done nothing. Capture now
resolves the base once and hands agents a file; they never see a ref name, and a
finding in a file outside the report's `files[]` is not a finding about this PR.

The review body. "A Suggestion never goes in body" is stated twice and was
violated anyway, because a model holding a finding it cannot anchor would rather
say it somewhere than drop it. On PR QwenLM#6631 an unanchorable Suggestion about
`session.ts:2048` — a line in no hunk — became a second paragraph of the public
review body. So the rule stops being prose: for COMMENT the body is exactly one
of three sentences plus the footer and nothing else, and you read what you are
about to send and confirm it. A Suggestion that will not anchor is deleted; it is
already in the terminal output and the Step 8 report.

The downgrade sentence. On PR QwenLM#6489 a review with three Suggestions and no
Critical announced it had been "downgraded from Approve" — telling the author the
PR would otherwise have been approved, which was false: a Suggestion-only review
is COMMENT on its own. Decide the event from the findings first, apply the
downgrade flag second, and write the sentence only if it changed the answer.

* fix(review): decide the event by counting, not by weighing

A review of PR QwenLM#6584 filed three inline Suggestions and submitted APPROVE with
an empty body. GitHub recorded it as an approval. The rule it broke has been in
Step 7 all along --- APPROVE means no Critical *and* no Suggestion --- and so has
the one about the body, which is empty only for REQUEST_CHANGES. Both were
stated twice. Both were ignored.

They are ignored because at submit time the model is reasoning about what it
wants to say, and "these are only suggestions, the PR is fine" is a sentence it
can talk itself into. Nothing in that sentence is a count.

So the event and the body become arithmetic. Count the Criticals, count the
Suggestions, read the row off a three-row table, and only then apply the
downgrade flags --- which can turn APPROVE or REQUEST_CHANGES into COMMENT and
nothing else. Then read back what you are about to send and confirm it matches
the row. A body holding text the table does not authorise is a finding that
failed to anchor; if it is a Suggestion, it gets deleted, not relocated into
public prose that no line of code answers to.

This subsumes the body-only invariant added in the previous commit, which the
same submit-time reasoning had already defeated once, on PR QwenLM#6631.

* fix(review): stop the plan report outgrowing the read it must fit in

The report tells an agent how to page everything else, so it has to be readable
in one `read_file` — about 25 000 characters. Running the real `fetch-pr`
against PR QwenLM#6457 produced 25 070.

Two constraints pull against each other. Compact JSON is a single enormous line,
and `read_file` pages at line boundaries, so a report too big for one call could
never be read at all. Indented JSON pages fine but spends four lines on
`{ "start": 812, "end": 815 }`, and a heavily rewritten file contributes hundreds
of them: `QQChannel.ts` alone carries 140 added ranges and 49 hunks.

So indent the structure and inline the leaves. Same JSON, same keys, one range
per line, still pageable — and 28% smaller. The QwenLM#6457 report goes from 25 070
bytes to 18 042, and the "page it" warning that used to fire on a seven-file PR
now stays quiet.

The earlier attempt at this trimmed `addedRanges` to heavy files only and landed
at 24 992 bytes on the same PR. Eight bytes of headroom was not a fix.

Tests pin the three properties that matter: the collapsed text parses back to an
identical object, no range spans two lines, and a path that literally spells a
range is not mistaken for one — JSON escapes the quotes inside a string value,
and the collapse patterns require unescaped ones.

* fix(review): prune the worktree registration a deleted directory leaves behind

`cleanStale` and `cleanup` both guarded `git worktree remove` behind
`existsSync(path)`, and neither ever pruned. Delete the directory by hand — which
is exactly what reclaiming disk with `rm -rf .qwen/tmp` does — and git keeps the
worktree registered but missing. From then on `/review` on that PR cannot run:

    $ git worktree add .qwen/tmp/review-pr-6457 qwen-review/pr-6457
    fatal: '...' is a missing but already registered worktree;
    use 'add -f' to override, or 'prune' or 'remove' to clear

and the branch delete that `cleanStale` does next fails too, because the phantom
worktree still has that branch checked out. Nothing in the review command surface
ran `git worktree prune`, so nothing ever cleared it.

This surfaced running the real skill: the orchestrator's first `fetch-pr` failed,
it fell back to `qwen review cleanup`, and retried. The leak is not rare — three
abandoned worktrees from May and June were still registered in this checkout,
one per review that died before Step 9.

`releaseWorktree` now does both halves in the order they depend on: remove the
directory if it is there, prune the registration unconditionally (a no-op when
nothing is stale), and only then let the caller delete the branch. Both callers
share it.

The tests drive real git. Deleting a worktree directory by hand and re-adding it
throws "missing but already registered" without the prune, and `branch -D` throws
"used by worktree" — both assertions fail if the prune is removed, which is the
point of writing them.

* fix(review): put the open comments where a truncated read will find them

`read_file` returns the first `truncateToolOutputThreshold` characters — 25 000
by default — sets `isTruncated`, and pages by line. `pr-context` wrote
"## Open inline comments (no replies yet — may still need attention)" last, so
on a PR with a long history it was the first thing lost, and nothing read the
flag that said so.

On PR QwenLM#5738 that section began at character 27 125 of a 31 220-character file.
The review submitted "Reviewed — no blockers." Five Critical threads were
unresolved; four had in fact been addressed, but the fifth — `clearCiEnv()`
clearing only `CI*` while `writeTerminalTitle` branches on `TMUX`/`STY`/
`ZELLIJ`/`DVTM` — was live, in the diff, and never seen.

Regenerating the context for ten PRs: four lost part or all of the section, and
all four were the PRs with the most review rounds. Small PRs never trip it.

- Emit the open threads before the already-discussed ones. The findings a round
  must answer outrank the ones already settled.
- `pr-context` warns when the file exceeds the threshold, naming any headings
  past the cut, and says so plainly when the loss is inside the last section's
  body instead.
- Step 2 of SKILL.md now tells the agent to read `isTruncated` and page the
  remainder before Step 3.

Reordering buys headroom; it does not create it. A 40 000-character context still
loses its tail, which is what the warning is for.

* fix(review): load this repo's review rules, and re-check open Criticals before approving

Two gaps the dogfood on live PRs surfaced, both invisible from reading the skill.

`load-rules` looks for a `## Code Review` heading in AGENTS.md and QWEN.md.
Neither had one, so it wrote an empty file on every run: every `/review` in this
repo reviewed with zero project rules. Add the section, distilled from the
conventions already scattered through AGENTS.md (ESM, no cross-package relative
imports, kebab-case/PascalCase naming, collocated tests, comments-only-when-why),
plus the two hard lessons below. The section loads from the base branch by design
— a PR cannot inject its own review rules — so it takes effect once merged.

The skill treated a zero-Critical outcome as a fallback rather than a claim. On
one PR it published two Criticals citing code not present at the reviewed commit
(a fabricated blocker on an already-approved PR); on another it submitted C=0
while a live, twice-filed Critical still stood (a dropped blocker). Add a step
before the verdict: for each unresolved Critical on the PR, read the code at the
reviewed commit and record still-stands / fixed-by-this-diff / cannot-tell. The
event follows from the code, not from the finding count or the thread flags —
`isResolved`/`isOutdated` track the anchored line, not whether the bug was fixed.

- AGENTS.md: new `## Code Review` section.
- load-rules.ts: export `extractCodeReviewSection`; load-rules.test.ts covers the
  boundary scan and asserts AGENTS.md's own section extracts non-empty, so
  deleting the heading fails the build.
- SKILL.md: re-verification step ahead of the Verdict.
@wenshao

wenshao commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@wenshao

wenshao commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

Local validation report — real-daemon E2E (maintainer review)

TL;DR — ⚠️ do not merge as-is. The static gate is green (typecheck clean, 1084/1084 touched unit tests pass), and the single-workspace path plus all three fail-fast paths behave exactly as documented. But a real multi-workspace daemon cannot start any channel worker: qwen serve with more than one --workspace plus any --channel dies on startup with exit code 1. This is a regression vs main (the same command works there) and it defeats this PR's headline feature. The unit suite misses it because it injects a fake worker supervisor, so no real worker ever calls /capabilities.

How this was validated

PR head 21a280f80 (feat/daemon-multi-workspace-phase4b-channel-workers)
Baseline main @ 25f491d3a
Env macOS (darwin 24.6), Node v22.23.1, clean npm ci
Build npm run bundle → ran the real bundled qwen serve (not vitest)
Isolation dedicated QWEN_HOME, two trusted git workspaces + one DO_NOT_TRUST
Channels real plugin-example channels → local mock WebSocket servers (no external creds), so workers genuinely reach the connected / ready state

Static gate — ✅ green

packages/cli$ npx tsc --noEmit          →  exit 0
packages/cli$ npx vitest run  (9 suites touched by the PR)
  ✓ serve/channel-workspace-grouping.test.ts   (15)
  ✓ serve/channel-worker-group.test.ts         (16)
  ✓ serve/channel-worker-supervisor.test.ts    (66)
  ✓ serve/daemon-status.test.ts                (25)
  ✓ serve/run-qwen-serve.test.ts              (162)
  ✓ serve/server.test.ts                      (671)
  ✓ commands/channel/config-utils.test.ts      (47)
  ✓ commands/channel/daemon-worker.test.ts     (54)
  ✓ commands/channel/pidfile.test.ts           (28)
  Test Files  9 passed (9)   |   Tests  1084 passed (1084)

Real-daemon E2E — scenario matrix

# Scenario Result
S1 Single-workspace regression (--workspace wsA --channel chA) ✅ PASS
S2 Multi-workspace success (--workspace wsA --workspace wsB --channel chA --channel chB) ❌ FAIL
S3 Failure: channel owned by no registered workspace ✅ PASS
S4 Failure: ambiguous global channel ✅ PASS
S5 Failure: channel in an untrusted workspace ✅ PASS
S6 --channel all on multi-workspace (primary-only) ⚠️ grouping correct, but worker fails (same bug as S2)

S1 — single-workspace is byte-identical (as promised):

// pidfile: no workers[]                       // GET /daemon/status: no channelWorkers
{ "owner":"serve", "channels":["chA"],         { "channelWorker": { "state":"running",
  "servePid":20567, "workerPid":20574 }                            "channels":["chA"], "pid":20574 } }
// daemon log: "channel worker stdout: ..."  — no workspace prefix.  [Channel] "chA" connected.

S3 / S4 / S5 — fail-fast paths all reject startup with clear errors:

S3  qwen serve: Channel "chC" is not configured in any registered workspace, or its "cwd" points outside them.
S4  qwen serve: Channel "chGlobal" is configured in multiple registered workspaces (wsA, wsB). Define it in one workspace's settings or set an explicit "cwd".
S5  qwen serve: Channel "chC" targets untrusted workspace ".../wsC".

❌ The blocker (S2 / S6): multi-workspace channel workers can't start

The grouping logic itself is correct — the live /daemon/status reports exactly the right per-workspace metadata:

"channelWorkers": [
  { "channels":["chA"], "workspaceId":"60e2e5e9…", "workspaceCwd":".../wsA", "primary":true  },
  { "channels":["chB"], "workspaceId":"cb69e0cd…", "workspaceCwd":".../wsB", "primary":false }
]

…but every worker exits before ready, and failRuntimeStartup() then closes the listener, so the whole daemon goes down:

# PR #6635  — qwen serve --workspace wsA --workspace wsB --channel chA --channel chB
channel worker [wsA] stderr: [Channel] daemon worker failed:
     GET /capabilities: Daemon runtime is still starting          ← 503
qwen serve: runtime startup failed: Channel worker exited before ready (code=1, signal=null).
$ echo $?  →  1                                                   ← whole daemon exits

# main @25f491d3a — qwen serve --workspace wsA --workspace wsB --channel chA  (same command)
route=GET /capabilities durationMs=0 status=200 request completed ← 200
channel worker stdout: [Channel] "chA" connected.                ← worker RUNNING ✅

This is a startup ordering regression, not a grouping bug — it breaks even the primary worker as soon as a second --workspace is present, so a scenario that worked on main (multi-workspace sessions + a primary channel) now fails.

Root cause — packages/cli/src/serve/run-qwen-serve.ts, completeRuntimeStartup():

flowchart TD
  R["runtime marked ready<br/>(markRuntimeReady)"] -->|"blocked by<br/>await startChannelWorkerGroup()"| W["channel worker reaches 'ready'"]
  W -->|"needs GET /capabilities → 200"| M["runtime app mounted<br/>(runtimeApp = candidateApp)"]
  M -->|"but PR assigns runtimeApp<br/>only AFTER the worker starts"| R
  B["bootstrap app<br/>multiWorkspaceCapabilitiesRequireRuntime → 503"] -.serves /capabilities while runtimeApp is unset.-> W
Loading
  • main: runtimeApp = runtime.app is assigned before await completeRuntimeStartup() → when the worker calls /capabilities, the runtime app answers 200.
  • PR feat(cli): group daemon channel workers by workspace (phase 4b) #6635: completeRuntimeStartup() runs await startChannelWorkerGroup(...) first and only then sets runtimeApp = candidateApp. While the worker starts, runtimeApp is still unset, so /capabilities is served by the 503-gated bootstrap app (multiWorkspaceCapabilitiesRequireRuntime === workspaceInputs.length > 1). The worker can never bootstrap → exits before ready → failRuntimeStartup() closes the server → the daemon exits 1.

Suggested fix: mount the runtime app (runtimeApp = candidateApp + attachServer) before await startChannelWorkerGroup(...) inside completeRuntimeStartup(), matching main's ordering — so the worker's /capabilities bootstrap call is served by the runtime app (200). Please also add a regression test that spawns a real worker under >1 --workspace (the current run-qwen-serve.test.ts injects a fake createSupervisor, which is why CI stayed green).

Recommendation

Hold the merge until the multi-workspace worker can actually start. Everything else in the PR — grouping rules, fail-fast validation, single-workspace parity, pidfile/status shapes — checks out against a live daemon.

中文版本(点击展开)

本地验证报告 —— 真实 daemon 端到端(维护者复核)

结论 —— ⚠️ 暂不建议合并。 静态门禁是绿的(typecheck 通过,改动涉及的 1084/1084 单测全绿),单工作区路径与三条快速失败路径也完全符合 PR 描述。但真实的多工作区 daemon 无法启动任何 channel worker: 只要 qwen serve 同时带 多个 --workspace 和任意 --channel,daemon 会在启动阶段以 退出码 1 崩溃。这相对 main 是回归(同样的命令在 main 上可用),并且让本 PR 的核心特性失效。单测没抓到,是因为它注入了假的 worker supervisor,真实 worker 从未真正去请求 /capabilities。

验证方式

PR head 21a280f80
基线 main @ 25f491d3a
环境 macOS,Node v22.23.1,全新 npm ci
构建 npm run bundle → 运行真实打包后的 qwen serve(不是 vitest)
隔离 独立 QWEN_HOME,两个受信 git 工作区 + 一个 DO_NOT_TRUST
Channel 真实 plugin-example channel → 本地 mock WebSocket 服务(无需外部凭据),worker 能真正达到 connected/ready

静态门禁 —— ✅ 通过

npx tsc --noEmit 退出 0;9 个受影响单测套件 1084 用例全绿(分组、worker-group、supervisor、daemon-status、run-qwen-serve、server、config-utils、daemon-worker、pidfile)。

真实 daemon 端到端 —— 场景矩阵

# 场景 结果
S1 单工作区回归 ✅ 通过(形状字节等价:pidfile 无 workers[],status 无 channelWorkers,日志无工作区前缀)
S2 多工作区成功路径(chA@wsA + chB@wsB) ❌ 失败(两个 worker 都 exited before ready)
S3 失败:channel 不属于任何已注册工作区 ✅ 通过(启动被拒)
S4 失败:全局歧义 channel ✅ 通过(启动被拒)
S5 失败:channel 属于未受信工作区 ✅ 通过(启动被拒)
S6 多工作区下 --channel all(仅 primary) ⚠️ 分组正确,但 primary worker 同样失败(与 S2 同因)

❌ 阻断项(S2/S6):多工作区 channel worker 无法启动

分组元数据本身是正确的(/daemon/status 的 channelWorkers[] 精确标注了 workspaceId/cwd/primary);但每个 worker 都在 ready 之前退出,随后 failRuntimeStartup() 关闭监听,整个 daemon 崩溃:

# PR #6635  多工作区
[Channel] daemon worker failed: GET /capabilities: Daemon runtime is still starting   ← 503
qwen serve: runtime startup failed: Channel worker exited before ready (code=1).
$ echo $?  → 1                                                                          ← 整个 daemon 退出

# main  同样命令
route=GET /capabilities ... status=200 ...   ← 200
[Channel] "chA" connected.                    ← worker 正常运行 ✅

这是启动时序回归,不是分组 bug —— 只要出现第二个 --workspace,连 primary worker 都会挂,因此在 main 上本可用的「多工作区会话 + primary channel」也一并坏掉。

根因 —— run-qwen-serve.ts 的 completeRuntimeStartup():

  • main: 先 runtimeApp = runtime.app,再 await completeRuntimeStartup() → worker 请求 /capabilities 时由运行时 app 返回 200。
  • PR: completeRuntimeStartup() 先 await startChannelWorkerGroup(...),之后才 runtimeApp = candidateApp。worker 启动时 runtimeApp 仍为空,/capabilities 落到 503 的 bootstrap app(multiWorkspaceCapabilitiesRequireRuntime === workspaceInputs.length > 1)→ worker 无法 bootstrap → exited before ready → failRuntimeStartup() 关闭 server → daemon 退出 1。

建议修复: 在 completeRuntimeStartup() 里把挂载运行时 app(runtimeApp = candidateApp + attachServer)移到 await startChannelWorkerGroup(...) 之前,与 main 时序一致;并补一个在 >1 --workspace 下 spawn 真实 worker 的回归测试(当前 run-qwen-serve.test.ts 注入的是假 createSupervisor,所以 CI 一直是绿的)。

建议

在多工作区 worker 能真正启动之前先不要合并。PR 的其余部分(分组规则、快速失败校验、单工作区一致性、pidfile/status 形状)在真实 daemon 上都验证通过。

@doudouOUC

Copy link
Copy Markdown
Collaborator Author

@wenshao The real daemon startup blocker is fixed in commit 753403599. The runtime app is now published and its ACP server attached before the sequential workspace worker group starts, while runtimeReady still resolves only after every worker is ready. Failure and overall startup-timeout paths withdraw the runtime, stop the group, remove pidfile metadata, shut down bridges, and close the listener. The timeout/stop race is also guarded so teardown cannot launch a later workspace worker or accept a late ready callback.

Verification completed:

  • 9 related CLI test files: 1085/1085 passed
  • npm run build && npm run typecheck: passed
  • npm run bundle: passed
  • bundled-CLI integration with isolated QWEN_HOME, two trusted workspaces, two real daemon-worker processes, and two local plugin-example WebSocket servers: passed; both workers connected and /daemon/status reported both as running
  • independent test-engineer E2E: VERIFIED_FIXED; both worker /capabilities probes returned 200, status was ok, daemon stayed alive, and SIGINT cleaned up daemon, workers, and listener
  • ESLint, Prettier, and git diff --check: passed
  • final concurrency/failure-path review: no remaining Critical, Important, or Minor findings

Could you please rerun the original real-daemon verification and update the CHANGES_REQUESTED review if it now passes? I will not merge before that verification/review update.

@doudouOUC
doudouOUC requested a review from wenshao July 11, 2026 03:56
@wenshao

wenshao commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@doudouOUC
doudouOUC dismissed a stale review via 3383358 July 11, 2026 04:54
@wenshao

wenshao commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

✅ Re-verification — the multi-workspace channel-worker blocker is fixed

@doudouOUC I reran the original real-daemon verification against the latest head 753403599 ("mount runtime before channel workers start"). The startup regression I flagged earlier (scenarios S2 / S6) is resolved, and the full scenario matrix now passes on a live daemon. Details below as a merge reference.

before / after

How this was verified

Not unit tests — the real bundled daemon:

  • npm run bundle → ran the actual dist/cli.js qwen serve (not vitest), rebuilt from each head under test.
  • Isolated QWEN_HOME, two trusted git workspaces + one untrusted, plugin-example channels pointed at local mock WebSocket servers (no external credentials — workers actually reach connected / running).
  • macOS, Node v22.23.1. Baseline pre-fix head 21a280f80 vs fix head 753403599, same command, same isolated env.

Before → after (the blocker)

pre-fix 21a280f80 fix 753403599
qwen serve --workspace wsA --workspace wsB --channel chA --channel chB daemon listens then crashes, exit 1 daemon alive, 2 workers running
worker GET /capabilities 503 Daemon runtime is still starting → "Channel worker exited before ready (code=1)" 200, both workers connect

Root cause was exactly the ordering in run-qwen-serve.ts › completeRuntimeStartup(): the worker's own /capabilities bootstrap was served by the 503-gated bootstrap app because runtimeApp had not been mounted yet. The fix mounts the runtime app + attachServer(server) before await startChannelWorkerGroup(...), so the bootstrap now gets 200.

Full scenario matrix — 6 / 6 pass on a live daemon

scenario matrix

# Scenario Command (abbrev.) Result
S1 Single-workspace regression --workspace wsA --channel chA ✅ legacy shape byte-identical
S2 Multi-workspace success (was the blocker) --workspace wsA --workspace wsB --channel chA --channel chB ✅ 2 workers running
S3 Channel in no registered workspace --channel does-not-exist ✅ refused, exit 1
S4 Ambiguous global channel (user scope, no cwd) --channel shared ✅ refused, exit 1
S5 Channel targets untrusted workspace --workspace wsC(untrusted) --channel chC ✅ refused, exit 1
S6 --channel all on multi-workspace --workspace wsA --workspace wsB --channel all ✅ primary-only (1 worker)

Backward-compat holds (captured from the live /daemon/status + pidfile):

  • S1 single-workspace — runtime.channelWorker present, runtime.channelWorkers absent; pidfile { owner, pid, channels:["chA"], servePid, workerPid } with no workers[]. Byte-identical to today.
  • S2 multi-workspace — additive only: runtime.channelWorkers[2] annotated with workspaceId / workspaceCwd / primary (wsA primary:true, wsB primary:false); pidfile grows workers[2] while the legacy channels (union ["chA","chB"]) and primary workerPid stay populated for old readers. runtime.channelWorker still reflects the primary.
  • S3–S5 each reject startup with a specific message (… not configured in any registered workspace / … configured in multiple registered workspaces … / … targets untrusted workspace …).
  • S6 --channel all hosts only the primary workspace's channel — the secondary never connects.

Static gates @ 753403599

  • cd packages/cli && npx tsc --noEmit → exit 0, 0 errors (the earlier TS2322 mock-typing issue is gone).
  • 9 affected unit suites → 1085 / 1085 passing (grouping · worker-group · supervisor · daemon-status · run-qwen-serve · server · config-utils · daemon-worker · pidfile).
  • The new real-worker integration test integration-tests/cli/qwen-serve-channel-workers.test.ts → 1 / 1 passing against a freshly built bundle. It spawns two real workers under >1 --workspace and asserts both reach running — this closes the gap where the old orchestration test injected a fake createSupervisor.
  • All earlier [Critical] test-coverage gaps I raised are now covered (pidfile workers[], status channelWorkers, daemon-worker trust branches, grouping no_primary_workspace, writeChannelWorkerPidfile construction).

One minor, non-blocking note

The /review suggestion to add packages/cli/src/commands/channel/channel-cwd.test.ts (direct coverage of the ~ / home-relative branch of resolveChannelCwd) is still open. resolveChannelCwd is exercised indirectly via the grouping suite and the live S1–S6 runs, so this is a nice-to-have, not a merge blocker.

Verdict

From my re-verification the blocker is cleared and the feature works end-to-end on a real multi-workspace daemon, with single-workspace behavior unchanged. Good to merge from my side. 👍

中文版本(点击展开)

✅ 复核验证 —— 多工作区 channel worker 的阻断问题已修复

@doudouOUC 我在最新 head 753403599("mount runtime before channel workers start")上重跑了原来的真实 daemon 验证。我之前提出的启动回归(场景 S2 / S6)已解决,完整场景矩阵现在在真实 daemon 上全部通过。以下作为合并参考。

验证方式

不是单元测试,而是真实打包后的 daemon:

  • npm run bundle → 运行真实的 dist/cli.js qwen serve(不是 vitest),对每个被测 head 分别重新构建。
  • 独立 QWEN_HOME,两个受信 git 工作区 + 一个未受信,plugin-example channel 指向本地 mock WebSocket 服务(无需外部凭据,worker 能真正达到 connected / running)。
  • macOS,Node v22.23.1。基线为修复前 head 21a280f80,对比修复 head 753403599,命令与隔离环境完全一致。

前 → 后(阻断项)

修复前 21a280f80 修复后 753403599
qwen serve --workspace wsA --workspace wsB --channel chA --channel chB daemon 监听后崩溃,退出码 1 daemon 存活,2 个 worker running
worker GET /capabilities 503 Daemon runtime is still starting → "Channel worker exited before ready (code=1)" 200,两个 worker 都连接成功

根因正是 run-qwen-serve.ts › completeRuntimeStartup() 的时序:worker 自身的 /capabilities bootstrap 被 503 的 bootstrap app 接管,因为此时 runtimeApp 还没挂载。修复把挂载运行时 app + attachServer(server) 移到 await startChannelWorkerGroup(...) 之前,bootstrap 现在返回 200。

完整场景矩阵 —— 真实 daemon 上 6 / 6 通过

# 场景 命令(简写) 结果
S1 单工作区回归 --workspace wsA --channel chA ✅ 旧形状字节等价
S2 多工作区成功路径 (原阻断项) --workspace wsA --workspace wsB --channel chA --channel chB ✅ 2 个 worker running
S3 channel 不属于任何已注册工作区 --channel does-not-exist ✅ 启动被拒,退出 1
S4 全局歧义 channel(user 作用域、无 cwd) --channel shared ✅ 启动被拒,退出 1
S5 channel 指向未受信工作区 --workspace wsC(未受信) --channel chC ✅ 启动被拒,退出 1
S6 多工作区下 --channel all --workspace wsA --workspace wsB --channel all ✅ 仅 primary(1 个 worker)

向后兼容成立(取自真实的 /daemon/status 与 pidfile):

  • S1 单工作区 —— runtime.channelWorker 存在,runtime.channelWorkers 不存在;pidfile { owner, pid, channels:["chA"], servePid, workerPid },无 workers[],与今天字节等价。
  • S2 多工作区 —— 纯 additive:runtime.channelWorkers[2] 带 workspaceId / workspaceCwd / primary 标注(wsA primary:true,wsB primary:false);pidfile 新增 workers[2],同时保留旧字段 channels(并集 ["chA","chB"])与 primary workerPid 以兼容旧读端;runtime.channelWorker 仍反映 primary。
  • S3–S5 均以具体错误信息拒绝启动(… not configured in any registered workspace / … configured in multiple registered workspaces … / … targets untrusted workspace …)。
  • S6 --channel all 仅托管 primary 工作区的 channel,secondary 从未连接。

静态门禁 @ 753403599

  • cd packages/cli && npx tsc --noEmit → 退出 0,0 错误(此前的 TS2322 mock 类型问题已消失)。
  • 9 个受影响单测套件 → 1085 / 1085 通过(grouping · worker-group · supervisor · daemon-status · run-qwen-serve · server · config-utils · daemon-worker · pidfile)。
  • 新增的真实 worker 集成测试 integration-tests/cli/qwen-serve-channel-workers.test.ts → 对全新构建的 bundle 1 / 1 通过。它在 >1 --workspace 下 spawn 两个真实 worker 并断言二者都达到 running,弥补了旧编排测试注入假 createSupervisor 的缺口。
  • 我之前提出的所有 [Critical] 测试覆盖缺口现均已覆盖(pidfile workers[]、status channelWorkers、daemon-worker 受信分支、grouping no_primary_workspace、writeChannelWorkerPidfile 构造)。

一处次要、非阻断说明

/review 建议新增 packages/cli/src/commands/channel/channel-cwd.test.ts(直接覆盖 resolveChannelCwd 的 ~ / home 相对路径分支)尚未落地。resolveChannelCwd 已通过 grouping 套件与真实 S1–S6 运行被间接覆盖,因此属于锦上添花,不构成合并阻断。

结论

从我的复核来看,阻断项已解除,功能在真实多工作区 daemon 上端到端可用,且单工作区行为保持不变。我这边同意合并。👍

wenshao
wenshao previously approved these changes Jul 11, 2026
@doudouOUC
doudouOUC enabled auto-merge July 11, 2026 05:09
@doudouOUC
doudouOUC requested a review from qqqys July 11, 2026 10:54
@wenshao

wenshao commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

1 similar comment
@wenshao

wenshao commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@doudouOUC
doudouOUC added this pull request to the merge queue Jul 11, 2026
Merged via the queue into QwenLM:main with commit 230db17 Jul 11, 2026
172 of 174 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants