Kaynağa Gözat

fix(agent-presets): make a preset's failures legible where they happen

Discovery proved only that a composition parsed, so a preset naming a
package a later rename took away kept a healthy card and its place in
every picker until a person switched to it. It now resolves each row it
can prove will start, reading the package off disk and falling back to
the resolver only for names that look absent — the resolver costs a
synchronous hooks-thread round-trip under the source launch's tsx hook,
which the walk avoids for every row it clears.

The mount diagnostic followed `AggregateError.errors` but never a cause,
so a group that failed on two rows named neither. It now follows a cause
that carries more than its own message.

A refused switch left the chip's label snapping back with no account of
why, which is the only account there can be for a preset that resolves
and then refuses. It announces through the shared Toast, which gained a
caller-set hold for a cause that names packages and rows.
Yichen Jiang 1 ay önce
ebeveyn
işleme
f7890f591a
39 değiştirilmiş dosya ile 1041 ekleme ve 145 silme
  1. 6 0
      .agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.i18n.yaml
  2. 73 0
      .agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.md
  3. 73 0
      .agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.zh.md
  4. 45 4
      apps/web/tests/agent-preset-selection.e2e.ts
  5. 1 0
      apps/web/tests/expected/agent-preset-selection/menu.expected.md
  6. 2 2
      packages/client/ui-agent-preset/README.i18n.yaml
  7. 2 2
      packages/client/ui-agent-preset/README.md
  8. 2 2
      packages/client/ui-agent-preset/README.zh.md
  9. 94 43
      packages/client/ui-agent-preset/src/client/AgentPresetSeat.tsx
  10. 46 4
      packages/client/ui-agent-preset/src/client/AgentPresetSection.module.css
  11. 20 3
      packages/client/ui-agent-preset/src/client/AgentPresetSection.tsx
  12. 3 1
      packages/client/ui-agent-preset/src/client/locales.ts
  13. 16 4
      packages/client/ui-agent-preset/src/client/seat-store.ts
  14. 24 0
      packages/client/ui-agent-preset/tests/apply.client.spec.ts
  15. 53 7
      packages/client/ui-agent-preset/tests/components.client.spec.tsx
  16. 13 3
      packages/client/ui-agent-preset/tests/section.client.spec.tsx
  17. 2 2
      packages/client/ui-primitives/README.i18n.yaml
  18. 1 1
      packages/client/ui-primitives/README.md
  19. 1 1
      packages/client/ui-primitives/README.zh.md
  20. 6 4
      packages/client/ui-primitives/src/Toast.module.css
  21. 21 7
      packages/client/ui-primitives/src/Toast.tsx
  22. 18 0
      packages/client/ui-primitives/tests/toast.client.spec.tsx
  23. 2 2
      packages/preset/agent-presets/README.i18n.yaml
  24. 2 2
      packages/preset/agent-presets/README.md
  25. 2 2
      packages/preset/agent-presets/README.zh.md
  26. 1 0
      packages/preset/agent-presets/package.json
  27. 174 8
      packages/preset/agent-presets/src/discovery.ts
  28. 25 1
      packages/preset/agent-presets/src/index.ts
  29. 37 9
      packages/preset/agent-presets/src/mount.ts
  30. 45 0
      packages/preset/agent-presets/src/specifier.ts
  31. 6 1
      packages/preset/agent-presets/tests/authoring.spec.ts
  32. 142 19
      packages/preset/agent-presets/tests/discovery.spec.ts
  33. 9 0
      packages/preset/agent-presets/tests/fixtures/plugins/throws.js
  34. 4 2
      packages/preset/agent-presets/tests/fixtures/user/broken/agent.cordis.yml
  35. 16 0
      packages/preset/agent-presets/tests/fixtures/user/nested-broken/agent.cordis.yml
  36. 9 5
      packages/preset/agent-presets/tests/fixtures/user/two-broken/agent.cordis.yml
  37. 35 3
      packages/preset/agent-presets/tests/mount.spec.ts
  38. 7 1
      packages/preset/agent-presets/tests/shipped-root.spec.ts
  39. 3 0
      pnpm-lock.yaml

+ 6 - 0
.agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.md
+2026-08-26-preset-health-resolves-rows.md: 1615b2b86bee27a282357e1d5f023797672cb9b5
+2026-08-26-preset-health-resolves-rows.zh.md: ea287ae8204aa1730d80199b0f4e86e3cf7b42a3

+ 73 - 0
.agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.md

@@ -0,0 +1,73 @@
+# Agent Note: Preset health resolves the rows it can prove will start
+
+Status: implemented
+
+English | [中文](2026-08-26-preset-health-resolves-rows.zh.md)
+
+## Problem
+
+A preset the roster listed as healthy could still be impossible to compose. Discovery's health check proved the composition parsed in the loader dialect and held named rows, and deliberately stopped there — it resolved no plugin name and applied no config.
+
+`broken` is load-bearing, though, not a card decoration. `presetOptions` drops a broken row from the session pickers so a chooser never defers the discovery to a failed session start, and `resolveMountable` refuses one before spending a mount. Everything downstream therefore reads "not broken" as "will compose".
+
+The gap surfaced when the [repository naming contract](2026-08-11-repository-naming-contract-and-rename-ledger.md) renamed packages under the pre-release stance. In-repo references moved with it; a preset authored under `<dshHome>/.agent-presets` did not, and one naming `@deepseek-ai/dsh-workspace-context` kept its healthy card, kept its place in the picker, and failed only when a person switched to it. A row naming a package a later release renamed or uninstalled is how an authored preset actually rots, and it was exactly the class the check excluded.
+
+The failure it did produce named less than it knew. The Loader's per-row wrapper builds a plain `Error` whose message ends with `cause.message` and keeps the cause only as `error.cause`. A group that fails on two rows therefore arrives as one wrapped row whose message is `failed to apply loader entry <group> (cordis:group): loader entries failed to apply`, with the two real reasons reachable through `cause.errors` alone. The mount diagnostic flattened `AggregateError.errors` and never followed `cause`, so it ended at that line and named neither row.
+
+## Decision
+
+**Discovery resolves each row it can prove will start, and imports nothing.** The resolve pass runs after the shape check in `packages/preset/agent-presets/src/discovery.ts`, so a malformed composition still answers with the shape reason. A package name is looked up on disk — Node's own upward `node_modules` walk, stopping at `<package>/package.json` — and only a name that finds nothing there is confirmed through `import.meta.resolve`, whose refusals are then remembered for the process. A preset-relative or absolute specifier is statted instead, because `import.meta.resolve` only joins URLs for those and a preset shipping a file that was deleted would otherwise pass. Nothing is evaluated either way.
+
+The disk lookup is the fast path because the resolver is not one: a registered ESM loader hook turns every `import.meta.resolve` call into a synchronous round-trip to the hooks thread. Under the `tsx` hook the source launch installs, that measured 2ms for a hit and 5ms for a miss against 0.055ms and 0.032ms on bare Node, which put 238ms of resolver time into each roster read. The walk answers the same 135 rows in 0.7ms. Keeping the resolver for names the walk cannot find leaves a read paying for the failures it reports rather than for every row it clears, and keeps a package only a loader can resolve — through tsconfig paths, or an import map — from being called broken. A Node builtin short-circuits ahead of both.
+
+The refusal memo sits behind the walk, never in front of it, so a package installed since is found on disk and a recorded refusal cannot go stale in the direction that matters.
+
+**One classifier decides where a row resolves.** `src/specifier.ts` owns the split — `cordis:` builtin, preset-relative, absolute file, package name — and both the mount's import override and discovery's check read it. A row discovery resolved from one base while the mount imported it from another would be reported healthy and then fail to load.
+
+**A row that may never start is skipped.** `disabled` is the one entry field the [Loader interpolates](2026-08-11-loader-entry-disabled-interpolation.md): a `!!js` expression evaluates against the loader context at mount time, which discovery cannot do from a file. A row carrying anything but an absent, null, or `false` value is left unchecked, and a disabled group takes its children with it. Every shipped preset gates its shell rows this way, so this is the common shape, not a corner.
+
+**The harness base is a required argument.** `discoverPresets(roots, harnessBase)` and `scanRoot(root, harnessBase)` take it; `AgentPresets` reads `ctx.baseUrl` once in its constructor and throws when it is absent. The base is what makes the question answerable at all — the same package name fails from a preset's own directory and resolves from the installed harness — so an optional one would silently restore the state this check exists to end.
+
+**The mount diagnostic follows a cause that carries more than its message.** `mountDetail` reads branches from `AggregateError.errors`, or from `error.cause.errors` when the cause is an `AggregateError`; a plain cause chain is already flattened into the message and is not followed, which would print every line twice. Nested branches indent under the row that owns them.
+
+**The client puts the reason on the badge.** The card face keeps the preset's own description, because a package specifier tells a chooser nothing they can act on there. The host's reason is the badge's tooltip for a pointer, and a visually hidden `role="alert"` node carries it to assistive technology — the card body is disabled when a preset is broken, so it leaves the tab order and the tooltip has no keyboard path.
+
+**A refused switch says why, where it was refused.** The chip's own label reverts to the preset the session still runs, so without a word the pick simply appears not to have happened. It announces through the shared `Toast`, over the composer column, the way the model picker beside it already reports a rejected selection. Only a pick a person just made is announced — the applier also runs when a session becomes current, and a banner over that would report a refusal nobody asked for. The banner holds for eight seconds rather than the primitive's three, because it carries a cause that names packages and rows; `Toast` gained a `holdMs` for that, which also retired the hazard of a hold constant the stylesheet had to be kept in step with by hand.
+
+The wire already separated the two texts this needs: `message` wraps the cause in the roster's own "preset X failed to mount" frame, while `details.reason` holds the cause alone. A surface that names the preset itself takes the second, or it says the preset twice.
+
+## Alternatives considered
+
+**Check when a preset is selected rather than when the roster is listed.** Rejected. The pickers filter on `broken` before anyone selects, so a preset only checked at selection is still offered, and the reported failure still arrives after the click — the original complaint, relocated. The roster row is where every consumer already reads the verdict.
+
+**Keep the base optional and skip the check without one.** Rejected. Its failure mode is precisely the bug being fixed, delivered with no signal: healthy cards for presets that cannot compose. `ctx.baseUrl` is set on the root before any scoped context derives from it, so the throw is an assertion about something that does not happen rather than a branch with runtime cost.
+
+**Import each row instead of resolving it.** Rejected. Importing runs module top-level code on every roster read, which is a side effect a picker must not have, and it is the mount's job — a plugin that throws on apply or waits forever for a service still fails at the first session, by design.
+
+**Resolve every row through `import.meta.resolve`.** Shipped first and reverted on measurement: correct, and 445ms per roster read, which the client's three concurrent reads turned into 2.45 seconds apiece — the settings section visibly stalled. The resolver is the authority on what imports, but asking it about rows that are plainly installed pays a hooks-thread round-trip for each one.
+
+**Cache the whole of `compositionProblem` on the existing `CompositionStamp`.** Rejected as the answer to the cost: it would have made repeat reads free while leaving the first read of every edited composition at full price, and it keys resolution on the composition file, which does not change when an install does. The walk removed the cost instead, so nothing needs the stamp.
+
+**Send the switch failure to the roster card instead of a banner.** Rejected: the card is exactly where the failures that reach a mount are invisible. A composition whose rows all resolve is reported healthy, so "see the settings page for the reason" points at a card that says the preset is fine.
+
+**Report only the first unresolvable row, matching the shape check.** Rejected. A parse failure can cascade, so naming one is honest there; unresolvable names are independent facts all knowable at once, and reporting them one reload at a time is the avoidable part.
+
+**Follow `error.cause` unconditionally in `mountDetail`.** Rejected. The Loader's wrapper already appends `cause.message` to the message it builds, so a plain chain would render every line twice. An `AggregateError` cause is the one shape whose detail the message drops.
+
+**Keep rendering the reason on the card face.** Rejected. The reason names package specifiers and paths, and a picker card that shows them in place of the preset's description trades what a chooser needs for what a fixer needs — while the fixer's copy is one hover away either way.
+
+**Reuse the icon row's `data-tip` pseudo-element for the tooltip.** Rejected once measured: generated content joins an element's accessible text, so the card's aria snapshot grew a second verbatim copy of a reason the alert already carried. A real `aria-hidden` element keeps exactly one accessible copy — and the existing tooltip is one `nowrap` line sized for an icon label, while this one names package specifiers one per line.
+
+**Make the badge a focusable control so the tooltip has a keyboard path.** Rejected for now. The badge sits inside the card's own `<button>`, so a focusable trigger means restructuring the card head; the visually hidden alert already reaches assistive technology, and no keyboard-only path regressed — the disabled card body was never in the tab order.
+
+## Consequences
+
+A preset naming a package that a rename or an uninstall took away is marked on the roster, refused before a mount is spent, and dropped from the pickers — the same treatment a ghost directory already got. The reason names each row at fault, and a failure that survives to mount names every row inside a group rather than the group alone.
+
+Health answers from what is installed, not from what would import: a package present but exporting a file that is missing still reports healthy and still fails at mount. That is the safe direction — under-reporting returns the previous behavior, while a false broken makes a usable preset unselectable — and it keeps the answer out of the build state of any one package. A source checkout is still not an installed host, though, because a shipped row names a package the deployment installs beside the roster: `shipped-root.spec.ts` asserts the shipped presets carry no reason other than unresolved rows rather than no reason at all. The mount fixtures name a module that loads and then refuses, since a fixture naming a file that does not exist can no longer reach the mount.
+
+A mount failure is now legible where it happens, which matters most for the failures health can never catch: a row that resolves and then refuses is reported healthy on the roster forever, so the banner is not a convenience over the card — it is the only account of that failure anywhere.
+
+Measured in the web app on a roster of eleven presets, `agentPreset.list` answers in 14ms cold and 6-8ms after, and the three concurrent reads the client opens with settle in 9ms of wall clock. The same reads took 2.45 seconds each while every row went through the resolver.
+
+`@deepseek-ai/cordis-plugin-group` is a devDependency of `dsh-agent-presets`: the mount fixtures now compose through `cordis:group` the way real presets do, and a preset outside the workspace cannot resolve that package by name, so the app registers it as a builtin and the fixture harness does the same.

+ 73 - 0
.agents/notes/implemented/architecture/2026-08-26-preset-health-resolves-rows.zh.md

@@ -0,0 +1,73 @@
+# Agent Note: Preset health resolves the rows it can prove will start
+
+Status: implemented
+
+[English](2026-08-26-preset-health-resolves-rows.md) | 中文
+
+## Problem
+
+名单列为健康的 preset,仍可能根本无法组装。发现过程的健康检查只证明组装能以加载器方言解析、由具名行组成,并刻意止步于此——它不解析任何插件名,也不应用任何配置。
+
+但 `broken` 是承重的,不是卡片上的装饰。`presetOptions` 会把损坏的行从会话选择器里滤掉,好让选择的人不必等到会话启动失败才发现;`resolveMountable` 会在花费一次挂载之前拒绝它。因此下游一切都把「不是 broken」读作「能组装」。
+
+这个缺口在[仓库命名契约](2026-08-11-repository-naming-contract-and-rename-ledger.zh.md)按预发布立场重命名包时暴露出来。仓库内的引用随之更新;写在 `<dshHome>/.agent-presets` 下的 preset 没有,于是引用 `@deepseek-ai/dsh-workspace-context` 的那一个保住了健康的卡片、保住了在选择器里的位置,直到有人切换过去才失败。引用了被后续版本改名或卸载的包,正是手写 preset 真正的腐化方式,而它恰好是这项检查排除掉的那一类。
+
+而它真正产出的失败,说得比它知道的还少。加载器的逐行包装构造一个普通 `Error`,其 message 以 `cause.message` 结尾,cause 只留在 `error.cause` 上。于是一个有两行失败的 group,抵达时是一行被包装的行,message 为 `failed to apply loader entry <group> (cordis:group): loader entries failed to apply`,两条真正的原因只能经由 `cause.errors` 取得。挂载诊断只展平 `AggregateError.errors`,从不跟随 `cause`,因此它停在那一行,一行都没点名。
+
+## Decision
+
+**发现过程解析每一行它能证明会启动的行,且不 import 任何东西。** 解析这一趟跑在 `packages/preset/agent-presets/src/discovery.ts` 的形状检查之后,因此格式错误的组装仍然回答形状原因。包名先在磁盘上查——就是 Node 自己那套向上走 `node_modules`、停在 `<包>/package.json` 的做法——只有在磁盘上查不到的名字才交给 `import.meta.resolve` 确认,而它的拒绝会在本进程内记下来。preset 相对路径与绝对路径改用 stat,因为对这两类 `import.meta.resolve` 只做 URL 拼接,否则一个丢失了自带文件的 preset 会蒙混过关。两条路都不求值。
+
+磁盘查找之所以是快路径,是因为解析器并非一件均质的事:只要注册了 ESM loader hook,每一次 `import.meta.resolve` 调用就变成一次到 hooks 线程的同步往返。在源码启动所用的 `tsx` hook 下,实测命中 2ms、未命中 5ms,而裸 Node 分别是 0.055ms 与 0.032ms——这让每次名单读取背上 238ms 的解析器时间。同样这 135 行,磁盘走法只要 0.7ms。把解析器留给磁盘找不到的名字,等于让一次读取只为它报出的失败付费,而不为它放行的每一行付费,同时也避免把只有 loader 能解析的包——经由 tsconfig paths 或 import map——判成损坏。Node 内建模块在两者之前直接短路。
+
+拒绝记录位于磁盘查找之后而非之前,因此后来装上的包会先在磁盘上被找到,已记下的拒绝不会在要紧的方向上过期。
+
+**只有一个分类器决定一行在哪里解析。** `src/specifier.ts` 拥有这个划分——`cordis:` 内建、preset 相对、绝对文件、包名——挂载的 import 覆写与发现过程的检查都读它。若发现过程按一个基准解析、而挂载按另一个基准 import,那一行会被报告为健康,然后加载失败。
+
+**可能永远不会启动的行被跳过。** `disabled` 是[加载器唯一会插值](2026-08-11-loader-entry-disabled-interpolation.zh.md)的条目字段:`!!js` 表达式在挂载时对加载器上下文求值,而发现过程无法仅凭文件做到。凡该字段不是缺失、null 或 `false` 的行都不做检查,被禁用的 group 连同其子行一起跳过。每个随附 preset 都用这种方式为 shell 行设门,所以这是常见形状,不是边角。
+
+**harness base 是必填参数。** `discoverPresets(roots, harnessBase)` 与 `scanRoot(root, harnessBase)` 都接收它;`AgentPresets` 在构造函数里读一次 `ctx.baseUrl`,缺失就抛。基准正是让这个问题可回答的前提——同一个包名从 preset 自己的目录解析会失败、从已安装的 harness 解析会成功——所以做成可选就等于悄悄恢复这项检查要终结的那个状态。
+
+**挂载诊断跟随携带信息多于自身 message 的 cause。** `mountDetail` 从 `AggregateError.errors` 取分支,或在 cause 是 `AggregateError` 时从 `error.cause.errors` 取;普通的 cause 链已被展平进 message,不再跟随,否则每一行都会打印两遍。嵌套分支在拥有它的那一行下缩进。
+
+**客户端把原因放到徽标上。** 卡片正面保留 preset 自己的描述,因为在那里一个包说明符不足以让选择的人采取行动。宿主给出的原因作为徽标的提示条服务于指针,另有一个视觉隐藏的 `role="alert"` 节点把它送达辅助技术——preset 损坏时卡片主体被禁用,因而离开 tab 序列,提示条也就没有键盘路径。
+
+**被拒绝的切换要在被拒绝的地方说明原因。** chip 的标签会弹回会话仍在运行的那个 preset,因此不说话的话,这次选择看起来就像根本没发生。它经由共享的 `Toast` 在 composer 列上方自报,与旁边的模型选择器报告被拒绝的选择方式一致。只有人刚做出的选择会被自报——应用器在会话成为当前会话时也会运行,为那种情况弹横幅等于报告一个没人问过的拒绝。横幅停留八秒而非 primitive 默认的三秒,因为它承载的原因要点名包与行;`Toast` 为此获得了 `holdMs`,顺带也消除了「停留常量必须由人手与样式表保持同步」这一隐患。
+
+线上本来就把这需要的两段文本分开了:`message` 把原因裹进名单自己的「preset X failed to mount」框架,而 `details.reason` 只保留原因本身。自己会点名 preset 的表面取后者,否则会把 preset 说两遍。
+
+## Alternatives considered
+
+**在选中 preset 时检查,而不是在列出名单时。** 否决。选择器在任何人选中之前就按 `broken` 过滤,因此只在选中时检查的 preset 仍会被摆出来,报出的失败仍在点击之后到达——原本的抱怨只是换了个位置。名单行才是每个消费者已经在读判定的地方。
+
+**让 base 可选,没有它就跳过检查。** 否决。它的失败模式正是要修的这个 bug,而且不带任何信号:无法组装的 preset 顶着健康卡片。`ctx.baseUrl` 在任何作用域上下文派生之前就设在根上,因此这个抛出是对「不会发生的事」的断言,而不是一条有运行时代价的分支。
+
+**import 每一行而不是解析它。** 否决。import 会在每次读取名单时执行模块顶层代码,这是选择器不该有的副作用,而且那是挂载的职责——在 apply 时抛错、或永远等待某个服务的插件仍按设计在第一个会话处失败。
+
+**每一行都交给 `import.meta.resolve` 解析。** 先这样发出去,实测后回退:它是对的,但每次名单读取要 445ms,而客户端并发的三次读取把它放大成每次 2.45 秒——设置分区肉眼可见地卡住。解析器确实是「什么能 import」的权威,但为明摆着装好的行去问它,等于为每一行付一次 hooks 线程往返。
+
+**把整个 `compositionProblem` 缓存在已有的 `CompositionStamp` 上。** 作为省开销的手段被否决:它只能让重复读取免费,每个被编辑过的组装的第一次读取仍是全价;而且它把解析结果挂在组装文件上,可安装状态变化时组装文件并不会变。改用磁盘查找直接消掉了开销,于是没有什么还需要这个 stamp。
+
+**把切换失败送到名单卡片上,而不是弹横幅。** 否决:卡片恰恰是那些能走到挂载的失败看不见的地方。所有行都能解析的组装会被报告为健康,于是「去设置页看原因」指向的是一张写着「这个 preset 没问题」的卡片。
+
+**只报第一个无法解析的行,与形状检查保持一致。** 否决。解析失败会连锁,所以在那里只点名一个是诚实的;无法解析的名字是彼此独立、一次即可全部知晓的事实,而一次重载只修一个才是可以避免的部分。
+
+**在 `mountDetail` 里无条件跟随 `error.cause`。** 否决。加载器的包装已经把 `cause.message` 追加进它构造的 message,因此普通链会把每一行渲染两遍。`AggregateError` 类型的 cause 是唯一被 message 丢掉细节的形状。
+
+**继续把原因渲染在卡片正面。** 否决。原因里是包说明符和路径,把它们摆在 preset 描述的位置,等于用选择者需要的东西换取修复者需要的东西——而修复者需要的那份,无论如何都只隔一次悬停。
+
+**复用图标行的 `data-tip` 伪元素来做提示条。** 实测后否决:生成内容会并入元素的可访问文本,因此卡片的 aria 快照多出一份 alert 已经携带的原因的逐字副本。改用真实的 `aria-hidden` 元素后,可访问副本恰好只有一份——而且既有那条提示条是为图标标签准备的单行 `nowrap`,这一条要逐行列出包说明符。
+
+**把徽标做成真正可聚焦的控件,让提示条有键盘路径。** 暂不采用。徽标位于卡片自身的 `<button>` 内部,可聚焦的触发器意味着改造卡片头部结构;视觉隐藏的 alert 已经触达辅助技术,且没有任何键盘路径退化——被禁用的卡片主体从来就不在 tab 序列里。
+
+## Consequences
+
+引用了被改名或卸载掉的包的 preset,会在名单上被标出、在花费挂载之前被拒绝、并从选择器里剔除——与幽灵目录早已得到的待遇一致。原因会点名每一个出问题的行;而活到挂载阶段的失败,会点名 group 内的每一行,而不只是 group 本身。
+
+健康依据的是「装没装」,而不是「能不能 import」:包在、但导出指向的文件不在,仍会报告健康并仍在挂载时失败。这是安全的方向——漏报只是退回先前的行为,而误报会让一个可用的 preset 变得不可选——而且它让答案不依赖于任何单个包的构建状态。不过源码检出仍不是已安装宿主,因为随附行引用的是部署与名单装在一起的包:`shipped-root.spec.ts` 断言随附 preset 除未解析行之外不携带其他原因,而不是不携带任何原因。挂载夹具改为引用一个能加载、随后拒绝的模块,因为引用不存在文件的夹具已经到不了挂载。
+
+挂载失败现在在它发生的地方就可读,这对健康永远抓不到的那类失败最要紧:能解析、随后拒绝的行在名单上永远显示健康,因此这条横幅不是卡片之外的一份便利——它是那类失败在任何地方唯一的交代。
+
+在 web 应用中对十一个 preset 的名单实测:`agentPreset.list` 冷启动 14ms、之后 6–8ms,客户端开场并发的三次读取合计 9ms wall。在每一行都过解析器的版本里,同样这三次读取各要 2.45 秒。
+
+`@deepseek-ai/cordis-plugin-group` 成为 `dsh-agent-presets` 的 devDependency:挂载夹具现在像真实 preset 那样经由 `cordis:group` 组装,而工作区之外的 preset 无法按名解析该包,所以应用把它注册为内建,夹具 harness 也照做。

+ 45 - 4
apps/web/tests/agent-preset-selection.e2e.ts

@@ -9,7 +9,8 @@
 //
 // Zero model calls: no replay fixture mounts, so a stray stream fails loud.
 import { fileURLToPath } from 'node:url'
-import { mkdir, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, realpath, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
 import { join } from 'node:path'
 import type { Browser, Page } from 'playwright'
 import { chromium } from 'playwright'
@@ -32,6 +33,26 @@ const MODE = webSnapshotMode()
 const SEED_ID = 'agent-preset-selection-web-e2e'
 /** A project skill only a preset that mounts `skill-filesystem` can discover. */
 const SKILL_NAME = 'preset-catalog-demo'
+/** The preset whose rows resolve and then refuse to start. */
+const REFUSING_ID = 'zz-refusing'
+
+/**
+ * Seed a preset discovery reports healthy and the mount refuses.
+ *
+ * Every row resolves — the module is right there beside the composition — so
+ * health has nothing to report and the chip offers the preset like any other.
+ * Only starting it finds out, which is the case the chip's banner exists for.
+ * @param root - the lane's writable preset root.
+ */
+async function seedRefusingPreset(root: string): Promise<void> {
+  const directory = join(root, REFUSING_ID)
+  await mkdir(directory, { recursive: true })
+  await writeFile(join(directory, 'refuses.mjs'),
+    'export const name = \'refuses\'\nexport function apply() { throw new Error(\'this row refuses to start\') }\n')
+  await writeFile(join(directory, 'agent.cordis.yml'), '- id: refuses\n  name: ./refuses.mjs\n')
+  await writeFile(join(directory, 'preset.yml'),
+    'name: Refusing mode\ndescription: Resolves, then refuses to start.\n')
+}
 
 /**
  * Seed one project skill under the connected workspace.
@@ -176,11 +197,16 @@ describe('web e2e: agent-preset selection', () => {
   let browser: Browser
   let page: Page
   let tripwire: ReturnType<typeof watchConsole>
+  let presetRoot: string
 
   beforeAll(async () => {
-    // The scaffold's default roster pin is exactly this scenario's shape: the
-    // plugin's shipped presets, default `standard`.
-    scaffold = await launchWebScaffold({})
+    // The shipped presets, plus one lane-owned preset that mounts and refuses:
+    // the chip's own failure path needs a preset the roster offers.
+    presetRoot = await realpath(await mkdtemp(join(tmpdir(), 'dsh-web-e2e-refusing-')))
+    await seedRefusingPreset(presetRoot)
+    scaffold = await launchWebScaffold({
+      agentPresets: { roots: [{ path: presetRoot, trust: 'user' }], default: 'standard' },
+    })
     // A resumed session runs what it was created with; seeding one that
     // records `minimal` is what makes the header label a claim about the
     // session rather than an echo of the current default.
@@ -237,6 +263,21 @@ describe('web e2e: agent-preset selection', () => {
     await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('minimal')
   })
 
+  it('says why a switch was refused instead of letting the chip revert in silence', async () => {
+    onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-preset-refused'))
+    await page.getByRole('button', { name: 'Minimal mode' }).click()
+    await page.getByRole('menuitem', { name: /Refusing mode/ }).click()
+
+    // Health cleared every row, so nothing on the settings page says this
+    // preset is unusable — the banner is where the host's reason lands, and
+    // without it the chip just snaps back to the preset it already ran.
+    const banner = page.getByRole('alert').filter({ hasText: 'Refusing mode' })
+    await banner.waitFor({ timeout: 15_000 })
+    expect(await banner.textContent()).toContain('this row refuses to start')
+    await expect.poll(() => livePreset(scaffold), { timeout: 15_000 }).toBe('minimal')
+    await page.getByRole('button', { name: 'Minimal mode' }).waitFor({ timeout: 10_000 })
+  }, 60_000)
+
   it('re-reads the slash catalog through the composition the switch installed', async () => {
     // Continues the previous case: the chip has already applied `minimal` to
     // the blank session, and this one reads the menu that switch left behind.

+ 1 - 0
apps/web/tests/expected/agent-preset-selection/menu.expected.md

@@ -5,3 +5,4 @@
   - menuitem "PTC mode All Standard mode capabilities, with tools exposed through the Code Mode SDK so the model can combine multi-step operations in one TypeScript program."
   - menuitem "Minimal mode Two-tool coding agent with persistent bash and str_replace_editor."
   - menuitem "Creator mode Built for creating custom agent presets, with all Standard mode capabilities plus runtime inspection, plugin experiments, and preset-authoring guidance."
+  - menuitem "Refusing mode Resolves, then refuses to start."

+ 2 - 2
packages/client/ui-agent-preset/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-agent-preset/README.md
-README.md: d36588fedc0a86b62acec05b523ec410f36d089b
-README.zh.md: e1364214af04c511c0b42fba46ac73e22edd8c41
+README.md: 20d8df62361e683ac302b40138984bc4ab7aad67
+README.zh.md: a99695909cabdd871d87e6cd75bd92f0d22329e5

+ 2 - 2
packages/client/ui-agent-preset/README.md

@@ -29,7 +29,7 @@ Mount this plugin alongside the settings and conversation packages; the preset s
 
 ### Managing the roster
 
-The settings section shows the roster as cards: a copy dialog is the only way a preset is created — the browser edits no composition text — and every custom card keeps a location action that opens the preset's own files. The default is set from any surface; deleting removes the preset directory while sessions already composed from it keep running. A shipped preset opens in a read-only viewer and offers no location or delete. A roster row carrying `broken` renders as a marked card whose body and duplication are disabled, because a copy of a broken preset is another broken preset; broken custom rows keep their location and delete actions so the files can be fixed and ghost directories cleared.
+The settings section shows the roster as cards: a copy dialog is the only way a preset is created — the browser edits no composition text — and every custom card keeps a location action that opens the preset's own files. The default is set from any surface; deleting removes the preset directory while sessions already composed from it keep running. A shipped preset opens in a read-only viewer and offers no location or delete. A roster row carrying `broken` renders as a marked card whose body and duplication are disabled, because a copy of a broken preset is another broken preset; broken custom rows keep their location and delete actions so the files can be fixed and ghost directories cleared. The card face still shows the preset's own description — a chooser cannot act on a package specifier there — and the host's reason rides the badge as a tooltip, plus a visually hidden alert that carries it to assistive technology, which a disabled card body cannot.
 
 ### The conversational entry
 
@@ -43,7 +43,7 @@ When the roster carries the self-referential `cordis` preset, a dashed add-card
 <details>
 <summary>Implementation internals — click to expand</summary>
 
-Options and the current default both come from one `agentPreset.list` call — the roster already reports which id a session with no explicit choice gets, so the row needs no settings-schema introspection — and the write targets the `agent-presets` settings namespace's `default` field, which is what the host resolves at creation. The new-session chip and the header label share one controller, because the staged choice belongs to the flow rather than to any one session; the stage is applied when a session arrives (covering both the session a workspace connect created and the blank one it reused) and dropped on refusal. [`dsh-client-connection`](../connection/README.md) authenticates `agentPreset.read`, `copy`, `openDocument`, `remove`, `list`, and every other Host API method with the same browser session. A composition still names the plugins a session runs, so reading one is reconnaissance, while copy, remove, and openDocument manage the roster and drive the host desktop. The section re-reads on its own actions, `settings/changed`, and `connection/reset`, because composition files are edited outside the browser and nothing on the wire announces a file change.
+Options and the current default both come from one `agentPreset.list` call — the roster already reports which id a session with no explicit choice gets, so the row needs no settings-schema introspection — and the write targets the `agent-presets` settings namespace's `default` field, which is what the host resolves at creation. The new-session chip and the header label share one controller, because the staged choice belongs to the flow rather than to any one session; the stage is applied when a session arrives (covering both the session a workspace connect created and the blank one it reused) and dropped on refusal. A refusal announces itself as a transient banner over the composer column, because the chip's label has already reverted and a preset the host refuses to MOUNT is one discovery reported healthy — its roster card carries no reason to go back and read. Only a pick a person just made is announced; the applier that runs when a session becomes current is not. A refusal announces itself as a transient banner over the composer column, because the chip's label has already reverted and a preset the host refuses to MOUNT is one discovery reported healthy — its roster card carries no reason to go back and read. Only a pick a person just made is announced; the applier that runs when a session becomes current is not. [`dsh-client-connection`](../connection/README.md) authenticates `agentPreset.read`, `copy`, `openDocument`, `remove`, `list`, and every other Host API method with the same browser session. A composition still names the plugins a session runs, so reading one is reconnaissance, while copy, remove, and openDocument manage the roster and drive the host desktop. The section re-reads on its own actions, `settings/changed`, and `connection/reset`, because composition files are edited outside the browser and nothing on the wire announces a file change.
 
 </details>
 

+ 2 - 2
packages/client/ui-agent-preset/README.zh.md

@@ -29,7 +29,7 @@ kind: "package-reference"
 
 ### 管理名单
 
-设置分区把名单呈现为卡片:复制对话框是创建 preset 的唯一入口——浏览器不编辑任何组装文本——每张自定义卡片都保留一个打开 preset 自身文件的位置动作。默认值可在任一表面设置;删除会移除 preset 目录,而已据其组装的会话继续运行。随附 preset 在只读查看器中打开,不提供位置或删除。名单行携带 `broken` 时渲染为标记卡片,其主体与复制均被禁用,因为损坏 preset 的副本只是另一个损坏 preset;损坏的自定义行保留位置与删除动作,以便修复文件、清掉幽灵目录。
+设置分区把名单呈现为卡片:复制对话框是创建 preset 的唯一入口——浏览器不编辑任何组装文本——每张自定义卡片都保留一个打开 preset 自身文件的位置动作。默认值可在任一表面设置;删除会移除 preset 目录,而已据其组装的会话继续运行。随附 preset 在只读查看器中打开,不提供位置或删除。名单行携带 `broken` 时渲染为标记卡片,其主体与复制均被禁用,因为损坏 preset 的副本只是另一个损坏 preset;损坏的自定义行保留位置与删除动作,以便修复文件、清掉幽灵目录。卡片正面仍显示 preset 自己的描述——在选择器里,一个包说明符不足以让人采取行动——宿主给出的原因作为提示条挂在徽标上,另有一个视觉隐藏的 alert 把它送达辅助技术,而被禁用的卡片主体做不到这一点。
 
 ### 对话式入口
 
@@ -43,7 +43,7 @@ kind: "package-reference"
 <details>
 <summary>实现细节——点击展开</summary>
 
-选项与当前默认值都来自同一次 `agentPreset.list` 调用——名单本身已报告未显式选择的会话会得到哪个 id,因此该行无需对 settings schema 做内省——写入目标是 `agent-presets` settings 命名空间的 `default` 字段,也正是宿主在创建时解析的字段。新建会话 chip 与标题标签共用一个控制器,因为暂存选择属于流程而非任何单个会话;暂存值在会话到达时应用(既覆盖工作区连接新建的会话,也覆盖它复用的空白会话),被拒绝时丢弃。[`dsh-client-connection`](../connection/README.zh.md) 使用同一浏览器会话认证 `agentPreset.read`、`copy`、`openDocument`、`remove`、`list` 及其他所有 Host API 方法。组装仍会指明一个会话所运行的插件,因此读取属于侦察,而 copy、remove 与 openDocument 管理名单并驱动宿主桌面。分区在自身操作、`settings/changed` 与 `connection/reset` 时重读,因为组装文件在浏览器之外编辑,线上没有任何机制宣布文件变动。
+选项与当前默认值都来自同一次 `agentPreset.list` 调用——名单本身已报告未显式选择的会话会得到哪个 id,因此该行无需对 settings schema 做内省——写入目标是 `agent-presets` settings 命名空间的 `default` 字段,也正是宿主在创建时解析的字段。新建会话 chip 与标题标签共用一个控制器,因为暂存选择属于流程而非任何单个会话;暂存值在会话到达时应用(既覆盖工作区连接新建的会话,也覆盖它复用的空白会话),被拒绝时丢弃。被拒绝会以一条瞬时横幅在 composer 列上方自报,因为 chip 的标签此时已经弹回,而被宿主拒绝**挂载**的 preset 正是发现过程报告为健康的那一种——它的名单卡片上没有任何原因可供回头查看。只有人刚做出的选择会被自报;会话成为当前会话时触发的应用器不会。[`dsh-client-connection`](../connection/README.zh.md) 使用同一浏览器会话认证 `agentPreset.read`、`copy`、`openDocument`、`remove`、`list` 及其他所有 Host API 方法。组装仍会指明一个会话所运行的插件,因此读取属于侦察,而 copy、remove 与 openDocument 管理名单并驱动宿主桌面。分区在自身操作、`settings/changed` 与 `connection/reset` 时重读,因为组装文件在浏览器之外编辑,线上没有任何机制宣布文件变动。
 
 </details>
 

+ 94 - 43
packages/client/ui-agent-preset/src/client/AgentPresetSeat.tsx

@@ -12,10 +12,12 @@
  * Picking stages; the choice reaches a session when one becomes current.
  */
 
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
 import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
 import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
-import { IconAgentPresetOutline16, IconChevronDownOutline14, Menu } from '@deepseek-ai/dsh-client-ui-primitives'
+import {
+  IconAgentPresetOutline16, IconChevronDownOutline14, IconWarningOutline16, Menu, Toast,
+} from '@deepseek-ai/dsh-client-ui-primitives'
 // Type-only: pulls the ui-conversation SlotMap merge (the hero seat).
 import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
 import type { AgentPresetSeatState } from './seat-store.ts'
@@ -30,8 +32,8 @@ export interface AgentPresetSeatInjected {
   }
   /** Read the roster when the chip first renders. */
   load: () => Promise<void>
-  /** Stage one preset for the next session. */
-  select: (id: string) => Promise<void>
+  /** Stage one preset for the next session; resolves to a refusal, or undefined. */
+  select: (id: string) => Promise<string | undefined>
   /** Clear the one-shot introduce cue once the chip has played it. */
   introduced: () => void
 }
@@ -47,6 +49,18 @@ const INTRO_CHAR_STAGGER_MS = 40
 const INTRO_TEXT_REVEAL_MS = 200
 const INTRO_CHAR_FADE_MS = 400
 
+/**
+ * How long a refused switch holds before fading.
+ *
+ * Longer than the primitive's default because this banner is the only place
+ * the refusal appears. The chip's label has already snapped back to the
+ * preset the session still runs, and a preset the host refuses to MOUNT is
+ * one discovery reported healthy — its row on the settings page carries no
+ * reason to go back and read, because there was nothing to see until the
+ * rows actually ran.
+ */
+const REFUSAL_HOLD_MS = 8000
+
 /**
  * Per-character start offset for the introduce reveal.
  * @param count - character count of the shown preset name.
@@ -71,6 +85,11 @@ export type AgentPresetSeatProps =
 export function AgentPresetSeat({ load, select, introduced, useAgentPresetSeat, t }: AgentPresetSeatProps) {
   const state = useAgentPresetSeat(snapshot => snapshot)
   const [open, setOpen] = useState(false)
+  // The seq keys the banner, so picking the same broken preset twice replays
+  // it rather than leaving the first one silently in place.
+  const seatRef = useRef<HTMLButtonElement>(null)
+  const toastSeq = useRef(0)
+  const [toast, setToast] = useState<{ seq: number; text: string } | null>(null)
 
   useEffect(() => {
     void load()
@@ -126,45 +145,77 @@ export function AgentPresetSeat({ load, select, introduced, useAgentPresetSeat,
     : label
 
   return (
-    <Menu
-      open={open}
-      onClose={() => { setOpen(false) }}
-      items={state.options.map((option) => {
-        const text = presetDisplayText(option, t)
-        return {
-          id: option.id,
-          // Name and description together: the id alone never says what a
-          // preset does, which is why the roster carries display copy.
-          label: (
-            <span className={css.item}>
-              <span className={css.itemName}>{text.name}</span>
-              <span className={css.itemDesc}>{text.description ?? t('noDescription')}</span>
-            </span>
-          ),
-        }
-      })}
-      selectedId={state.current}
-      onSelect={(id) => {
-        setOpen(false)
-        void select(id)
-      }}
-      align="start"
-      portal
-      anchor={(
-        <button
-          type="button"
-          className={css.seat}
-          aria-haspopup="menu"
-          aria-expanded={open}
-          title={state.error ?? t('seatHint')}
-          disabled={state.busy}
-          onClick={() => { setOpen(value => !value) }}
-        >
-          <IconAgentPresetOutline16 className={introducing ? `${css.seatIcon} ${css.introIcon}` : css.seatIcon} />
-          {shownLabel}
-          <IconChevronDownOutline14 className={css.chevron} />
-        </button>
+    <>
+      <Menu
+        open={open}
+        onClose={() => { setOpen(false) }}
+        items={state.options.map((option) => {
+          const text = presetDisplayText(option, t)
+          return {
+            id: option.id,
+            // Name and description together: the id alone never says what a
+            // preset does, which is why the roster carries display copy.
+            label: (
+              <span className={css.item}>
+                <span className={css.itemName}>{text.name}</span>
+                <span className={css.itemDesc}>{text.description ?? t('noDescription')}</span>
+              </span>
+            ),
+          }
+        })}
+        selectedId={state.current}
+        onSelect={(id) => {
+          setOpen(false)
+          const picked = state.options.find(option => option.id === id)
+          // The fallback is for the row shape `find` cannot promise; the menu's
+          // items ARE `state.options`, so an emitted id is always one of them.
+          /* v8 ignore next */
+          const name = picked === undefined ? id : presetDisplayText(picked, t).name
+          void select(id).then((refusal) => {
+            // Announced only for a pick a person just made: `apply()` also runs
+            // when a session becomes current, and a banner over that would
+            // report a refusal nobody asked for.
+            if (refusal === undefined) return
+            toastSeq.current += 1
+            setToast({ seq: toastSeq.current, text: t('switchRefused', { name, reason: refusal }) })
+          })
+        }}
+        align="start"
+        portal
+        anchor={(
+          <button
+            ref={seatRef}
+            type="button"
+            className={css.seat}
+            aria-haspopup="menu"
+            aria-expanded={open}
+            title={state.error ?? t('seatHint')}
+            disabled={state.busy}
+            onClick={() => { setOpen(value => !value) }}
+          >
+            <IconAgentPresetOutline16 className={introducing ? `${css.seatIcon} ${css.introIcon}` : css.seatIcon} />
+            {shownLabel}
+            <IconChevronDownOutline14 className={css.chevron} />
+          </button>
+        )}
+      />
+      {toast !== null && (
+        <Toast
+          key={toast.seq}
+          text={toast.text}
+          icon={<IconWarningOutline16 />}
+          holdMs={REFUSAL_HOLD_MS}
+          // The composer card, which is the content column this chip sits
+          // above — not an ancestor of it, so the lookup is a page query
+          // rather than `closest`. Absent, the banner centers on the window,
+          // which is off-center whenever the sidebar is open.
+          anchor={
+            seatRef.current?.closest<HTMLElement>('[data-composer-card]')
+            ?? document.querySelector<HTMLElement>('[data-composer-card]')
+          }
+          onDone={() => { setToast(null) }}
+        />
       )}
-    />
+    </>
   )
 }

+ 46 - 4
packages/client/ui-agent-preset/src/client/AgentPresetSection.module.css

@@ -94,12 +94,49 @@
   color: var(--dsw-alias-bg-layer-3);
 }
 
-/* The discovery-reported reason, verbatim: it names the file and the fix. */
-.cardBrokenReason {
-  font-size: 12px;
+/* The discovery-reported reason, verbatim: it names the rows and the fix.
+   A real element rather than the icon row's `data-tip` pseudo-element, for two
+   reasons: generated content joins the card's accessible text, where this would
+   repeat what the alert already carries, and that tooltip is one `nowrap` line
+   for an icon label while this names package specifiers one per line. */
+.brokenTip {
+  position: absolute;
+  top: calc(100% + 6px);
+  left: 0;
+  z-index: 1;
+  width: max-content;
+  max-width: 100%;
+  padding: 6px 8px;
+  border-radius: 6px;
+  background: var(--dsw-alias-label-primary);
+  color: var(--dsw-alias-bg-layer-3);
+  font-size: 11px;
+  font-weight: 400;
   line-height: 1.5;
-  color: var(--dsw-alias-state-error-primary);
+  text-align: left;
+  white-space: pre-line;
   overflow-wrap: anywhere;
+  opacity: 0;
+  pointer-events: none;
+  transition: opacity .12s;
+}
+
+.brokenBadge:hover .brokenTip {
+  opacity: 1;
+}
+
+/* The same reason, for assistive technology only. The card body is disabled
+   when a preset is broken, so it leaves the tab order and the badge's tooltip
+   has no keyboard or screen-reader path; this node is that path. Sighted
+   pointer users read the badge instead, which keeps a picker card showing the
+   preset's own description rather than a package specifier. */
+.cardBrokenReason {
+  position: absolute;
+  width: 1px;
+  height: 1px;
+  overflow: hidden;
+  clip: rect(0 0 0 0);
+  white-space: nowrap;
 }
 
 /* The card body is the control that picks the preset. */
@@ -132,6 +169,11 @@
   display: flex;
   align-items: center;
   gap: 8px;
+  /* Anchors the broken badge's tooltip: the badge itself stays unpositioned so
+     its `::after` resolves against the card's own width instead of against a
+     badge that sits partway across it. A tooltip grown from the badge would
+     run past the card, and past the section for a card in the last column. */
+  position: relative;
 }
 
 .cardName {

+ 20 - 3
packages/client/ui-agent-preset/src/client/AgentPresetSection.tsx

@@ -257,7 +257,8 @@ export function AgentPresetSection(props: AgentPresetSectionProps): ReactNode {
                       The action row sits outside it — nesting buttons is
                       invalid, and these act on the card rather than select it.
                       A broken preset cannot compose a session, so its body is
-                      disabled and the card says why instead of offering it. */}
+                      disabled; the reason rides the badge rather than the card
+                      face, which stays the preset's own description. */}
                     <button
                       type="button"
                       className={css.cardMain}
@@ -266,13 +267,25 @@ export function AgentPresetSection(props: AgentPresetSectionProps): ReactNode {
                       // Without this the name is the whole card read aloud —
                       // title, badge, description, id.
                       aria-label={`${row.broken !== undefined ? t('brokenBadge') : row.isDefault ? t('inUse') : t('setDefault')}: ${text.name}`}
-                      title={row.broken ?? (row.isDefault ? t('inUse') : t('setDefault'))}
+                      // The reason rides the badge, not the whole card: two
+                      // tooltips over one target would race, and the card's
+                      // own label answers what clicking it would do.
+                      title={row.broken !== undefined ? t('brokenBadge') : row.isDefault ? t('inUse') : t('setDefault')}
                       onClick={() => { void props.makeDefault(row.id) }}
                     >
                       <span className={css.cardHead}>
                         <span className={css.cardName}>{text.name}</span>
                         {row.broken !== undefined
-                          ? <span className={css.brokenBadge}>{t('brokenBadge')}</span>
+                          ? (
+                            <span className={css.brokenBadge}>
+                              {t('brokenBadge')}
+                              {/* Pointer-only, hence `aria-hidden`: the same
+                                reason reaches assistive technology through the
+                                alert below, and a second copy inside the card's
+                                own text would be read out twice. */}
+                              <span className={css.brokenTip} aria-hidden="true">{row.broken}</span>
+                            </span>
+                          )
                           : null}
                         <span className={css.badge}>
                           {row.trust === 'user' ? t('userTrust') : t('builtIn')}
@@ -280,6 +293,10 @@ export function AgentPresetSection(props: AgentPresetSectionProps): ReactNode {
                         {row.isDefault ? <span className={css.inUse}>{t('inUse')}</span> : null}
                       </span>
                       <CardDescription text={text.description ?? t('noDescription')} />
+                      {/* Visually hidden, deliberately: the pointer path is the
+                        badge's tooltip, and a disabled card body is out of the
+                        tab order, so this is the only reading a screen reader
+                        or a keyboard-only user gets. */}
                       {row.broken === undefined
                         ? null
                         : <span className={css.cardBrokenReason} role="alert">{row.broken}</span>}

+ 3 - 1
packages/client/ui-agent-preset/src/client/locales.ts

@@ -11,7 +11,7 @@ export type AgentPresetSettingsKey =
   | 'duplicate' | 'duplicateUnavailable' | 'delete' | 'presetId' | 'presetIdPlaceholder' | 'copyOf'
   | 'displayName' | 'displayNamePlaceholder'
   | 'inUse' | 'noDescription' | 'builtInGroup' | 'customGroup'
-  | 'brokenBadge' | 'brokenNoCopy'
+  | 'brokenBadge' | 'brokenNoCopy' | 'switchRefused'
   | 'composition' | 'cancel' | 'close' | 'retry'
   | 'copyTitle' | 'copyIntro' | 'create' | 'creating' | 'creatorDraft'
   | 'openLocation' | 'showLocation' | 'revealedPathLabel'
@@ -59,6 +59,7 @@ export const en: Record<AgentPresetSettingsKey, string> = {
   noDescription: 'No description.',
   brokenBadge: 'Failed to load',
   brokenNoCopy: 'A preset that failed to load cannot be duplicated',
+  switchRefused: 'Could not switch to {name}: {reason}',
   copyOf: 'Copied from',
   composition: 'Composition (agent.cordis.yml)',
   cancel: 'Cancel',
@@ -119,6 +120,7 @@ export const zh: Record<AgentPresetSettingsKey, string> = {
   noDescription: '暂无描述。',
   brokenBadge: '加载失败',
   brokenNoCopy: '预设加载失败,不能复制',
+  switchRefused: '无法切换到「{name}」:{reason}',
   copyOf: '复制自',
   composition: '组装(agent.cordis.yml)',
   cancel: '取消',

+ 16 - 4
packages/client/ui-agent-preset/src/client/seat-store.ts

@@ -98,13 +98,20 @@ export class AgentPresetSeatController {
   /**
    * Stage one preset for the next session, applying it immediately when a
    * blank session is already current.
+   *
+   * The refusal is returned as well as stored, because the two readers need
+   * different things from it: the chip's own label carries the standing state,
+   * while the caller that made this pick is the one that has to say why the
+   * label came back — and only it knows the pick was a person's, not the
+   * applier catching up with a session that just became current.
    * @param id - the preset to stage.
-   * @returns once the stage settled, and the apply too when one happened.
+   * @returns the refusal text, or undefined once the pick settled.
    */
-  async select(id: string): Promise<void> {
-    if (this.store.getSnapshot().busy) return
+  async select(id: string): Promise<string | undefined> {
+    if (this.store.getSnapshot().busy) return undefined
     this.stage(id)
     await this.apply()
+    return this.store.getSnapshot().error ?? undefined
   }
 
   /**
@@ -156,9 +163,14 @@ export class AgentPresetSeatController {
       const response = await this.api.agentPresets.select({ sessionId: session.id, agentPreset: staged })
       this.staged = undefined
       if (!response.result.ok) {
+        const { error } = response.result
         this.set({
           busy: false,
-          error: response.result.error.message,
+          // A mount failure carries its cause twice: `message` wraps it in the
+          // roster's own frame, which names the preset the surface reporting
+          // this already names, and `details.reason` holds the same cause
+          // without it.
+          error: error.code === 'agent-preset-invalid' ? error.details.reason : error.message,
           current: presetOf(session) ?? '',
         })
         return

+ 24 - 0
packages/client/ui-agent-preset/tests/apply.client.spec.ts

@@ -621,4 +621,28 @@ describe('AgentPresetSeatController reconciliation', () => {
       busy: false, current: '', error: message,
     })
   })
+
+  it('keeps the bare cause of a mount failure, not the frame that names the preset again', async () => {
+    const reason = 'failed to import loader entry ctx (@deepseek-ai/dsh-gone): Cannot find package'
+    const controller = new AgentPresetSeatController({
+      agentPresets: {
+        select: () => Promise.resolve({
+          rpcId: 'r',
+          result: {
+            ok: false as const,
+            error: {
+              code: 'agent-preset-invalid',
+              message: `agent-presets: preset "broken" failed to mount: ${reason}`,
+              details: { agentPreset: 'broken', reason },
+            },
+          },
+        }),
+      },
+    } as never, () => ({ id: SessionId('uncomposed'), blank: true }))
+
+    // The surface reporting this names the preset itself, so carrying the
+    // roster's own "preset X failed to mount" frame would say it twice.
+    expect(await controller.select('broken')).toBe(reason)
+    expect(controller.store.getSnapshot().error).toBe(reason)
+  })
 })

+ 53 - 7
packages/client/ui-agent-preset/tests/components.client.spec.tsx

@@ -55,17 +55,24 @@ function renderRow(state: Partial<AgentPresetSettingsState> = {}) {
   return actions
 }
 
-function renderSeat(state: Partial<AgentPresetSeatState> = {}) {
+/** The runtime's own `{name}` substitution, so a test reads the shown text. */
+function translate(key: keyof typeof en, params?: Record<string, unknown>): string {
+  const template = en[key]
+  return params === undefined
+    ? template
+    : template.replace(/\{(\w+)\}/g, (match, name: string) => name in params ? String(params[name]) : match)
+}
+
+function renderSeat(
+  state: Partial<AgentPresetSeatState> = {},
+  select: () => Promise<string | undefined> = () => Promise.resolve(undefined),
+) {
   const store = createSnapshotStore<AgentPresetSeatState>({ ...SEAT_READY, ...state })
-  const actions = {
-    load: vi.fn(() => Promise.resolve()),
-    select: vi.fn(() => Promise.resolve()),
-    introduced: vi.fn(),
-  }
+  const actions = { load: vi.fn(() => Promise.resolve()), select: vi.fn(select), introduced: vi.fn() }
   render(<AgentPresetSeat {...({
     ...actions,
     useAgentPresetSeat: bindSnapshotSelector(store),
-    t: (key: keyof typeof en) => en[key],
+    t: translate,
   } as unknown as AgentPresetSeatProps)} />)
   return actions
 }
@@ -277,6 +284,45 @@ describe('the new-session chip', () => {
   })
 })
 
+describe('a refused switch', () => {
+  it('announces the reason instead of letting the label snap back in silence', async () => {
+    // The banner's own timer has to be a fake one from the start, or the
+    // lifetime assertion below would wait out its real nine seconds.
+    vi.useFakeTimers({ shouldAdvanceTime: true })
+    try {
+      const reason = 'failed to import loader entry live-on-mac (@deepseek-ai/dsh-also-gone)'
+      renderSeat({}, () => Promise.resolve(reason))
+
+      fireEvent.click(screen.getByRole('button'))
+      fireEvent.click(screen.getByRole('menuitem', { name: /mine/ }))
+
+      // The host refuses a mount discovery reported healthy, so this banner is
+      // the only place the cause appears — the chip has already reverted and
+      // the settings row shows the preset as fine.
+      const banner = await screen.findByRole('alert')
+      expect(banner.textContent).toContain(reason)
+      expect(banner.textContent).toContain('mine')
+
+      // Transient by design: it holds long enough to read a cause that names
+      // packages, then leaves rather than sitting over the screen.
+      act(() => { vi.advanceTimersByTime(9001) })
+      expect(screen.queryByRole('alert')).toBeNull()
+    } finally {
+      vi.useRealTimers()
+    }
+  })
+
+  it('says nothing when the switch lands', async () => {
+    const actions = renderSeat()
+
+    fireEvent.click(screen.getByRole('button'))
+    fireEvent.click(screen.getByRole('menuitem', { name: /mine/ }))
+
+    await waitFor(() => { expect(actions.select).toHaveBeenCalledWith('mine') })
+    expect(screen.queryByRole('alert')).toBeNull()
+  })
+})
+
 describe('the chip introduce cue', () => {
   afterEach(() => {
     vi.useRealTimers()

+ 13 - 3
packages/client/ui-agent-preset/tests/section.client.spec.tsx

@@ -176,13 +176,23 @@ describe('the preset list', () => {
     const actions = renderSection({
       rows: [
         { id: 'standard', trust: 'system', isDefault: true },
-        { id: 'ghost', trust: 'user', isDefault: false, name: '幽灵预设', broken: 'the composition file agent.cordis.yml is missing' },
+        {
+          id: 'ghost', trust: 'user', isDefault: false, name: '幽灵预设', description: '我自己写的',
+          broken: 'the composition file agent.cordis.yml is missing',
+        },
       ],
     })
 
     const ghost = rowFor('ghost')
-    // The reason is on the card, and the body cannot pick what cannot mount.
-    expect(within(ghost).getByText(en.brokenBadge)).toBeTruthy()
+    // The badge carries the reason for a pointer, and the body cannot pick
+    // what cannot mount.
+    expect(within(ghost).getByText(en.brokenBadge).textContent)
+      .toBe(`${en.brokenBadge}the composition file agent.cordis.yml is missing`)
+    // A picker card keeps showing what the preset is; a package specifier in
+    // its place would tell a chooser nothing they can act on there.
+    expect(within(ghost).getByText('我自己写的')).toBeTruthy()
+    // Reachable without a pointer: the disabled body leaves the tab order, so
+    // this node is the only reading assistive technology gets.
     expect(within(ghost).getByRole('alert').textContent).toContain('is missing')
     const body = within(ghost).getByRole('button', { name: `${en.brokenBadge}: 幽灵预设` })
     expect(body).toHaveProperty('disabled', true)

+ 2 - 2
packages/client/ui-primitives/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/client/ui-primitives/README.md
-README.md: 4ca3d89dfcb5d169c274092ed9b14ab888bcafff
-README.zh.md: 0be30193cffe463f2ff05588c2ae1ded0746fec3
+README.md: bd3aa5292c189a0d1b62f6d5a20314f0be5e986c
+README.zh.md: 55b808aa73ff9cafad98d2dfca877263f0ca8723

+ 1 - 1
packages/client/ui-primitives/README.md

@@ -29,7 +29,7 @@ Compose feature UI from these atoms whenever the web client needs a standard con
 
 ### Controls and icons
 
-`Button`, `Pill`, `Input`, `Menu`, `Modal`, `Tooltip`, `DisclosureRow`, `StateDot`, `HoverCard`, `Toast`, `ConnectionBanner`, `RiskConfirmation`, and the `OnboardingSurface` first-run takeover cover the common interaction shapes. The `ic_ds_*` icon set and the `FishLogo`/`BrandWordmark` marks fill brand and inline-icon slots. `useAnchoredPosition` and `useAnchoredMaxHeight` keep floating panels and bottom-anchored overlays clamped to the viewport and following their anchor. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop.
+`Button`, `Pill`, `Input`, `Menu`, `Modal`, `Tooltip`, `DisclosureRow`, `StateDot`, `HoverCard`, `Toast`, `ConnectionBanner`, `RiskConfirmation`, and the `OnboardingSurface` first-run takeover cover the common interaction shapes. The `ic_ds_*` icon set and the `FishLogo`/`BrandWordmark` marks fill brand and inline-icon slots. `useAnchoredPosition` and `useAnchoredMaxHeight` keep floating panels and bottom-anchored overlays clamped to the viewport and following their anchor. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. `Toast` holds for the window its owner names through `holdMs`, because how long a banner has to stay depends on how much there is to read; the same value drives its unmount timer and the stylesheet's fade delay, so the two cannot disagree. `Toast` holds for the window its owner names through `holdMs`, because how long a banner has to stay depends on how much there is to read; the same value drives its unmount timer and the stylesheet's fade delay, so the two cannot disagree.
 
 ### Rendering agent output
 

+ 1 - 1
packages/client/ui-primitives/README.zh.md

@@ -29,7 +29,7 @@ kind: "package-library"
 
 ### 控件与图标
 
-`Button`、`Pill`、`Input`、`Menu`、`Modal`、`Tooltip`、`DisclosureRow`、`StateDot`、`HoverCard`、`Toast`、`ConnectionBanner`、`RiskConfirmation` 与首次运行接管层 `OnboardingSurface` 覆盖常见的交互形态。`ic_ds_*` 图标集与 `FishLogo`/`BrandWordmark` 标记填充品牌与行内图标 slot。`useAnchoredPosition` 与 `useAnchoredMaxHeight` 让浮动面板与底部锚定浮层始终钳制在视口内并跟随锚点。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。
+`Button`、`Pill`、`Input`、`Menu`、`Modal`、`Tooltip`、`DisclosureRow`、`StateDot`、`HoverCard`、`Toast`、`ConnectionBanner`、`RiskConfirmation` 与首次运行接管层 `OnboardingSurface` 覆盖常见的交互形态。`ic_ds_*` 图标集与 `FishLogo`/`BrandWordmark` 标记填充品牌与行内图标 slot。`useAnchoredPosition` 与 `useAnchoredMaxHeight` 让浮动面板与底部锚定浮层始终钳制在视口内并跟随锚点。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。 `Toast` 的停留时长由使用方通过 `holdMs` 指定,因为横幅该留多久取决于有多少内容要读;同一个值同时驱动它的卸载定时器与样式表的淡出延迟,两者不可能再错位。 `Toast` 的停留时长由使用方通过 `holdMs` 指定,因为横幅该留多久取决于有多少内容要读;同一个值同时驱动它的卸载定时器与样式表的淡出延迟,两者不可能再错位。
 
 ### 渲染 agent 输出
 

+ 6 - 4
packages/client/ui-primitives/src/Toast.module.css

@@ -1,5 +1,7 @@
-/* Keep the fade delay and duration synchronized with HOLD_MS and FADE_MS in
-   Toast.tsx so the toast unmounts after the fade. */
+/* The fade delay comes from the component as `--dsh-toast-hold`, so one value
+   drives both the unmount timer and this animation; the fallback matches the
+   component's own default. The fade DURATION still has to agree with FADE_MS
+   in Toast.tsx, which no owner varies. */
 
 .toast {
   position: fixed;
@@ -24,7 +26,7 @@
   transform: translateX(-50%);
   animation:
     dsh-toast-in 160ms ease-out,
-    dsh-toast-fade 1000ms ease 3000ms forwards;
+    dsh-toast-fade 1000ms ease var(--dsh-toast-hold, 3000ms) forwards;
 }
 
 .icon {
@@ -60,6 +62,6 @@
    not movement) still ends the banner before the timed unmount. */
 @media (prefers-reduced-motion: reduce) {
   .toast {
-    animation: dsh-toast-fade 1000ms ease 3000ms forwards;
+    animation: dsh-toast-fade 1000ms ease var(--dsh-toast-hold, 3000ms) forwards;
   }
 }

+ 21 - 7
packages/client/ui-primitives/src/Toast.tsx

@@ -1,10 +1,9 @@
 import { useEffect, useLayoutEffect, useState } from 'react'
-import type { ReactNode } from 'react'
+import type { CSSProperties, ReactNode } from 'react'
 import { createPortal } from 'react-dom'
 import css from './Toast.module.css'
 
-/** Full-opacity hold before the fade starts. Must agree with the stylesheet's
- * toast-fade delay (Toast.module.css) or the banner unmounts mid-fade. */
+/** Full-opacity hold before the fade starts, when the owner names none. */
 const HOLD_MS = 3000
 /** Fade duration. Must agree with the stylesheet's toast-fade duration. */
 const FADE_MS = 1000
@@ -17,24 +16,32 @@ const FADE_MS = 1000
  * transformed or filtered ancestor cannot trap the fixed banner in that
  * ancestor's box.
  *
+ * The hold is the owner's to set, because how long a banner has to stay
+ * depends on how much there is to read: a one-line limit lands in the default
+ * window, while a failure that names what broke does not. One value drives
+ * both the unmount timer and the stylesheet's fade delay — the stylesheet
+ * reads it as a custom property — so the two can no longer disagree and leave
+ * the banner unmounting mid-fade.
  * @param props.text - resolved banner copy; the owner passes localized text.
  * @param props.icon - optional leading glyph (e.g. a warning icon).
+ * @param props.holdMs - full-opacity hold before the fade; defaults to 3000.
  * @param props.anchor - optional element whose horizontal center the banner
  * follows (e.g. the composer card, so the banner centers over the chat column
  * rather than the whole window); omitted, it centers on the viewport.
  * @param props.onDone - called once the fade completes; unmount the toast here.
  * @returns the floating banner.
  */
-export function Toast({ text, icon, anchor, onDone }: {
+export function Toast({ text, icon, anchor, holdMs = HOLD_MS, onDone }: {
   text: string
   icon?: ReactNode
   anchor?: HTMLElement | null
+  holdMs?: number
   onDone: () => void
 }) {
   useEffect(() => {
-    const timer = setTimeout(onDone, HOLD_MS + FADE_MS)
+    const timer = setTimeout(onDone, holdMs + FADE_MS)
     return () => { clearTimeout(timer) }
-  }, [onDone])
+  }, [holdMs, onDone])
   // Anchor-centered placement re-measures on window resizes; the banner lives
   // four seconds, so sub-window layout drift within that span stays out of
   // scope.
@@ -50,7 +57,14 @@ export function Toast({ text, icon, anchor, onDone }: {
     return () => { window.removeEventListener('resize', measure) }
   }, [anchor])
   return createPortal(
-    <div className={css.toast} role="alert" style={left === null ? undefined : { left }}>
+    <div
+      className={css.toast}
+      role="alert"
+      style={{
+        ...left === null ? {} : { left },
+        '--dsh-toast-hold': `${String(holdMs)}ms`,
+      } as CSSProperties}
+    >
       {icon !== undefined && <span className={css.icon} aria-hidden>{icon}</span>}
       <span className={css.text}>{text}</span>
     </div>,

+ 18 - 0
packages/client/ui-primitives/tests/toast.client.spec.tsx

@@ -24,6 +24,24 @@ describe('Toast', () => {
     }
   })
 
+  it('holds for the owner\'s window and hands the stylesheet the same value', () => {
+    vi.useFakeTimers()
+    try {
+      const onDone = vi.fn()
+      const view = render(<Toast text="切换失败" holdMs={6000} onDone={onDone} />)
+      // One value drives both, so a banner can never unmount mid-fade: the
+      // timer waits the hold plus the fade, and the stylesheet delays the
+      // fade by the same hold.
+      expect(view.getByRole('alert').style.getPropertyValue('--dsh-toast-hold')).toBe('6000ms')
+      vi.advanceTimersByTime(6999)
+      expect(onDone).not.toHaveBeenCalled()
+      vi.advanceTimersByTime(1)
+      expect(onDone).toHaveBeenCalledTimes(1)
+    } finally {
+      vi.useRealTimers()
+    }
+  })
+
   it('centers over its anchor and re-measures on window resize', () => {
     vi.useFakeTimers()
     try {

+ 2 - 2
packages/preset/agent-presets/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write packages/preset/agent-presets/README.md
-README.md: 9dff11bd44a92013852021db5de6b23dfd7e634c
-README.zh.md: c63c72b7a1066948eeabb385685306535a03e84d
+README.md: f2860d5c84ac7a17c9dc5c0c556857d36450885a
+README.zh.md: 774c4e759201db7a923c38a0412e31a85f3dde10

+ 2 - 2
packages/preset/agent-presets/README.md

@@ -80,7 +80,7 @@ A session can switch to a different preset only while it has produced nothing 
 
 ### Failures and recovery
 
-A preset whose composition is missing, unparsable, or not a list of named plugin rows is listed as broken with a one-line reason; composing such a preset is refused up front, so a session never starts half-composed. A composition that parses but names a missing package, or waits for a service the composition never supplies, fails at session creation, which rolls the creation back. Fix the preset's file or delete it, then retry.
+A preset whose composition is missing, unparsable, not a list of named plugin rows, or naming a module that cannot be resolved is listed as broken with a reason naming the rows at fault; composing such a preset is refused up front, so a session never starts half-composed. What survives to session creation is a row whose module loads and then refuses — a plugin that throws, or one waiting for a service the composition never supplies — which fails the creation and rolls it back, naming every failed row including those inside a group. Fix the preset's file or delete it, then retry.
 
 -----
 
@@ -169,7 +169,7 @@ These limits define when the roster is a poor fit or needs special operational c
 - **A generation is keyed on the composition file alone** — the stamp check notices `agent.cordis.yml` changing, not an edit to a skill file or asset beside it; those reach new sessions only once the composition file itself moves or the process restarts.
 - **A superseded generation is never reclaimed** — sessions already joined keep the generation they run on, and the roster holds no join count that could tell when the last one left, so the whole subtree stays mounted until the process ends. The cost is per generation rather than per session, but it is not free: `dsh-skill-filesystem` watches its roots by default, so each edit-then-create cycle adds a live watcher set.
 - **A copy is never mounted to validate** — it is byte-identical to its source, so a source broken on disk yields a copy exactly as broken as the source; discovery's health check marks both rows on the next roster read rather than deferring the failure to a session start.
-- **Health is a shape check, not a mount** — discovery proves the composition parses in the loader dialect and holds named rows, not that every row's module resolves or activates; a row naming an absent package still fails at the first session, which rolls the creation back.
+- **Health asks what is installed, not what would import** — discovery proves the composition parses in the loader dialect, holds named rows, and that each row it can prove will start names a package present above the harness base or a file that exists; it never imports one, so a package whose own entry file is missing, a plugin that throws on apply, and one waiting forever for a service all still fail at the first session. `disabled` is the one entry field the Loader interpolates, so a row carrying an expression there is left unchecked rather than judged from the file.
 - **A copy is a snapshot that drifts** — upgrading the deployment does not update copies of shipped presets, and there is no patch semantics at this layer to express "standard plus one change"; the shipped set itself accepts the same cost — `cordis` and `code` each duplicate `standard`'s full assembly and then edit it — so the whole assembly stays readable in one file.
 - **Root scans are not watched** — every read hits the filesystem instead, which keeps the roster fresh but puts one `readdir` per root on each `list()`.
 

+ 2 - 2
packages/preset/agent-presets/README.zh.md

@@ -80,7 +80,7 @@ agent-presets:
 
 ### 失败与恢复
 
-组装缺失、无法解析或不是具名插件行列表的 preset 会被列为 broken,并附带一行原因;组装此类 preset 会被提前拒绝,因此会话绝不会以半组装状态启动。能解析但引用了缺失包、或等待组装从未提供的服务的组装,会在会话创建时失败并回滚创建。修复 preset 的文件或删除它,然后重试。
+组装缺失、无法解析、不是具名插件行列表,或者引用了无法解析的模块的 preset 会被列为 broken,原因会指名出问题的行;组装此类 preset 会被提前拒绝,因此会话绝不会以半组装状态启动。能活到会话创建的,是模块能加载但随后拒绝的行——抛错的插件,或等待组装从未提供的服务的插件——它会让创建失败并回滚,且会指名每一个失败的行,包括组内的行。修复 preset 的文件或删除它,然后重试。
 
 -----
 
@@ -169,7 +169,7 @@ agent-presets:
 - **代际只以组装文件为键**——stamp 检查只察觉 `agent.cordis.yml` 的变化,察觉不到旁边 skill 文件或资产的编辑;那些编辑要等组装文件本身变动或进程重启才达到新会话。
 - **被替代的代际永不回收**——已加入的会话保持其运行所在的代际,而名单没有加入计数可以判断最后一个何时离开,因此整棵子树一直挂到进程结束。代价按代际计而非按会话计,但并非为零:`dsh-skill-filesystem` 默认监听自己的根目录,因此每一轮「编辑后建会话」都会新增一套活的 watcher。
 - **副本从不被实际挂载以校验**——它与来源逐字节相同,因此磁盘上已坏的来源会产出与来源同样损坏的副本;发现过程的健康检查会在下一次读取名单时把两行都标出来,而不是把失败推迟到会话启动。
-- **健康是形状检查,不是挂载**——发现过程只证明组装能以加载器方言解析、由具名行组成,不证明每一行的模块都能解析并激活;引用不存在的包的行仍在第一个会话处失败,并回滚该会话的创建。
+- **健康问的是「装没装」,不是「能不能 import」**——发现过程证明组装能以加载器方言解析、由具名行组成,且每一行它能证明会启动的行所引用的包装在 harness 基准之上、或所引用的文件确实存在;它从不 import 任何一个,因此入口文件缺失的包、在 apply 时抛错的插件、以及永远等待某个服务的插件,都仍在第一个会话处失败。`disabled` 是加载器唯一会插值的条目字段,因此在该字段写了表达式的行会被跳过,而不是仅凭文件下判断。
 - **副本是会漂移的快照**——升级部署不会更新随附 preset 的副本,本层也没有表达「standard 加一处改动」的 patch 语义;随附集合自己也接受同样的代价——`cordis` 与 `code` 都复制了 `standard` 的完整组装并在此基础上编辑——换来整份组装在一个文件里可读。
 - **根目录扫描不做监听**——每次读取都实际访问文件系统,这让名单保持新鲜,但每次 `list()` 会对每个根目录产生一次 `readdir`。
 

+ 1 - 0
packages/preset/agent-presets/package.json

@@ -58,6 +58,7 @@
     "zod": "^4.4.3"
   },
   "devDependencies": {
+    "@deepseek-ai/cordis-plugin-group": "workspace:^",
     "@deepseek-ai/cordis-plugin-include": "workspace:^",
     "@deepseek-ai/cordis-plugin-loader": "workspace:^",
     "@deepseek-ai/dsh-agent": "workspace:^",

+ 174 - 8
packages/preset/agent-presets/src/discovery.ts

@@ -11,17 +11,27 @@
  * path refuses the name while no surface shows anything to delete — and a
  * malformed composition would otherwise read as an ordinary preset until the
  * first session fails to mount it.
+ *
+ * Health is what every consumer reads before offering a preset — the pickers
+ * drop a broken row rather than defer the discovery to a failed session
+ * start — so it covers the way an authored preset actually rots: a row naming
+ * a package that was renamed or uninstalled. Resolving those names is a
+ * separate pass from the shape check and stops short of importing anything,
+ * so a composition is judged without running a line of plugin code.
  * @module @deepseek-ai/dsh-agent-presets/discovery
  */
 
+import { existsSync } from 'node:fs'
 import { readdir, readFile, stat } from 'node:fs/promises'
-import { join, resolve } from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { isBuiltin } from 'node:module'
+import { dirname, join, resolve } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
 import { load } from 'js-yaml'
 import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
 import { expandHomePath } from '@deepseek-ai/dsh-home-paths'
 import { readPresetMetadata } from './metadata.ts'
 import { PRESET_ID, type AgentPreset, type PresetRoot } from './preset.ts'
+import { classifyRowSpecifier, type RowSpecifier } from './specifier.ts'
 
 /** The composition file that makes a directory a preset. */
 export const COMPOSITION_FILE = 'agent.cordis.yml'
@@ -84,15 +94,153 @@ function entryListProblem(rows: unknown, at = ''): string | undefined {
   return undefined
 }
 
+/**
+ * Whether a package name is installed anywhere above `base`.
+ *
+ * Node's own upward `node_modules` walk, stopping at the package directory:
+ * the question is whether the package is there at all, which is what a row
+ * naming a package a rename or an uninstall took away gets wrong. A pnpm
+ * store link answers through the symlink, and a link left dangling by a
+ * deleted checkout answers false — the shape a stale profile install leaves.
+ *
+ * `existsSync` rather than the async `stat`: the walk is a handful of lookups
+ * per package and runs on every roster read, where 150 promise round-trips
+ * cost more than the lookups they wrap.
+ * @param name - the package specifier, possibly carrying a subpath.
+ * @param base - the URL to walk up from.
+ * @returns true when the package directory is installed above `base`.
+ */
+function packageInstalled(name: string, base: string): boolean {
+  // A scoped name spends two segments on the package; anything after either
+  // form is a subpath export, which lives inside the package directory.
+  const pkg = name.split('/').slice(0, name.startsWith('@') ? 2 : 1).join('/')
+  let dir = fileURLToPath(base)
+  for (;;) {
+    if (existsSync(join(dir, 'node_modules', pkg, 'package.json'))) return true
+    const parent = dirname(dir)
+    if (parent === dir) return false
+    dir = parent
+  }
+}
+
+/**
+ * Package specifiers a resolver has already refused, keyed by base and name.
+ *
+ * Consulted only after {@link packageInstalled} finds nothing, which is what
+ * keeps a recorded refusal from going stale in the direction that matters: a
+ * package installed since is found on disk and never reaches this set, so
+ * fixing an install still takes effect on the next roster read. What it
+ * removes is the repeat cost of confirming the same absent name on every
+ * read, which a preset carrying several stale rows would otherwise pay
+ * forever.
+ */
+const refusedPackages = new Set<string>()
+
+/**
+ * Whether one classified row names a module that exists, importing nothing.
+ *
+ * Each kind is checked by what actually answers it. A package name is looked
+ * up on disk, then — only when that finds nothing — confirmed through
+ * `import.meta.resolve`, which is authoritative but expensive: a registered
+ * ESM loader hook turns each call into a synchronous round-trip to the hooks
+ * thread, measured at 2ms for a hit and 5ms for a miss under the `tsx` hook
+ * the source launch installs. Keeping it to the rows that look absent leaves
+ * a roster read paying for the failures it reports rather than for every row
+ * it clears, and keeps a package that only a loader can resolve — through
+ * tsconfig paths, or an import map — from being called broken.
+ *
+ * A relative or `file:` specifier is statted, because `import.meta.resolve`
+ * only joins URLs for those: a preset shipping a file that was deleted would
+ * otherwise pass. Nothing is evaluated either way, so a row is judged without
+ * its plugin observing that discovery looked.
+ * @param row - the classified specifier, from {@link classifyRowSpecifier}.
+ * @param presetBase - directory URL a preset-relative specifier resolves against.
+ * @param harnessBase - base URL a package name resolves against.
+ * @returns true when the row names something that can be imported.
+ */
+async function rowResolves(row: RowSpecifier, presetBase: string, harnessBase: string): Promise<boolean> {
+  if (row.kind === 'builtin') return true
+  if (row.kind === 'package') {
+    if (isBuiltin(row.specifier)) return true
+    if (packageInstalled(row.specifier, harnessBase)) return true
+    const refusal = `${harnessBase}\u0000${row.specifier}`
+    if (refusedPackages.has(refusal)) return false
+    try {
+      import.meta.resolve(row.specifier, harnessBase)
+      return true
+    } catch {
+      // Absent package, dangling install link, missing subpath export: every
+      // resolution failure is the same answer to the only question asked here,
+      // and the reason names the row rather than repeating the resolver's text.
+      refusedPackages.add(refusal)
+      return false
+    }
+  }
+  const url = row.kind === 'file' ? new URL(row.specifier) : new URL(row.specifier, presetBase)
+  return await isFile(fileURLToPath(url))
+}
+
+/** One row that names a module no resolver can find. */
+interface UnresolvableRow {
+  /** The row's own id in quotes, or its position when it declares none. */
+  readonly label: string
+  /** The specifier exactly as the row wrote it. */
+  readonly name: string
+}
+
+/**
+ * Rows whose module cannot be resolved.
+ *
+ * Only rows that will certainly be started are checked. `disabled` is the one
+ * entry field the Loader interpolates — a `!!js` expression evaluates against
+ * the loader context at mount time — so a row carrying anything but an absent,
+ * null, or `false` value cannot be proven to load from a file alone. Skipping
+ * those trades a missed name for the failure that matters more: calling a
+ * usable preset broken makes it unselectable and uncopyable, which is worse
+ * than reporting the same stale row at mount time as before.
+ *
+ * Shape is the caller's precondition: {@link entryListProblem} has already
+ * proven every row is a map carrying a `name` string, and groups recurse the
+ * same way it does.
+ * @param rows - the parsed composition rows.
+ * @param presetBase - directory URL a preset-relative specifier resolves against.
+ * @param harnessBase - base URL a package name resolves against.
+ * @param at - row-path prefix for nested diagnostics, empty at the top level.
+ * @returns one entry per unresolvable row, in composition order.
+ */
+async function unresolvableRows(
+  rows: readonly unknown[],
+  presetBase: string,
+  harnessBase: string,
+  at = '',
+): Promise<UnresolvableRow[]> {
+  const found: UnresolvableRow[] = []
+  for (const [index, entry] of rows.entries()) {
+    const row = entry as { id?: unknown; name: string; group?: unknown; config?: unknown; disabled?: unknown }
+    const { disabled } = row
+    if (disabled !== undefined && disabled !== null && disabled !== false) continue
+    const positional = at === '' ? `row ${String(index + 1)}` : `${at} row ${String(index + 1)}`
+    if (row.group === true) {
+      found.push(...await unresolvableRows(row.config as readonly unknown[], presetBase, harnessBase, positional))
+      continue
+    }
+    if (await rowResolves(classifyRowSpecifier(row.name), presetBase, harnessBase)) continue
+    const label = typeof row.id === 'string' && row.id !== '' ? `"${row.id}"` : positional
+    found.push({ label, name: row.name })
+  }
+  return found
+}
+
 /**
  * Why the composition at `path` cannot mount, or undefined when it looks
  * loadable. Parsed with the loader's own YAML dialect ({@link entryListSchema},
  * the one carrying `!!js`), so health can never call a composition broken
  * that the loader would accept.
  * @param path - absolute path of the composition file.
+ * @param harnessBase - base URL a row's package name resolves against.
  * @returns one human-readable reason, or undefined when the file is loadable.
  */
-async function compositionProblem(path: string): Promise<string | undefined> {
+async function compositionProblem(path: string, harnessBase: string): Promise<string | undefined> {
   let content: string
   try {
     content = await readFile(path, 'utf8')
@@ -111,7 +259,19 @@ async function compositionProblem(path: string): Promise<string | undefined> {
     // the reason is displayed on a roster card, not in a terminal.
     return `the composition is not valid YAML: ${full.replace(/\n[\s\S]*$/, '')}`
   }
-  return entryListProblem(rows)
+  const shape = entryListProblem(rows)
+  if (shape !== undefined) return shape
+  // The composition's own directory, exactly as `Include` derives it, so a
+  // row naming a file the preset ships resolves the way the mount will.
+  const presetBase = new URL('.', pathToFileURL(path)).href
+  const unresolvable = await unresolvableRows(rows as readonly unknown[], presetBase, harnessBase)
+  const [first] = unresolvable
+  if (first === undefined) return undefined
+  if (unresolvable.length === 1) {
+    return `row ${first.label} names a plugin that cannot be resolved: ${first.name}`
+  }
+  return `${String(unresolvable.length)} rows name plugins that cannot be resolved:\n`
+    + unresolvable.map(row => `- ${row.label}: ${row.name}`).join('\n')
 }
 
 /**
@@ -143,9 +303,11 @@ async function isFile(path: string): Promise<boolean> {
  * so it blocks nothing, and reporting `.DS_Store`-grade residue as broken
  * presets would teach users to ignore the marker.
  * @param root - the directory and the trust its presets inherit.
+ * @param harnessBase - base URL a row's package name resolves against; the
+ * caller's own `ctx.baseUrl`, which is where the installed harness lives.
  * @returns the root's presets ordered by id.
  */
-export async function scanRoot(root: PresetRoot): Promise<AgentPreset[]> {
+export async function scanRoot(root: PresetRoot, harnessBase: string): Promise<AgentPreset[]> {
   const dir = resolve(expandHomePath(root.path))
   let children
   try {
@@ -160,7 +322,7 @@ export async function scanRoot(root: PresetRoot): Promise<AgentPreset[]> {
     const directory = join(dir, child.name)
     const path = join(directory, COMPOSITION_FILE)
     const broken = await isFile(path)
-      ? await compositionProblem(path)
+      ? await compositionProblem(path, harnessBase)
       : `the composition file ${COMPOSITION_FILE} is missing — the directory still occupies the id; delete it or restore the file`
     // Display text only, and never fatal: a preset with unreadable metadata
     // still mounts, it just shows its id.
@@ -181,12 +343,16 @@ export async function scanRoot(root: PresetRoot): Promise<AgentPreset[]> {
 /**
  * Scan every root in precedence order.
  * @param roots - roots in precedence order; an earlier root wins a duplicate id.
+ * @param harnessBase - base URL a row's package name resolves against.
  * @returns every discovered preset, first-root-wins per id.
  */
-export async function discoverPresets(roots: readonly PresetRoot[]): Promise<AgentPreset[]> {
+export async function discoverPresets(
+  roots: readonly PresetRoot[],
+  harnessBase: string,
+): Promise<AgentPreset[]> {
   const byId = new Map<string, AgentPreset>()
   for (const root of roots) {
-    for (const preset of await scanRoot(root)) {
+    for (const preset of await scanRoot(root, harnessBase)) {
       if (byId.has(preset.id)) continue
       byId.set(preset.id, preset)
     }

+ 25 - 1
packages/preset/agent-presets/src/index.ts

@@ -111,6 +111,18 @@ export class AgentPresets extends Service {
    */
   private readonly resolvedRoots: readonly PresetRoot[]
 
+  /**
+   * Where a row's package name resolves from: the base URL of the composition
+   * this roster was loaded by, which is inside the installed harness.
+   *
+   * Discovery needs it because a preset's own directory is the wrong base for
+   * a package name — a locally authored preset lives under the user's home,
+   * where Node's upward `node_modules` walk never reaches the harness's
+   * dependencies. The mount already resolves rows this way; holding the same
+   * base here is what lets health answer the question before a session does.
+   */
+  private readonly harnessBase: string
+
   /**
    * The user layer over `config.default`, present only while a settings
    * provider is composed. Held rather than snapshotted so a hot-reloaded
@@ -137,6 +149,18 @@ export class AgentPresets extends Service {
   constructor(ctx: Context, public config: Config) {
     super(ctx, 'agentPresets')
     this.selfCtx = ctx
+    const { baseUrl } = ctx
+    if (baseUrl === undefined) {
+      // Self-contained misconfiguration, so it fails at load: without a base
+      // the roster can neither resolve a row nor tell a healthy preset from
+      // one naming a package that is gone, and the silent alternative is the
+      // exact failure this check exists to report.
+      throw new Error(
+        'agent-presets: the roster needs `ctx.baseUrl` to resolve the plugins a composition names; '
+        + 'compose it under a Loader, or set the base on the context this plugin is applied to',
+      )
+    }
+    this.harnessBase = baseUrl
     this.resolvedRoots = [
       ...config.includeShippedRoot ? [{ path: SHIPPED_PRESET_ROOT, trust: 'system' } satisfies PresetRoot] : [],
       ...config.roots,
@@ -210,7 +234,7 @@ export class AgentPresets extends Service {
    * @returns the presets, first-root-wins per id.
    */
   async list(): Promise<AgentPreset[]> {
-    return await discoverPresets(this.resolvedRoots)
+    return await discoverPresets(this.resolvedRoots, this.harnessBase)
   }
 
   /**

+ 37 - 9
packages/preset/agent-presets/src/mount.ts

@@ -14,13 +14,13 @@
  * @module @deepseek-ai/dsh-agent-presets/mount
  */
 
-import { isAbsolute } from 'node:path'
 import { pathToFileURL } from 'node:url'
 import { Context, type Fiber } from '@deepseek-ai/cordis'
 import { Include } from '@deepseek-ai/cordis-plugin-include'
 import type { EntryTree } from '@deepseek-ai/cordis-plugin-loader'
 import { scopeOf, scopeParentOf, type ScopeKey } from '@deepseek-ai/dsh-scope'
 import { PresetMountError, type AgentPreset } from './preset.ts'
+import { classifyRowSpecifier } from './specifier.ts'
 
 /** What one mounted subtree publishes about itself for the audit to read. */
 interface MountedTree {
@@ -74,21 +74,24 @@ class PresetTree extends Include {
    * filesystem path names neither base and becomes a file URL before Node's
    * ESM loader receives it, which is required for drive-letter paths on
    * Windows.
+   *
+   * {@link classifyRowSpecifier} makes that split, so discovery's health check
+   * resolves every row from the same base this import uses.
    * @param name - the module specifier from the row.
    * @param getOuterStack - the loader's stack composer for import diagnostics.
    * @returns the imported module, or the `cordis:` builtin.
    */
   override import(name: string, getOuterStack?: () => string[]): unknown {
-    const specifier = isAbsolute(name) ? pathToFileURL(name).href : name
+    const row = classifyRowSpecifier(name)
     const base = harnessBase.get(this.config)
     /* v8 ignore next -- every PresetTree is constructed by `mountPreset`, which records the base first */
-    if (base === undefined) return super.import(specifier, getOuterStack)
-    if (name.startsWith('.') || name.startsWith('cordis:')) return super.import(name, getOuterStack)
+    if (base === undefined) return super.import(row.specifier, getOuterStack)
+    if (row.kind === 'builtin' || row.kind === 'preset') return super.import(row.specifier, getOuterStack)
     const internal = this.ctx.loader.internal
     /* v8 ignore next -- Node always supplies the internal module loader; the branch keeps a
        hypothetical embedder from losing the row's name in a resolution error. */
-    if (internal === undefined) return super.import(specifier, getOuterStack)
-    return internal.import(specifier, base, {})
+    if (internal === undefined) return super.import(row.specifier, getOuterStack)
+    return internal.import(row.specifier, base, {})
   }
 
   /**
@@ -302,13 +305,34 @@ export function inactiveRows(tree: EntryTree): string[] {
   return lines
 }
 
+/**
+ * The causes of `error` whose detail its own message does not already carry.
+ *
+ * `AggregateError` names none of its causes in its own message, so its
+ * `errors` are the branches. The Loader's per-row wrapper takes the opposite
+ * approach: it appends `cause.message` to the message it builds and keeps the
+ * cause only as `error.cause`, so following a plain chain would print every
+ * line twice. That leaves exactly one lossy shape — a wrapped row whose cause
+ * is an `AggregateError`. Its message ends with the aggregate's own line and
+ * drops the `errors` behind it, which is how a failed group reports as
+ * "loader entries failed to apply" and names none of the rows that failed.
+ * @param error - the failure to read branches from.
+ * @returns the branches to render beneath `error.message`, possibly empty.
+ */
+function detailBranches(error: Error): readonly unknown[] {
+  if (error instanceof AggregateError) return error.errors
+  return error.cause instanceof AggregateError ? error.cause.errors : []
+}
+
 /**
  * The reportable text of a mount failure.
  *
  * The loader reports several failed rows as one `AggregateError`, whose own
  * message names none of them; without flattening, a composition that fails on
  * two rows says only "loader entries failed to apply" and the operator has
- * nothing to act on.
+ * nothing to act on. Nested groups indent under the row that owns them, so a
+ * composition failing inside a group still names the rows rather than the
+ * group alone.
  * @param error - the value the mount rejected with.
  * @returns a single-line-per-cause description.
  */
@@ -317,8 +341,12 @@ function mountDetail(error: unknown): string {
      wraps a row's thrown value before it propagates, and this module's own
      rejections are Errors. The fallback keeps a hostile value readable. */
   if (!(error instanceof Error)) return String(error)
-  if (!(error instanceof AggregateError)) return error.message
-  return [error.message, ...error.errors.map(cause => `- ${mountDetail(cause)}`)].join('\n')
+  const branches = detailBranches(error)
+  if (branches.length === 0) return error.message
+  return [
+    error.message,
+    ...branches.map(branch => `- ${mountDetail(branch).replaceAll('\n', '\n  ')}`),
+  ].join('\n')
 }
 
 /**

+ 45 - 0
packages/preset/agent-presets/src/specifier.ts

@@ -0,0 +1,45 @@
+/**
+ * How one composition row's `name` reaches a module.
+ *
+ * A preset composition is read by `Include`, which rewrites its context's
+ * `baseUrl` to the composition's own directory. That is right for a row
+ * naming a file the preset ships and wrong for a row naming a package: a
+ * locally authored preset lives under the user's home, where Node's upward
+ * `node_modules` walk never reaches the harness's own dependencies. Both the
+ * mount's import override and discovery's health check therefore have to
+ * classify a row's name before they can act on it, and they must classify it
+ * the same way — a row discovery resolves from one base and the mount imports
+ * from another would be reported healthy and then fail to load.
+ * @module @deepseek-ai/dsh-agent-presets/specifier
+ */
+
+import { isAbsolute } from 'node:path'
+import { pathToFileURL } from 'node:url'
+
+/** One composition row's module specifier, classified by where it resolves. */
+export type RowSpecifier =
+  /** A `cordis:` builtin the Loader supplies; nothing is resolved. */
+  | { readonly kind: 'builtin'; readonly specifier: string }
+  /** A path relative to the preset's own directory; the preset ships the file. */
+  | { readonly kind: 'preset'; readonly specifier: string }
+  /** An absolute path, already a file URL; it names one file and no base. */
+  | { readonly kind: 'file'; readonly specifier: string }
+  /** A package name resolved from the installed harness. */
+  | { readonly kind: 'package'; readonly specifier: string }
+
+/**
+ * Classify one row's `name`.
+ *
+ * An absolute filesystem path becomes a file URL here rather than at each
+ * call site, because Node's ESM resolver rejects a bare drive-letter path on
+ * Windows. The `specifier` a caller receives is always the string to hand a
+ * resolver; only `kind` decides which base it goes with.
+ * @param name - the module specifier exactly as the row wrote it.
+ * @returns the classification, carrying the specifier to resolve.
+ */
+export function classifyRowSpecifier(name: string): RowSpecifier {
+  if (name.startsWith('cordis:')) return { kind: 'builtin', specifier: name }
+  if (name.startsWith('.')) return { kind: 'preset', specifier: name }
+  if (isAbsolute(name)) return { kind: 'file', specifier: pathToFileURL(name).href }
+  return { kind: 'package', specifier: name }
+}

+ 6 - 1
packages/preset/agent-presets/tests/authoring.spec.ts

@@ -303,6 +303,11 @@ describe('a ghost directory under the user root', () => {
     await ctx.agentPresets.remove('ghost')
     expect(existsSync(join(userRoot, 'ghost'))).toBe(false)
     await ctx.agentPresets.copy('standard', 'ghost')
-    expect((await ctx.agentPresets.list()).find(preset => preset.id === 'ghost')?.broken).toBeUndefined()
+    expect((await ctx.agentPresets.list()).map(preset => preset.id)).toContain('ghost')
+    // A copy carries the whole preset directory, so a preset's own files
+    // travel with it. This fixture's rows reach OUTSIDE that directory, which
+    // no real preset does and which no copy can carry — so the claim here is
+    // the reclaimed id and the restored composition, not the rows' targets.
+    expect(existsSync(join(userRoot, 'ghost', COMPOSITION_FILE))).toBe(true)
   })
 })

+ 142 - 19
packages/preset/agent-presets/tests/discovery.spec.ts

@@ -1,7 +1,7 @@
-import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'
+import { mkdtemp, mkdir, symlink, writeFile } from 'node:fs/promises'
 import { tmpdir } from 'node:os'
 import { dirname, join } from 'node:path'
-import { fileURLToPath } from 'node:url'
+import { fileURLToPath, pathToFileURL } from 'node:url'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 import { COMPOSITION_FILE, discoverPresets, scanRoot } from '@deepseek-ai/dsh-agent-presets'
 
@@ -25,6 +25,9 @@ vi.mock('node:fs/promises', async (importOriginal) => {
 })
 
 const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), 'fixtures')
+// Standing in for the installed harness: a row's package name resolves from
+// here, and this directory's upward `node_modules` walk reaches the workspace.
+const HARNESS = new URL('.', import.meta.url).href
 const SYSTEM = { path: join(FIXTURES, 'system'), trust: 'system' as const }
 const USER = { path: join(FIXTURES, 'user'), trust: 'user' as const }
 
@@ -45,7 +48,7 @@ describe('display order', () => {
       await writeFile(join(root, id, COMPOSITION_FILE), '[]\n')
     }
 
-    const found = await scanRoot({ path: root, trust: 'system' })
+    const found = await scanRoot({ path: root, trust: 'system' }, HARNESS)
 
     // The shipped set reads by capability; presets that declare nothing stay
     // alphabetical behind them rather than interleaving unpredictably.
@@ -60,7 +63,7 @@ describe('display order', () => {
       await writeFile(join(root, id, 'preset.yml'), 'order: 1\n')
     }
 
-    const found = await scanRoot({ path: root, trust: 'system' })
+    const found = await scanRoot({ path: root, trust: 'system' }, HARNESS)
 
     // Two presets claiming the same slot must still list in a stable order:
     // a directory-scan order would reshuffle the picker between reads.
@@ -70,7 +73,7 @@ describe('display order', () => {
 
 describe('preset discovery', () => {
   it('reports one preset per directory holding a composition, ordered by id', async () => {
-    const found = await scanRoot(SYSTEM)
+    const found = await scanRoot(SYSTEM, HARNESS)
 
     expect(found.map(preset => preset.id)).toEqual(['minimal', 'standard'])
     expect(found[0]).toEqual({
@@ -81,7 +84,7 @@ describe('preset discovery', () => {
   })
 
   it('reports a directory with no composition as a broken preset slot', async () => {
-    const found = await scanRoot(USER)
+    const found = await scanRoot(USER, HARNESS)
 
     // The directory still occupies its id — a copy to that name is refused —
     // so hiding it would leave nothing to see or delete. It surfaces broken.
@@ -96,7 +99,7 @@ describe('preset discovery', () => {
     await mkdir(join(root, 'usable'))
     await writeFile(join(root, 'usable', COMPOSITION_FILE), '[]\n')
 
-    const found = await scanRoot({ path: root, trust: 'user' })
+    const found = await scanRoot({ path: root, trust: 'user' }, HARNESS)
 
     // `.hidden` and `Has_Caps` cannot collide with any copy target, so
     // reporting tool residue as broken presets would only train users to
@@ -105,13 +108,13 @@ describe('preset discovery', () => {
   })
 
   it('records the root trust on every preset it discovers', async () => {
-    const found = await scanRoot(USER)
+    const found = await scanRoot(USER, HARNESS)
 
     expect(found.every(preset => preset.trust === 'user')).toBe(true)
   })
 
   it('lets the earlier root win a duplicate id', async () => {
-    const found = await discoverPresets([SYSTEM, USER])
+    const found = await discoverPresets([SYSTEM, USER], HARNESS)
 
     const standard = found.filter(preset => preset.id === 'standard')
     expect(standard).toHaveLength(1)
@@ -119,7 +122,7 @@ describe('preset discovery', () => {
   })
 
   it('treats an absent root as supplying no presets', async () => {
-    const found = await scanRoot({ path: join(FIXTURES, 'no-such-root'), trust: 'user' })
+    const found = await scanRoot({ path: join(FIXTURES, 'no-such-root'), trust: 'user' }, HARNESS)
 
     expect(found).toEqual([])
   })
@@ -130,7 +133,7 @@ describe('preset discovery', () => {
     await mkdir(join(root, 'real'))
     await writeFile(join(root, 'real', COMPOSITION_FILE), '[]\n')
 
-    const found = await scanRoot({ path: root, trust: 'user' })
+    const found = await scanRoot({ path: root, trust: 'user' }, HARNESS)
 
     expect(found.map(preset => preset.id)).toEqual(['real'])
   })
@@ -140,26 +143,34 @@ describe('preset discovery', () => {
     const notADirectory = join(root, 'file-as-root')
     await writeFile(notADirectory, 'not a directory\n')
 
-    await expect(scanRoot({ path: notADirectory, trust: 'user' }))
+    await expect(scanRoot({ path: notADirectory, trust: 'user' }, HARNESS))
       .rejects.toThrow(/cannot read preset root/)
   })
 
   it('expands a leading tilde in a root path', async () => {
     // `~` alone resolves to the home directory, which exists but holds no
     // preset directories; the point is that it did not throw on a literal `~`.
-    const found = await scanRoot({ path: '~/.dsh-agent-presets-absent', trust: 'user' })
+    const found = await scanRoot({ path: '~/.dsh-agent-presets-absent', trust: 'user' }, HARNESS)
 
     expect(found).toEqual([])
   })
 })
 
 describe('composition health', () => {
-  /** One directory under a fresh root holding `composition`, scanned. */
+  /**
+   * One directory under a fresh root holding `composition`, scanned.
+   *
+   * Rows that exist only to carry a shape name `js-yaml`, a package the
+   * harness base really resolves: health resolves every enabled row's module,
+   * so an invented name would answer the wrong check.
+   * @param composition - the composition file's contents.
+   * @returns the reported reason, or undefined when the composition is healthy.
+   */
   async function scanned(composition: string): Promise<string | undefined> {
     const root = await mkdtemp(join(tmpdir(), 'dsh-presets-health-'))
     await mkdir(join(root, 'probe'))
     await writeFile(join(root, 'probe', COMPOSITION_FILE), composition)
-    const [preset] = await scanRoot({ path: root, trust: 'user' })
+    const [preset] = await scanRoot({ path: root, trust: 'user' }, HARNESS)
     return preset?.broken
   }
 
@@ -172,7 +183,7 @@ describe('composition health', () => {
   })
 
   it('reports the first row that names no plugin, by position', async () => {
-    expect(await scanned('- id: ok\n  name: some-plugin\n- id: broken\n'))
+    expect(await scanned('- id: ok\n  name: js-yaml\n- id: broken\n'))
       .toMatch(/row 2 names no plugin/)
   })
 
@@ -191,7 +202,7 @@ describe('composition health', () => {
   })
 
   it('accepts a group whose own list is healthy', async () => {
-    const composition = '- id: grp\n  name: cordis:group\n  group: true\n  config:\n    - id: inner\n      name: some-plugin\n'
+    const composition = '- id: grp\n  name: cordis:group\n  group: true\n  config:\n    - id: inner\n      name: js-yaml\n'
     expect(await scanned(composition)).toBeUndefined()
   })
 
@@ -202,7 +213,7 @@ describe('composition health', () => {
     await writeFile(path, '[]\n')
     fsHarness.nextReadError = Object.assign(new Error('EACCES: injected read failure'), { code: 'EACCES' })
 
-    const [preset] = await scanRoot({ path: root, trust: 'user' })
+    const [preset] = await scanRoot({ path: root, trust: 'user' }, HARNESS)
 
     expect(fsHarness.nextReadError).toBeUndefined()
     expect(preset?.broken).toMatch(/cannot be read/)
@@ -211,7 +222,7 @@ describe('composition health', () => {
   it('accepts the loader dialect, !!js scalars included', async () => {
     // Health must never call a composition broken that the loader accepts:
     // `!!js` is the loader's own extension, so it parses here too.
-    const composition = '- id: x\n  name: some-plugin\n  config:\n    value: !!js "1 + 1"\n'
+    const composition = '- id: x\n  name: js-yaml\n  config:\n    value: !!js "1 + 1"\n'
     expect(await scanned(composition)).toBeUndefined()
   })
 
@@ -219,3 +230,115 @@ describe('composition health', () => {
     expect(await scanned('[]\n')).toBeUndefined()
   })
 })
+
+describe('rows naming a plugin that cannot be resolved', () => {
+  /** One directory under a fresh root holding `composition`, scanned. */
+  async function scanned(composition: string): Promise<string | undefined> {
+    const root = await mkdtemp(join(tmpdir(), 'dsh-presets-resolve-'))
+    await mkdir(join(root, 'probe'))
+    await writeFile(join(root, 'probe', COMPOSITION_FILE), composition)
+    const [preset] = await scanRoot({ path: root, trust: 'user' }, HARNESS)
+    return preset?.broken
+  }
+
+  it('reports a package the harness cannot resolve, with the row and the name', async () => {
+    // The way an authored preset actually rots: it named a package that a
+    // later release renamed, so the composition still parses and still cannot
+    // compose a session.
+    expect(await scanned('- id: stale\n  name: \'@deepseek-ai/dsh-no-such-package\'\n'))
+      .toBe('row "stale" names a plugin that cannot be resolved: @deepseek-ai/dsh-no-such-package')
+  })
+
+  it('names every unresolvable row rather than only the first', async () => {
+    // Unlike a parse failure, one unresolvable name tells you nothing about
+    // the next: fixing them one reload at a time is the avoidable part.
+    const composition = '- id: a\n  name: no-such-a\n- id: b\n  name: no-such-b\n'
+
+    expect(await scanned(composition)).toBe(
+      '2 rows name plugins that cannot be resolved:\n- "a": no-such-a\n- "b": no-such-b')
+  })
+
+  it('falls back to the row position when a row declares no id', async () => {
+    expect(await scanned('- name: no-such-plugin\n'))
+      .toMatch(/^row row 1 names a plugin/)
+  })
+
+  it('descends into a group and keeps the group in the label', async () => {
+    const composition = '- id: grp\n  name: cordis:group\n  group: true\n  config:\n    - name: no-such-plugin\n'
+
+    expect(await scanned(composition)).toMatch(/row 1 row 1 names a plugin that cannot be resolved/)
+  })
+
+  it('resolves a preset-relative row against the preset\'s own directory', async () => {
+    const root = await mkdtemp(join(tmpdir(), 'dsh-presets-relative-'))
+    await mkdir(join(root, 'probe'))
+    await writeFile(join(root, 'probe', 'own-plugin.mjs'), 'export function apply() {}\n')
+    await writeFile(join(root, 'probe', COMPOSITION_FILE), '- id: own\n  name: ./own-plugin.mjs\n- id: gone\n  name: ./deleted.mjs\n')
+
+    const [preset] = await scanRoot({ path: root, trust: 'user' }, HARNESS)
+
+    // A file the preset ships resolves beside its composition, not from the
+    // harness — the same split the mount's import override makes.
+    expect(preset?.broken).toBe('row "gone" names a plugin that cannot be resolved: ./deleted.mjs')
+  })
+
+  it('skips a row the loader may never start', async () => {
+    // `disabled` is the one entry field the Loader interpolates, so a `!!js`
+    // row cannot be judged from the file; calling a usable preset broken is
+    // worse than leaving a switched-off row to fail at mount as before.
+    const composition = '- id: off\n  name: no-such-plugin\n  disabled: true\n'
+      + '- id: maybe\n  name: no-such-either\n  disabled: !!js process.platform === \'win32\'\n'
+
+    expect(await scanned(composition)).toBeUndefined()
+  })
+
+  it('checks a row that says it is enabled', async () => {
+    expect(await scanned('- id: on\n  name: no-such-plugin\n  disabled: false\n'))
+      .toMatch(/cannot be resolved/)
+  })
+
+  it('reads an installed package off disk without asking the resolver', async () => {
+    // The fast path, and the one that has to answer alone: this package has a
+    // directory and nothing to import, so a resolver would reject it.
+    const home = await mkdtemp(join(tmpdir(), 'dsh-presets-installed-'))
+    await mkdir(join(home, 'node_modules', '@scope', 'pkg'), { recursive: true })
+    await writeFile(join(home, 'node_modules', '@scope', 'pkg', 'package.json'), '{"name":"@scope/pkg"}\n')
+    await mkdir(join(home, 'presets', 'probe'), { recursive: true })
+    await writeFile(join(home, 'presets', 'probe', COMPOSITION_FILE), "- id: p\n  name: '@scope/pkg'\n")
+
+    const [preset] = await scanRoot(
+      { path: join(home, 'presets'), trust: 'user' }, pathToFileURL(join(home, 'app/')).href)
+
+    expect(preset?.broken).toBeUndefined()
+  })
+
+  it('reports a package whose install link dangles', async () => {
+    // What a stale profile install leaves behind: the name is still in
+    // `node_modules`, pointing at a checkout that is gone.
+    const home = await mkdtemp(join(tmpdir(), 'dsh-presets-dangling-'))
+    await mkdir(join(home, 'node_modules', '@scope'), { recursive: true })
+    await symlink(join(home, 'deleted-checkout'), join(home, 'node_modules', '@scope', 'pkg'))
+    await mkdir(join(home, 'presets', 'probe'), { recursive: true })
+    await writeFile(join(home, 'presets', 'probe', COMPOSITION_FILE), "- id: p\n  name: '@scope/pkg'\n")
+
+    const [preset] = await scanRoot(
+      { path: join(home, 'presets'), trust: 'user' }, pathToFileURL(join(home, 'app/')).href)
+
+    expect(preset?.broken).toBe('row "p" names a plugin that cannot be resolved: @scope/pkg')
+  })
+
+  it('leaves a node builtin alone', async () => {
+    // Nothing installs `node:fs`, so the disk walk finds nothing; calling a
+    // composition broken over a name Node always supplies would be a false
+    // report, which costs more than the row it would have caught.
+    expect(await scanned('- id: b\n  name: node:fs\n')).toBeUndefined()
+  })
+
+  it('leaves a cordis builtin alone', async () => {
+    // A `cordis:` name is supplied by the Loader itself, so there is nothing
+    // to resolve — as a row of its own, and as the group it recurses into.
+    expect(await scanned('- id: inc\n  name: cordis:include\n  config:\n    path: ./nested.cordis.yml\n'))
+      .toBeUndefined()
+    expect(await scanned('- id: grp\n  name: cordis:group\n  group: true\n  config: []\n')).toBeUndefined()
+  })
+})

+ 9 - 0
packages/preset/agent-presets/tests/fixtures/plugins/throws.js

@@ -0,0 +1,9 @@
+// A row that resolves and then refuses to apply. Discovery's health check
+// resolves every row's module without importing it, so a fixture naming a file
+// that does not exist can no longer reach the mount; a module that loads and
+// throws is what still exercises the loader's own failure reporting.
+export const name = 'throws'
+
+export function apply(_ctx, config) {
+  throw new Error(config.message)
+}

+ 4 - 2
packages/preset/agent-presets/tests/fixtures/user/broken/agent.cordis.yml

@@ -2,5 +2,7 @@
   name: ../../plugins/contribute.js
   config:
     tool: ok
-- id: missing
-  name: ../../plugins/does-not-exist.js
+- id: refuses
+  name: ../../plugins/throws.js
+  config:
+    message: this row refuses to apply

+ 16 - 0
packages/preset/agent-presets/tests/fixtures/user/nested-broken/agent.cordis.yml

@@ -0,0 +1,16 @@
+# Two failing rows inside a group. The Loader wraps the group's own
+# AggregateError into a plain Error carrying only its message, so without
+# following `cause` the diagnostic ends at "loader entries failed to apply" and
+# names neither row.
+- id: outer
+  name: cordis:group
+  group: true
+  config:
+    - id: inner-first
+      name: ../../plugins/throws.js
+      config:
+        message: inner first refuses
+    - id: inner-second
+      name: ../../plugins/throws.js
+      config:
+        message: inner second refuses

+ 9 - 5
packages/preset/agent-presets/tests/fixtures/user/two-broken/agent.cordis.yml

@@ -1,7 +1,11 @@
-# Two rows that cannot load: the Loader reports several failed entries as one
+# Two rows that cannot apply: the Loader reports several failed entries as one
 # AggregateError whose own message names none of them, so this fixture is what
 # proves the mount diagnostic flattens the causes.
-- id: first-missing
-  name: ../../plugins/does-not-exist.js
-- id: second-missing
-  name: ../../plugins/also-missing.js
+- id: first-refuses
+  name: ../../plugins/throws.js
+  config:
+    message: first row refuses
+- id: second-refuses
+  name: ../../plugins/throws.js
+  config:
+    message: second row refuses

+ 35 - 3
packages/preset/agent-presets/tests/mount.spec.ts

@@ -5,6 +5,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
 import { Context } from '@deepseek-ai/cordis'
 import Loader from '@deepseek-ai/cordis-plugin-loader'
 import Include from '@deepseek-ai/cordis-plugin-include'
+import Group from '@deepseek-ai/cordis-plugin-group'
 import LlmRuntime from '@deepseek-ai/dsh-llm'
 import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
 import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
@@ -43,6 +44,10 @@ async function harness(roster: Config = { default: 'standard', roots: ROOTS, inc
   ctx.baseUrl = pathToFileURL(FIXTURES).href + '/'
   await ctx.plugin(Loader)
   ctx.loader.builtins.include = Include
+  // A preset outside this workspace cannot resolve `cordis-plugin-group` by
+  // name, so the app registers it as a builtin; the fixtures compose the same
+  // way real presets do, which needs it here too.
+  ctx.loader.builtins.group = Group
   await ctx.plugin(LlmRuntime)
   await ctx.plugin(SessionStore)
   await ctx.plugin(SystemPrompt, { persona: '' })
@@ -244,7 +249,16 @@ describe('rejecting a composition that cannot be used', () => {
     // message names none of them; unflattened, the operator is told only that
     // "loader entries failed to apply" and has nothing to act on.
     await expect(agentOn(ctx, 'sess-two-broken', 'two-broken'))
-      .rejects.toThrow(/first-missing[\s\S]*second-missing/)
+      .rejects.toThrow(/first-refuses[\s\S]*second-refuses/)
+  })
+
+  it('names the rows inside a failed group, not the group alone', async () => {
+    // The Loader's per-row wrapper keeps only `cause.message`, so a group's
+    // own AggregateError arrives with its `errors` reachable through `cause`
+    // alone. Reading the message stops at "loader entries failed to apply"
+    // and names neither row that actually refused.
+    await expect(agentOn(ctx, 'sess-nested-broken', 'nested-broken'))
+      .rejects.toThrow(/outer[\s\S]*inner-first[\s\S]*inner-second/)
   })
 
   it('names the unresolved service when a row never activates', async () => {
@@ -330,7 +344,7 @@ describe('the preset roster', () => {
 
     // `not-a-preset` is the fixture ghost: no composition file, listed broken.
     expect(listed.map(preset => preset.id).sort())
-      .toEqual(['broken', 'isolated', 'late', 'leaky', 'minimal', 'not-a-preset', 'pending', 'standard', 'two-broken'])
+      .toEqual(['broken', 'isolated', 'late', 'leaky', 'minimal', 'nested-broken', 'not-a-preset', 'pending', 'standard', 'two-broken'])
     expect(listed.find(preset => preset.id === 'standard')?.trust).toBe('system')
     expect(listed.find(preset => preset.id === 'not-a-preset')?.broken).toMatch(/is missing/)
   })
@@ -378,6 +392,7 @@ describe('composing from a broken preset', () => {
 describe('a roster with nothing in it', () => {
   it('says so instead of naming an empty list of candidates', async () => {
     const bare = new Context()
+    bare.baseUrl = pathToFileURL(FIXTURES).href + '/'
     await bare.plugin(Loader)
     await bare.plugin(AgentPresets, { default: 'standard', roots: [], includeShippedRoot: false, includeUserRoot: false })
 
@@ -386,6 +401,21 @@ describe('a roster with nothing in it', () => {
   })
 })
 
+describe('a roster with no base to resolve from', () => {
+  it('refuses at load rather than calling every preset broken', async () => {
+    // Health answers "can this row be imported?", and the same package name
+    // fails from a preset's own directory while resolving from the installed
+    // harness. Without the base there is no answer, and the silent one is
+    // exactly the failure the check exists to report.
+    const baseless = new Context()
+    await baseless.plugin(Loader)
+
+    await expect(baseless.plugin(AgentPresets, {
+      default: 'standard', roots: ROOTS, includeShippedRoot: false, includeUserRoot: false,
+    })).rejects.toThrow(/needs `ctx\.baseUrl`/)
+  })
+})
+
 describe('the preset file is an input, never a persistence target', () => {
   it('survives a row that disposes itself, which makes the Loader persist a tree', async () => {
     // The preset lives in a temp root, not under `fixtures/`: without the
@@ -411,6 +441,7 @@ describe('the preset file is an input, never a persistence target', () => {
     scoped.baseUrl = pathToFileURL(FIXTURES).href + '/'
     await scoped.plugin(Loader)
     scoped.loader.builtins.include = Include
+    scoped.loader.builtins.group = Group
     await scoped.plugin(LlmRuntime)
     await scoped.plugin(SessionStore)
     await scoped.plugin(SystemPrompt, { persona: '' })
@@ -588,7 +619,7 @@ describe('replacing a composition', () => {
     // A preset root this test owns, so removing the composition mid-flight
     // cannot disturb the shipped fixtures.
     const root = await mkdtemp(join(tmpdir(), 'dsh-preset-restore-'))
-    const seeded: [string, string][] = [['first', `- id: only\n  name: ${join(FIXTURES, 'plugins', 'contribute.js')}\n  config:\n    tool: only\n`], ['broken', '- id: nope\n  name: ./does-not-exist.js\n']]
+    const seeded: [string, string][] = [['first', `- id: only\n  name: ${join(FIXTURES, 'plugins', 'contribute.js')}\n  config:\n    tool: only\n`], ['broken', `- id: nope\n  name: ${join(FIXTURES, 'plugins', 'throws.js')}\n  config:\n    message: refuses\n`]]
     for (const [id, body] of seeded) {
       await mkdir(join(root, id))
       await writeFile(join(root, id, COMPOSITION_FILE), body)
@@ -597,6 +628,7 @@ describe('replacing a composition', () => {
     scoped.baseUrl = pathToFileURL(FIXTURES).href + '/'
     await scoped.plugin(Loader)
     scoped.loader.builtins.include = Include
+    scoped.loader.builtins.group = Group
     await scoped.plugin(LlmRuntime)
     await scoped.plugin(SessionStore)
     await scoped.plugin(SystemPrompt, { persona: '' })

+ 7 - 1
packages/preset/agent-presets/tests/shipped-root.spec.ts

@@ -58,7 +58,13 @@ describe('the shipped preset root', () => {
     const listed = await ctx.agentPresets.list()
     expect(listed.map(preset => preset.id).sort()).toEqual(['code', 'cordis', 'minimal', 'standard'])
     expect(listed.every(preset => preset.trust === 'system')).toBe(true)
-    expect(listed.every(preset => preset.broken === undefined)).toBe(true)
+    // Not `broken === undefined`: health asks whether each row's package is
+    // installed above the base, and the shipped rows name packages the
+    // deployment installs beside the roster. This fixture base is not that
+    // install, so unresolved rows are the only reason it can report here —
+    // malformed would be a different one, and this asserts there is none.
+    expect(listed.map(preset => preset.broken)
+      .filter(reason => reason !== undefined && !reason.includes('cannot be resolved'))).toEqual([])
   })
 
   it('prepends the shipped root before configured roots and the derived user root', async () => {

+ 3 - 0
pnpm-lock.yaml

@@ -6524,6 +6524,9 @@ importers:
       '@deepseek-ai/cordis':
         specifier: workspace:^
         version: link:../../../vendor/cordis
+      '@deepseek-ai/cordis-plugin-group':
+        specifier: workspace:^
+        version: link:../../../vendor/group
       '@deepseek-ai/cordis-plugin-include':
         specifier: workspace:^
         version: link:../../../vendor/include