@suifei/dsh-ai-team 0.4.152 → 0.4.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.154 - 2026-12-03
4
+
5
+ - 新建和编辑项目可用宿主的浏览式目录列表。选定后回填路径,提交表单时才保存或创建项目。感谢 @ljyzww 提供 Windows 复现与宿主契约(#100)。
6
+ - 桌面首次安装说明明确初始化后先退出应用,再安装到内置 `desktop` profile。感谢 @Arnoldnuo 的桌面安装反馈(#102)。
7
+ - 编制巡检列出缺少合格验收人的任务、宿主回合观察值和容量来源。补位建议按每张卡的实际验收资格判断能否恢复现有成员或需要补位。感谢 @buger-gif 的现场案例和巡检建议(#116)。
8
+
9
+ ## 0.4.153 - 2026-12-03
10
+
11
+ - 看板的受阻徽标、读屏名称和分组计数使用宿主提供的当前受阻状态,依赖编号保持可查。感谢 @idontlikefruit 提供复现(#115)。
12
+ - 把离队、退役和任务认领放到同一队列,执行时核查成员状态。先认领的任务进入交接清单,先离队的成员不能再认领。感谢 @buger-gif 提供现场线索(#116、#117)。
13
+ - 普通项目可选择试跑只读编制巡检,记录岗位队列、等待和实际返工样本,复用现有派员建议。感谢 @buger-gif 提供试跑建议(#116)。
14
+ - PMO 派发和任务认领共用依赖、写入范围和在手任务检查。同一接收人的重复补派会退避,改派后重新判定。感谢 @buger-gif 提供空转记录(#120)。
15
+ - 兼容 DSH 0.2.3 的 `Connection.admit()`。工作台收到已验证的会话才能处理请求,早期宿主继续使用原鉴权接口。感谢 @Estelle00 提供复现、版本差异和桌面验证(#122)。
16
+
3
17
  ## 0.4.152 - 2026-12-02
4
18
 
5
19
  - 修复 PMO 冷恢复时缺少 `provider` 和 `model` 导致首轮请求失败。恢复原会话时一并传入默认模型和推理等级,宿主可继续沿用已保存的模型选择。原 PMO 会话、成员关系和任务可继续使用。感谢 @phm101299-ui 提供复现、根因和桌面验证(#112)。
package/README.md CHANGED
@@ -22,9 +22,9 @@
22
22
  > [!IMPORTANT]
23
23
  > **🤝 社区共创:文渊阁下一步怎么走,由社区决定。**
24
24
  >
25
- > 任何想法都欢迎[提到 Issue 里](https://github.com/suifei/dsh-ai-team/issues/new/choose):想加的功能、用着不顺的地方,或者你希望文渊阁以后长成什么样。**项目路线完全由本仓库的 Issue 驱动,不由维护者凭个人偏好改方向。**
25
+ > 任何想法都欢迎[提到 Issue 里](https://github.com/suifei/dsh-ai-team/issues/new/choose)。你可以描述一个实际卡点,也可以提出新方向、参与试跑或补充证据。
26
26
  >
27
- > 每条建议都会认真看、公开反馈。社区讨论定下来的改动,由我们负责实现、验证和发版,发布结果也会回到对应的 Issue。
27
+ > 维护者会公开说明判断依据和下一步,发布结果也会回到对应的 Issue。跨版本推进的目标和验收证据见[社区共创路线图](https://github.com/suifei/dsh-ai-team/issues/118)。
28
28
 
29
29
  > 文渊阁,藏修、校勘、纂辑之地。
30
30
  > 在这里,Human 不在环里逐条调度,而是在环上定方向、守信任、做最后那一步。
@@ -37,6 +37,9 @@
37
37
 
38
38
  ## 最近更新
39
39
 
40
+ - **目录浏览和验收补位**(0.4.154)。新建或编辑项目时可使用宿主的原生对话框或浏览式选择器。桌面安装说明补齐首次初始化和退出步骤。编制巡检标明缺少合格验收人的任务、观察到的成员回合和容量来源。感谢 [@ljyzww](https://github.com/ljyzww),[#100](https://github.com/suifei/dsh-ai-team/issues/100)。感谢 [@Arnoldnuo](https://github.com/Arnoldnuo),[#102](https://github.com/suifei/dsh-ai-team/issues/102)。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
41
+ - **看板受阻、离队交接和只读巡检**(0.4.153)。看板按当前状态显示受阻,历史依赖仍可查。离队与认领按同一顺序处理,待交接的原卡能交给继任者。普通项目可以开启只读编制巡检。感谢 [@idontlikefruit](https://github.com/idontlikefruit),[#115](https://github.com/suifei/dsh-ai-team/issues/115)。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117)。
42
+ - **派发预检和 DSH 0.2.3 兼容**(0.4.153)。PMO 在唤醒前核对依赖、在手任务和写入范围。工作台兼容新版宿主的会话鉴权。感谢 [@buger-gif](https://github.com/buger-gif),[#120](https://github.com/suifei/dsh-ai-team/issues/120)。感谢 [@Estelle00](https://github.com/Estelle00),[#122](https://github.com/suifei/dsh-ai-team/issues/122)。
40
43
  - **PMO 重启后续跑**(0.4.152)。恢复原会话时即提供模型路由,避免首轮因缺少模型而失败。保留原 PMO 会话、成员关系和任务。感谢 [@phm101299-ui](https://github.com/phm101299-ui),[#112](https://github.com/suifei/dsh-ai-team/issues/112)。
41
44
  - **文渊阁直接导入技能包**(0.4.151)。「导入技能」可选 Markdown、技能文件夹、ZIP 和 `.skill`。只需安装文渊阁,即可安装完整包并在 DSH 确认可加载后加入技能列表。感谢 [@godfay-g](https://github.com/godfay-g),[#109](https://github.com/suifei/dsh-ai-team/issues/109)。
42
45
  - **给成员装技能包**(0.4.150)。成员资料和新建人才增加已安装技能选择和完整技能包导入。感谢 [@godfay-g](https://github.com/godfay-g),[#109](https://github.com/suifei/dsh-ai-team/issues/109)。
@@ -135,6 +138,14 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
135
138
 
136
139
  项目「总览」从账本统计近七天验收、一次通过率和认领至验收的中位耗时。交付流程可跳转到对应看板状态,AI 协作卡可查看成员资料,验收证据可打开原始任务卡。
137
140
 
141
+ ### 只读编制巡检试跑
142
+
143
+ 在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。
144
+
145
+ 巡检还会记录没有合格验收人的任务 ID、插件观察到的在队成员运行回合数和容量来源。容量来源为 `default` 时使用默认估计,为 `host` 时来自宿主报告。PMO 会把长期无人可验收的任务带进现有补位建议。
146
+
147
+ 巡检复用现有派员建议和冷却规则,记录被暂缓的建议。人员动作仍由已有授权流程处理。试跑样本和调整建议可回到 [#116](https://github.com/suifei/dsh-ai-team/issues/116)。
148
+
138
149
  ---
139
150
 
140
151
  ## 为什么是「文渊阁」
@@ -156,7 +167,7 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
156
167
 
157
168
  ### DSH 桌面应用
158
169
 
159
- 首次使用时先打开一次 DSH 桌面应用,初始化 `desktop`。使用桌面版自带的 `dsh` 安装。
170
+ 首次使用时先打开一次 DSH 桌面应用,初始化 `desktop`。完全退出应用后,使用桌面版自带的 `dsh` 安装。
160
171
 
161
172
  ```powershell
162
173
  dsh plugin --profile desktop add "@suifei/dsh-ai-team"
@@ -177,6 +188,8 @@ dsh --profile web --no-open --port 33271
177
188
 
178
189
  第一次进入 Project 先设置 **工作目录**:工作目录编辑器会自动弹出,并预填宿主给出的建议值——配置项 `defaultWorkspace` → 当前进程目录 → **`~/works`**(Windows 为 `%USERPROFILE%\works`,Linux/macOS 为 `~/works`;不存在时自动创建)。点「选择目录」或用输入框改成任意已存在的目录即可;**新建项目必须填工作目录**(服务端强制,空目录会被 400 拒绝)。每个 Project 独立一个目录,成员只在这个目录里执行 Task。
179
190
 
191
+ 「选择目录」会使用宿主的原生对话框或在文渊阁内浏览宿主目录。选定后先回填路径,保存或创建项目时生效。
192
+
180
193
  ### 打开文渊阁后提示 503
181
194
 
182
195
  先确认插件安装在当前入口使用的 profile。桌面应用可用 `dsh plugin --profile desktop list "@suifei/dsh-ai-team" --depth 0` 回读版本。浏览器入口把命令里的 `desktop` 换成 `web`,并打开当前 Web 进程输出的完整 URL。
@@ -356,18 +369,36 @@ round-19 DeepSeek + Zhipu 双 provider
356
369
  - **贡献人才和团队**:新的人才(`talents/<人才>/talent.yml`)和团队(`teams/<团队>/team.yml`)都欢迎,合并后会随在线人才库发给所有用户。
357
370
  - **头像库**:[hash-avatar](https://github.com/suifei/hash-avatar) 同样欢迎 Star 和贡献新的种族、画风。
358
371
 
372
+ ### 共创约定
373
+
374
+ 提议可以从你在哪一步卡住、希望得到什么结果开始。已有版本、复现步骤、脱敏日志或样本,也欢迎一起附上。维护者会在原 Issue 给出归类、依据、下一步和进入实现的验收条件。任何人都可以补充证据或提出不同判断。
375
+
376
+ 证据和验收条件齐备、可以采纳的议题,维护者可以直接开工,并在原 Issue 链接实现与验证。社区贡献者随时可以加入实现或复测。
377
+
378
+ | 议题类型 | 下一步 |
379
+ |---|---|
380
+ | 缺陷 | 核对复现和预期行为。修复时用回归测试覆盖原场景。 |
381
+ | 改进 | 说明现有流程的卡点和希望改善的结果,用真实用例验收。 |
382
+ | 方向提案 | 在社区讨论收益和代价,约定一轮最小试跑。涉及授权或任务状态变化时,一并说明谁授权、如何停用、未完成任务如何交接。 |
383
+ | 使用或环境问题 | 给出可执行的排查步骤,依据结果更新归类。 |
384
+
385
+ 一条反馈可以拆成多个可验证的议题并互相链接。需要跨版本推进的能力,在[公开路线图](https://github.com/suifei/dsh-ai-team/issues/118)记录期望结果、阶段、验收证据和关联 Issue。暂缓时写清原因与重新讨论的条件。
386
+
359
387
  ### 致谢
360
388
 
361
389
  带来重要进展的反馈和代码,都会在这里和对应的「最近更新」条目里点名感谢。
362
390
 
363
391
  | 贡献者 | 贡献 | 带来的进展 |
364
392
  |---|---|---|
393
+ | [@idontlikefruit](https://github.com/idontlikefruit) | 受阻状态的三组复现输入 [#115](https://github.com/suifei/dsh-ai-team/issues/115) | 统一看板徽标、读屏和分组统计的受阻判定,保留历史依赖 |
394
+ | [@buger-gif](https://github.com/buger-gif) | 编制巡检、离队交接案例 [#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117),派发空转记录 [#120](https://github.com/suifei/dsh-ai-team/issues/120) | 统一认领与离队的执行顺序,在唤醒前检查认领条件,巡检识别缺少合格验收人的任务并记录运行回合和容量来源 |
395
+ | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化 |
365
396
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
366
397
  | [@godfay-g](https://github.com/godfay-g) | 技能目录和 ZIP 的导入建议 [#109](https://github.com/suifei/dsh-ai-team/issues/109) | 成员与自定义人才可在文渊阁选择已安装的技能或导入完整技能包。0.4.151 统一新建人才的导入入口,并由文渊阁直接安装整包 |
367
398
  | [@qq958691165](https://github.com/qq958691165) | 归档项目的成员反馈、团队管理建议 [#103](https://github.com/suifei/dsh-ai-team/issues/103) | 人员池排除归档项目,侧栏集中管理项目成员与团队预设 |
368
- | [@Arnoldnuo](https://github.com/Arnoldnuo) | 桌面端启动 503 反馈 [#102](https://github.com/suifei/dsh-ai-team/issues/102) | 工作台提供分情况的 503 提示,快速开始说明内置 `desktop` 与 `web` 的安装和启动方式,连接错误提示引导核对 profile |
399
+ | [@Arnoldnuo](https://github.com/Arnoldnuo) | 桌面端启动 503 反馈 [#102](https://github.com/suifei/dsh-ai-team/issues/102) | 工作台提示核对 profile,快速开始说明内置 `desktop` 与 `web` 的入口和安装方式,以及桌面端首次初始化和退出步骤 |
369
400
  | [@Lamooner](https://github.com/Lamooner) | PMO 决策反馈与建议 [#99](https://github.com/suifei/dsh-ai-team/issues/99) | 避免选中「不推荐」项,移除编号偏向并补充括注编号回归 |
370
- | [@ljyzww](https://github.com/ljyzww) | Windows 目录选择反馈 [#100](https://github.com/suifei/dsh-ai-team/issues/100) | 新建和编辑项目共用目录选择失败提示,保留手填路径 |
401
+ | [@ljyzww](https://github.com/ljyzww) | Windows 目录选择复现及宿主能力说明 [#100](https://github.com/suifei/dsh-ai-team/issues/100) | 新建和编辑项目共用浏览式目录选择,选定后回填路径 |
371
402
  | [@xiuchuan666](https://github.com/xiuchuan666) | 反馈与建议 [#65](https://github.com/suifei/dsh-ai-team/issues/65) | 输入框长高可拖大、贴图拖文件、@ 点名成员(0.4.120–0.4.123);人才市场与在线人才库(0.4.124–0.4.131);团队扩编:超限排队、开发验收配对、空闲必派、写入范围、加人建议(0.4.140) |
372
403
  | [@TardisBooo](https://github.com/TardisBooo) | 代码 [#88](https://github.com/suifei/dsh-ai-team/pull/88) | 工具参数改为对象 JSON Schema,Grok 4.7 可用(0.4.139) |
373
404
 
package/client.js CHANGED
@@ -88,7 +88,7 @@ window.__ModuleLoader__.load({
88
88
  agentFailed: '失败',
89
89
  agentRetired: '已退役',
90
90
  groupCreated: '新建 {n} 个任务',
91
- groupBlocked: '{n} 项有依赖',
91
+ groupBlocked: '{n} 项受阻',
92
92
  groupMore: '展开其余 {n} 项',
93
93
  groupLess: '收起其余 {n} 项',
94
94
  fromDiscussion: '由讨论升格',
@@ -299,6 +299,13 @@ window.__ModuleLoader__.load({
299
299
  workspacePathPlaceholder: '例如 D:/work/my-project',
300
300
  workspacePickUnavailable: '当前宿主的目录选择器不能用于此表单。请在「工作目录」中粘贴或输入完整路径。',
301
301
  workspacePickFailed: '未能打开目录选择器。请重试,或在「工作目录」中粘贴或输入完整路径。',
302
+ workspaceBrowseTitle: '浏览工作目录',
303
+ workspaceBrowseHome: '主目录',
304
+ workspaceBrowseParent: '上一级',
305
+ workspaceBrowseChoose: '使用当前目录',
306
+ workspaceBrowseEmpty: '此目录没有子目录。',
307
+ workspaceBrowseTruncated: '仅显示宿主返回的部分目录。',
308
+ workspaceBrowseError: '未能读取目录。{message}',
302
309
  workspaceSave: '保存目录',
303
310
  projectCreate: '创建项目',
304
311
  projectCreated: '已创建项目 {name}。',
@@ -597,7 +604,7 @@ window.__ModuleLoader__.load({
597
604
  agentFailed: 'Failed',
598
605
  agentRetired: 'Retired',
599
606
  groupCreated: '{n} tasks created',
600
- groupBlocked: '{n} with dependencies',
607
+ groupBlocked: '{n} blocked',
601
608
  groupMore: 'Show {n} more',
602
609
  groupLess: 'Collapse {n}',
603
610
  fromDiscussion: 'Promoted from discussion',
@@ -809,6 +816,13 @@ window.__ModuleLoader__.load({
809
816
  workspacePathPlaceholder: 'e.g. D:/work/my-project',
810
817
  workspacePickUnavailable: 'The host’s directory picker is unavailable for this form. Paste or enter the full path in the Workspace field.',
811
818
  workspacePickFailed: 'Could not open the directory picker. Retry, or paste or enter the full path in the Workspace field.',
819
+ workspaceBrowseTitle: 'Browse workspace directories',
820
+ workspaceBrowseHome: 'Home',
821
+ workspaceBrowseParent: 'Parent directory',
822
+ workspaceBrowseChoose: 'Use this directory',
823
+ workspaceBrowseEmpty: 'This directory has no subdirectories.',
824
+ workspaceBrowseTruncated: 'Only some directories were returned by the host.',
825
+ workspaceBrowseError: 'Could not read the directory. {message}',
812
826
  workspaceSave: 'Save directory',
813
827
  projectCreate: 'Create project',
814
828
  projectCreated: 'Created project {name}.',
@@ -1125,7 +1139,8 @@ window.__ModuleLoader__.load({
1125
1139
  if (data.thread && data.thread.taskId === taskId) return data.thread;
1126
1140
  return null;
1127
1141
  };
1128
- const blockedRefs = (task, tasks) => (task?.blockedBy ?? []).map((id) => {
1142
+ const isBlocked = (task) => task.blocked === true;
1143
+ const dependencyRefs = (task, tasks) => (task?.blockedBy ?? []).map((id) => {
1129
1144
  const dep = (tasks ?? []).find((item) => item.id === id);
1130
1145
  return '#' + taskNo(dep ?? { id });
1131
1146
  });
@@ -1156,10 +1171,10 @@ window.__ModuleLoader__.load({
1156
1171
  if (Object.hasOwn(STATUS, filter)) return task.status === filter;
1157
1172
  if (filter === 'q1') {
1158
1173
  return task.status === 'pending_acceptance'
1159
- || (task.ownerId === humanId && task.status === 'pending' && task.blocked === true);
1174
+ || (task.ownerId === humanId && task.status === 'pending' && isBlocked(task));
1160
1175
  }
1161
1176
  if (filter === 'q2') return task.status === 'in_progress';
1162
- if (filter === 'q3') return task.status === 'pending' && task.blocked === true;
1177
+ if (filter === 'q3') return task.status === 'pending' && isBlocked(task);
1163
1178
  if (filter === 'q4') return task.status === 'done';
1164
1179
  return true;
1165
1180
  }
@@ -1379,7 +1394,7 @@ window.__ModuleLoader__.load({
1379
1394
  .at-pill.at-tone-success { background: var(--dsw-alias-state-success-tertiary); color: var(--dsw-alias-state-success-primary); }
1380
1395
  .at-pill.at-tone-muted { border: 1px solid var(--dsw-alias-border-l3); background: transparent; color: var(--dsw-alias-label-caption); }
1381
1396
  .at-blocked { display: inline-flex; align-items: center; gap: 4px; height: 20px; padding: 0 6px; border-radius: var(--dsw-radius-xs); background: var(--dsw-alias-state-warn-tertiary); color: var(--dsw-alias-state-warn-label); font-size: 11px; font-weight: 500; line-height: 16px; white-space: nowrap; }
1382
- .at-dep { color: var(--dsw-alias-state-warn-label); font-weight: 400; }
1397
+ .at-dep { color: var(--dsw-alias-label-secondary); font-size: 11px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1383
1398
  .at-replies { margin-left: auto; color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 16px; white-space: nowrap; font-variant-numeric: tabular-nums; }
1384
1399
  .at-ct { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; color: var(--dsw-alias-label-primary); font-size: 13px; font-weight: 500; line-height: 21px; overflow-wrap: anywhere; }
1385
1400
  .at-card-board .at-ct { font-size: 13px; }
@@ -1574,6 +1589,11 @@ window.__ModuleLoader__.load({
1574
1589
  .at-modal.at-modal-wide { width: 90%; height: 90%; max-height: 90%; }
1575
1590
  .at-modal.at-blueprint-dialog { width: min(720px, 90cqi); max-width: 90%; height: auto; }
1576
1591
  .at-modal.at-blueprint-setup { width: min(820px, 90cqi); height: auto; }
1592
+ .at-modal.at-directory-picker { width: min(460px, 90cqi); overflow-x: hidden; }
1593
+ .at-directory-nav { display: flex; flex-wrap: wrap; gap: 8px; }
1594
+ .at-directory-path { overflow-wrap: anywhere; }
1595
+ .at-directory-list { display: grid; gap: 4px; max-height: 42vh; overflow: auto; overscroll-behavior: contain; }
1596
+ .at-directory-list .at-btn { display: block; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; text-align: start; }
1577
1597
  .at-blueprint-fields { display: grid; gap: 10px; min-width: 0; }
1578
1598
  .at-blueprint-fields fieldset { min-inline-size: 0; margin: 0; padding: 10px; border: 1px solid var(--dsw-alias-border-l1); border-radius: var(--dsw-radius-sm); }
1579
1599
  .at-blueprint-fields p { margin: 0; overflow-wrap: anywhere; }
@@ -1899,7 +1919,9 @@ window.__ModuleLoader__.load({
1899
1919
  function TaskCard({ t, card, tasks, variant, selected, following, onOpen, onToggleFollow }) {
1900
1920
  const meta = statusMeta(card.status);
1901
1921
  const no = taskNo(card);
1902
- const refs = blockedRefs(card, tasks);
1922
+ const blocked = isBlocked(card);
1923
+ const refs = dependencyRefs(card, tasks);
1924
+ const dependencies = refs.length ? t('dependsOn') + ' ' + refs.join('、') : '';
1903
1925
  const fromDiscussion = Array.isArray(card.originRefs) && card.originRefs.length > 0;
1904
1926
  const ownerText = t('owner') + ' ' + (card.owner ?? t('unassigned'));
1905
1927
  const execText = card.assignee ? t('executor') + ' ' + card.assignee : t('unassigned');
@@ -1909,7 +1931,8 @@ window.__ModuleLoader__.load({
1909
1931
  'Task #' + no,
1910
1932
  card.title,
1911
1933
  t(meta.label),
1912
- refs.length ? t('blocked') + ' ' + t('dependsOn') + ' ' + refs.join('、') : '',
1934
+ blocked ? t('blocked') : '',
1935
+ dependencies,
1913
1936
  ownerText,
1914
1937
  execText,
1915
1938
  replyLabel,
@@ -1939,7 +1962,8 @@ window.__ModuleLoader__.load({
1939
1962
  h('span', { className: 'at-num' }, 'Task #' + no),
1940
1963
  h(StatusPill, { t, status: card.status }),
1941
1964
  card.irreversible ? h('span', { className: 'at-blocked', title: t('irreversibleBadge') }, t('irreversibleBadge')) : null,
1942
- refs.length ? h('span', { className: 'at-blocked' }, h(Ico, { name: 'block', size: 12 }), t('blocked'), h('span', { className: 'at-dep' }, '· ' + t('dependsOn') + ' ' + refs.join('、'))) : null,
1965
+ blocked ? h('span', { className: 'at-blocked' }, h(Ico, { name: 'block', size: 12 }), t('blocked')) : null,
1966
+ dependencies ? h('span', { className: 'at-dep', title: dependencies }, dependencies) : null,
1943
1967
  h('span', { className: 'at-replies' }, replyLabel + (time ? ' · ' + time : '')),
1944
1968
  ),
1945
1969
  h('div', { className: 'at-ct', title: card.title }, card.title),
@@ -1962,7 +1986,7 @@ window.__ModuleLoader__.load({
1962
1986
  const parts = ['in_progress', 'pending_acceptance', 'pending', 'done']
1963
1987
  .filter((status) => counts[status])
1964
1988
  .map((status) => t(statusMeta(status).label) + ' ' + counts[status]);
1965
- const blockedCount = cards.filter((card) => (card.blockedBy ?? []).length > 0).length;
1989
+ const blockedCount = cards.filter(isBlocked).length;
1966
1990
  const groupLabel = tf(t, 'groupCreated', { n: cards.length });
1967
1991
  const renderCard = (card) => h(TaskCard, {
1968
1992
  key: card.id,
@@ -2096,6 +2120,58 @@ window.__ModuleLoader__.load({
2096
2120
  return h('div', { className: 'at-modalback', ref: backRef }, children);
2097
2121
  }
2098
2122
 
2123
+ function WorkspaceDirectoryBrowser({ t, service, initialPath, onPick, onClose }) {
2124
+ const [request, setRequest] = React.useState({ path: initialPath });
2125
+ const [listing, setListing] = React.useState(null);
2126
+ const [error, setError] = React.useState('');
2127
+ const [loading, setLoading] = React.useState(true);
2128
+ const closeButton = React.useRef(null);
2129
+ React.useEffect(() => {
2130
+ const previous = document.activeElement;
2131
+ closeButton.current?.focus({ preventScroll: true });
2132
+ return () => previous?.focus?.({ preventScroll: true });
2133
+ }, []);
2134
+ React.useEffect(() => {
2135
+ const controller = new AbortController();
2136
+ const { signal } = controller;
2137
+ const load = async () => {
2138
+ try {
2139
+ const result = await service.listDirectory(request.path, signal);
2140
+ if (!signal.aborted) setListing(result);
2141
+ } catch (cause) {
2142
+ if (!signal.aborted) setError(cause?.message ?? String(cause));
2143
+ } finally {
2144
+ if (!signal.aborted) setLoading(false);
2145
+ }
2146
+ };
2147
+ void load();
2148
+ return () => controller.abort();
2149
+ }, [request, service]);
2150
+ const browse = (path) => {
2151
+ setLoading(true);
2152
+ setError('');
2153
+ setRequest({ path });
2154
+ };
2155
+ const parentPath = listing?.crumbs?.at(-2)?.path;
2156
+ return h(ModalBack, { onClose },
2157
+ h('div', { className: 'at-modal at-directory-picker', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('workspaceBrowseTitle') },
2158
+ h('h2', { className: 'at-modaltitle' }, t('workspaceBrowseTitle')),
2159
+ h('div', { className: 'at-modalactions' },
2160
+ h('button', { ref: closeButton, className: 'at-btn', type: 'button', onClick: onClose }, t('cancel')),
2161
+ h('button', { className: 'at-btn at-btn-primary', type: 'button', disabled: loading || !listing?.path || Boolean(error), onClick: () => onPick(listing.path) }, t('workspaceBrowseChoose'))),
2162
+ h('div', { className: 'at-directory-nav' },
2163
+ h('button', { className: 'at-btn', type: 'button', disabled: loading, onClick: () => browse(undefined) }, t('workspaceBrowseHome')),
2164
+ h('button', { className: 'at-btn', type: 'button', disabled: loading || !parentPath, onClick: () => browse(parentPath) }, t('workspaceBrowseParent'))),
2165
+ listing?.path ? h('div', { className: 'at-modalmeta at-directory-path' }, listing.path) : null,
2166
+ loading ? h('div', { className: 'at-modalmeta', role: 'status' }, t('loading')) : null,
2167
+ error ? h('div', { className: 'at-modalerror at-directory-path', role: 'alert' }, tf(t, 'workspaceBrowseError', { message: error })) : null,
2168
+ h('div', { className: 'at-directory-list', 'aria-busy': loading },
2169
+ (listing?.entries ?? []).map(({ name, path }) =>
2170
+ h('button', { className: 'at-btn', key: path, title: name, type: 'button', disabled: loading, onClick: () => browse(path) }, name))),
2171
+ !loading && !error && listing?.entries?.length === 0 ? h('p', { className: 'at-modalmeta' }, t('workspaceBrowseEmpty')) : null,
2172
+ listing?.truncated ? h('p', { className: 'at-modalmeta' }, t('workspaceBrowseTruncated')) : null));
2173
+ }
2174
+
2099
2175
  const emptyBlueprintOpportunity = () => ({ kind: '', work: '', minutes: '', perWeek: '' });
2100
2176
  const emptyBlueprintIntake = () => ({ business: '', humanWork: '', weeklyHours: '', opportunities: [emptyBlueprintOpportunity()] });
2101
2177
 
@@ -3177,10 +3253,7 @@ window.__ModuleLoader__.load({
3177
3253
  quadrant.key === 'q4' && meta && meta.total > meta.count ? h('div', { className: 'at-qtotal' }, tf(t, 'q4Total', { n: meta.count, m: meta.total })) : null,
3178
3254
  shown.length
3179
3255
  ? h('div', { className: 'at-qlist' }, shown.map((item) => {
3180
- const blocked = (item.blockedBy ?? []).map((id) => {
3181
- const dep = tasks.find((task) => task.id === id);
3182
- return '#' + taskNo(dep ?? { id });
3183
- });
3256
+ const blocked = dependencyRefs(item, tasks);
3184
3257
  const category = t(CATEGORY_LABEL[item.category] ?? 'catBlocked');
3185
3258
  const parts = [category];
3186
3259
  if (quadrant.key === 'q3') {
@@ -4293,6 +4366,12 @@ window.__ModuleLoader__.load({
4293
4366
  const [workspaceDraft, setWorkspaceDraft] = React.useState('');
4294
4367
  const [workspaceError, setWorkspaceError] = React.useState('');
4295
4368
  const [workspaceBusy, setWorkspaceBusy] = React.useState(false);
4369
+ const [workspacePicker, setWorkspacePicker] = React.useState(null);
4370
+ const workspacePickRequest = React.useRef(0);
4371
+ React.useEffect(() => {
4372
+ setWorkspacePicker((picker) => (picker && (picker.form === 'new' ? !newOpen : !workspaceOpen) ? null : picker));
4373
+ return () => { workspacePickRequest.current += 1; };
4374
+ }, [newOpen, workspaceOpen]);
4296
4375
  const [memberViewId, setMemberViewId] = React.useState(null);
4297
4376
  // 人员池(全局层):进入该 scope 时拉取一次聚合视图。
4298
4377
  const [peopleData, setPeopleData] = React.useState(null);
@@ -4994,31 +5073,41 @@ window.__ModuleLoader__.load({
4994
5073
  }
4995
5074
  async function pickWorkspacePath() {
4996
5075
  const service = ctx?.get?.('uiWorkspace') ?? ctx?.uiWorkspace;
4997
- if (service === undefined || service === null || typeof service.pickDirectory !== 'function') {
4998
- return { error: 'unavailable', path: null };
4999
- }
5000
- try {
5001
- return { path: await service.pickDirectory(), error: null };
5002
- } catch (error) {
5003
- // Harness rc.5 wraps the RPC error in a plain Error and retains only its message.
5004
- const unavailable = error?.code === 'directory-picker/unavailable'
5005
- || error?.message === 'directory picker failed: directoryPicker.pick needs the native capability; the composed picker serves "browse"';
5006
- return { error: unavailable ? 'unavailable' : 'failed', path: null };
5076
+ if (typeof service?.pickDirectory === 'function') {
5077
+ try {
5078
+ return { path: await service.pickDirectory() };
5079
+ } catch (error) {
5080
+ // Harness rc.5 retains only the message from the native pick RPC failure.
5081
+ const unavailable = (error?.code ?? error?.rpcError?.code) === 'directory-picker/unavailable'
5082
+ || error?.message === 'directory picker failed: directoryPicker.pick needs the native capability; the composed picker serves "browse"';
5083
+ if (!unavailable) {
5084
+ console.warn('[ai-team] directory picker failed', error);
5085
+ return { error: 'failed' };
5086
+ }
5087
+ }
5007
5088
  }
5089
+ return typeof service?.listDirectory === 'function' ? { browse: service } : { error: 'unavailable' };
5008
5090
  }
5009
- async function applyWorkspacePick(setPath, setError) {
5091
+ async function applyWorkspacePick(form, draft, setPath, setError) {
5092
+ const request = ++workspacePickRequest.current;
5010
5093
  const picked = await pickWorkspacePath();
5094
+ if (workspacePickRequest.current !== request) return;
5011
5095
  const unavailable = t('workspacePickUnavailable');
5012
5096
  const failed = t('workspacePickFailed');
5013
- if (picked.path) {
5014
- setPath(picked.path);
5097
+ const onPick = (path) => {
5098
+ setPath(path);
5015
5099
  setError((previous) => previous === unavailable || previous === failed ? '' : previous);
5100
+ };
5101
+ if (picked.browse) {
5102
+ setWorkspacePicker({ form, service: picked.browse, initialPath: draft.trim() || undefined, onPick });
5103
+ } else if (picked.path) {
5104
+ onPick(picked.path);
5016
5105
  } else if (picked.error) {
5017
5106
  setError(picked.error === 'unavailable' ? unavailable : failed);
5018
5107
  }
5019
5108
  }
5020
5109
  async function pickNewWorkspace() {
5021
- await applyWorkspacePick(setNWorkspace, setNError);
5110
+ await applyWorkspacePick('new', nWorkspace, setNWorkspace, setNError);
5022
5111
  }
5023
5112
  function openWorkspaceEditor() {
5024
5113
  setWorkspaceDraft(project?.workspacePath ?? '');
@@ -5026,7 +5115,7 @@ window.__ModuleLoader__.load({
5026
5115
  setWorkspaceOpen(true);
5027
5116
  }
5028
5117
  async function pickProjectWorkspace() {
5029
- await applyWorkspacePick(setWorkspaceDraft, setWorkspaceError);
5118
+ await applyWorkspacePick('edit', workspaceDraft, setWorkspaceDraft, setWorkspaceError);
5030
5119
  }
5031
5120
  async function saveWorkspace() {
5032
5121
  if (!project || workspaceBusy || !workspaceDraft.trim()) return;
@@ -6583,6 +6672,11 @@ window.__ModuleLoader__.load({
6583
6672
  h('h2', { className: 'at-modaltitle' }, withIco('users', t('teamComposeTitle'), 16)),
6584
6673
  h(TeamComposer, { t, talents, onSaved: (team) => { setTeamComposeOpen(false); void loadTeams(team && team.id); }, onCancel: () => setTeamComposeOpen(false) }))) : null,
6585
6674
  peopleModel ? h(PeopleModelDialog, { t, catalog: modelCatalog, catalogError: modelCatalogError, people: peopleData ?? [], initial: peopleModel, onApply: applyPeopleModel, onClose: () => setPeopleModel(null) }) : null,
6675
+ workspacePicker && (workspacePicker.form === 'new' ? newOpen : workspaceOpen) ? h(WorkspaceDirectoryBrowser, {
6676
+ t, service: workspacePicker.service, initialPath: workspacePicker.initialPath,
6677
+ onPick: (path) => { workspacePicker.onPick(path); setWorkspacePicker(null); },
6678
+ onClose: () => setWorkspacePicker(null),
6679
+ }) : null,
6586
6680
  dialog ? h(WorkbenchDialog, { key: dialogSeqRef.current, t, dialog, onDismiss: () => setDialog(null) }) : null,
6587
6681
  shortcutsOpen ? h(ModalBack, { onClose: () => setShortcutsOpen(false) },
6588
6682
  h('div', { className: 'at-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('shortcutTitle') },
package/index.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * The member runtime (real Agent sessions) lands in M2. Until then the
9
9
  * ledger/domain service is the only writer and the Host never fakes work.
10
10
  */
11
- import { HOST_SUBAGENT_LIMIT, planDispatch, planIdleRetry, planIdleStaffing, planStaffingAdvice, planTaskNudges } from './lib/host/pmo.js';
11
+ import { HOST_SUBAGENT_LIMIT, planDispatch, planIdleRetry, planIdleStaffing, planStaffingAdvice, planTaskNudges, staffingReview } from './lib/host/pmo.js';
12
12
  import { pmoHasNews } from './lib/ledger/fold.js';
13
13
  import { homedir, tmpdir } from 'node:os';
14
14
  import { randomUUID } from 'node:crypto';
@@ -59,7 +59,7 @@ import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
59
59
  import { installFaultAdapter } from './lib/host/fault-adapter.js';
60
60
  import { buildModelCatalog, buildModelEfforts } from './lib/host/model-catalog.js';
61
61
  import { createTeamTool } from './lib/host/member-tools.js';
62
- import { describeTaskContext, describeWake, planWakes } from './lib/host/waker.js';
62
+ import { canDeliverWake, describeTaskContext, describeWake, planWakes } from './lib/host/waker.js';
63
63
  import { describeCauseChain } from './lib/runtime/error-chain.js';
64
64
  import { capacityLimit, classifyWakeFailure, deferredWakeKind, isCapacityError, isMalformedTurnError } from './lib/runtime/wake-failure.js';
65
65
  import { createDeferredWakes } from './lib/runtime/deferred-wakes.js';
@@ -137,6 +137,8 @@ export const Config = z.object({
137
137
  pmoMaxRounds: z.number().step(1).min(0).max(100).default(3),
138
138
  // 加人建议:可认领的待办没人接、或待验收排队,持续这么多分钟算「推进过慢」,给 Human 收件箱一条加人建议。
139
139
  staffingAdviceMinutes: z.number().step(1).min(1).max(1440).default(30),
140
+ // 只读编制巡检的采样周期。0 关闭;试跑记录通过 full 诊断日志回读。
141
+ staffingReviewMinutes: z.number().step(1).min(0).max(1440).default(0),
140
142
  // 新项目的初始团队:内置 teams/<团队>/,或 ~/.dsh/ai-team/catalog/user/teams/<团队>/(同名覆盖内置)。
141
143
  teamPreset: z.string().default('default'),
142
144
  });
@@ -975,11 +977,12 @@ export function apply(ctx, config = {}) {
975
977
  const pmoLastDispatch = new Map();
976
978
  // 空闲必派的节流状态(按项目):上次叫的时间、局面签名、同一局面重复次数(planIdleStaffing)。
977
979
  const pmoLastStaffing = new Map();
980
+ const pmoStaffingReviewWindows = new Map();
978
981
  // 宿主同时在跑的子智能体上限:默认 8,见到容量报错就以报错里的数字为准(加人建议的排队提示用)。
979
- let hostCapacity = HOST_SUBAGENT_LIMIT;
982
+ let observedHostCapacity = null;
980
983
  const noteHostCapacity = (error) => {
981
984
  const limit = capacityLimit(error);
982
- if (limit !== null) hostCapacity = limit;
985
+ if (limit !== null) observedHostCapacity = limit;
983
986
  };
984
987
  const pmoLastEscalate = new Map();
985
988
  const pmoLastReview = new Map();
@@ -1091,6 +1094,8 @@ export function apply(ctx, config = {}) {
1091
1094
  * @param {{ seq?: number|null, retry?: boolean }} options retry:这是 deferredWakes 的补投
1092
1095
  */
1093
1096
  const deliverWakePlans = async (projectRuntime, plans, { seq = null, retry = false } = {}) => {
1097
+ const readyPlans = plans.filter((plan) => canDeliverWake(projectRuntime.service.state, plan));
1098
+ if (readyPlans.length === 0) return;
1094
1099
  const subagents = serviceOf(ctx, 'subagents');
1095
1100
  const sessions = serviceOf(ctx, 'sessions');
1096
1101
  const permissionPresets = serviceOf(ctx, 'permissionPresets');
@@ -1116,8 +1121,8 @@ export function apply(ctx, config = {}) {
1116
1121
  const wakePrompt = async (plan, member, options = {}) => describeWake(plan, projectRuntime.service.state, options);
1117
1122
  // #65:Human 消息里的图片/文件随唤醒一起交给成员会话(文字块 + 附件块)。
1118
1123
  const wakeContent = async (plan, member, options = {}) => messageContent(await wakePrompt(plan, member, options), plan.attachments);
1119
- for (const plan of plans) {
1120
- if (wakeKeys.has(plan.key)) continue;
1124
+ for (const plan of readyPlans) {
1125
+ if (wakeKeys.has(plan.key) || !canDeliverWake(projectRuntime.service.state, plan)) continue;
1121
1126
  let member = projectRuntime.service.state.members?.[plan.memberId];
1122
1127
  if (member === undefined) continue;
1123
1128
  // 无工作目录的项目不 wake(与 activate 的 fail-closed 同一不变量):
@@ -1439,8 +1444,11 @@ export function apply(ctx, config = {}) {
1439
1444
  // 吞掉,60s tick 兜底。判定(实时回合、每卡上限)在 planDispatch(lib/host/pmo.js)。
1440
1445
  for (const task of active) {
1441
1446
  const last = pmoLastDispatch.get(task.id);
1442
- if (planDispatch(task, state, { inTurn: (id) => turnsInFlight.has(id), last, now }) === null) continue;
1443
- pmoLastDispatch.set(task.id, { at: now, count: (last?.count ?? 0) + 1 });
1447
+ const current = projectRuntime.service.state;
1448
+ const memberId = planDispatch(current.tasks?.[task.id], current, { inTurn: (id) => turnsInFlight.has(id), last, now });
1449
+ if (memberId === null) continue;
1450
+ const count = last?.memberId === memberId ? last.count + 1 : 1;
1451
+ pmoLastDispatch.set(task.id, { at: now, count, memberId });
1444
1452
  await wakeFromResult(projectRuntime, {
1445
1453
  event: { type: 'pmo/dispatch', payload: { taskId: task.id, bucket: Math.floor(now / 60_000) } },
1446
1454
  }, {});
@@ -1472,7 +1480,31 @@ export function apply(ctx, config = {}) {
1472
1480
  }, {});
1473
1481
  }
1474
1482
  // 加人建议:推进过慢(待办没人接 / 待验收排长队)时给 Human 收件箱一条建议,由 Human 决定(planStaffingAdvice)。
1475
- for (const advice of planStaffingAdvice(state, { now, inTurn: (id) => turnsInFlight.has(id), capacity: hostCapacity, humanId: projectRuntime.service.humanId(), wait: (config.staffingAdviceMinutes ?? 30) * 60_000 })) {
1483
+ const staffingState = projectRuntime.service.state;
1484
+ const reviewInterval = (config.staffingReviewMinutes ?? 0) * 60_000;
1485
+ const reviewWindow = diag.level === 'full' && reviewInterval > 0 ? Math.floor(now / reviewInterval) : null;
1486
+ const reviewDue = reviewWindow !== null && pmoStaffingReviewWindows.get(projectRuntime.id) !== reviewWindow;
1487
+ const suppressed = [];
1488
+ const inTurn = (id) => turnsInFlight.has(id);
1489
+ const capacity = observedHostCapacity ?? HOST_SUBAGENT_LIMIT;
1490
+ const adviceList = planStaffingAdvice(staffingState, {
1491
+ now, inTurn, capacity,
1492
+ humanId: projectRuntime.service.humanId(), wait: (config.staffingAdviceMinutes ?? 30) * 60_000,
1493
+ onSuppressed: reviewDue ? (entry) => suppressed.push(entry) : undefined,
1494
+ });
1495
+ if (reviewDue) {
1496
+ pmoStaffingReviewWindows.set(projectRuntime.id, reviewWindow);
1497
+ try {
1498
+ const review = staffingReview(staffingState, projectRuntime.ledger.events, {
1499
+ now, intervalMs: reviewInterval, capacity, capacitySource: observedHostCapacity === null ? 'default' : 'host',
1500
+ inTurn, advice: adviceList, suppressed,
1501
+ });
1502
+ diag.append({ ev: 'pmo.staffing.review', projectId: projectRuntime.id, window: reviewWindow, ...review });
1503
+ } catch (error) {
1504
+ diag.append({ ev: 'pmo.staffing.review.fail', projectId: projectRuntime.id, message: error?.message ?? String(error) });
1505
+ }
1506
+ }
1507
+ for (const advice of adviceList) {
1476
1508
  const item = await projectRuntime.service.recordStaffingAdvice(projectRuntime.id, advice);
1477
1509
  diag.append({ ev: 'pmo.advice', projectId: projectRuntime.id, role: advice.role, count: advice.count, title: advice.title, itemId: item?.id ?? null });
1478
1510
  }
@@ -2514,18 +2546,21 @@ export function apply(ctx, config = {}) {
2514
2546
  path: '/ai-team',
2515
2547
  handler: async (req, res) => {
2516
2548
  try {
2517
- // 信任栅栏:webServer 承载层不做认证与 Host/Origin 校验,路由各自过 Connection 的
2518
- // 栅栏(宿主 open-in-app / inspector 同一做法)。缺了它,任何网页都能以 Human 身份
2519
- // 跨站 POST 命令(实测桌面版:Origin: https://evil.example 的 text/plain POST 直达处理器)。
2520
- // 栅栏缺失即拒绝,不静默放行。
2549
+ // 0.2.2 使用 requestRejection;0.2.3 的 admit 同时验证来源与会话。
2550
+ // isTrustedRequest 只检查来源,不能作为认证栅栏。
2521
2551
  const connection = serviceOf(ctx, 'connection');
2522
- if (typeof connection?.requestRejection !== 'function') {
2523
- return send(res, { error: { code: 'E_TRUST_FENCE_UNAVAILABLE', message: 'connection service is unavailable' } }, 503);
2552
+ let rejection = 503;
2553
+ if (typeof connection?.requestRejection === 'function') {
2554
+ rejection = connection.requestRejection(req);
2555
+ } else if (typeof connection?.admit === 'function') {
2556
+ const admission = await connection.admit(req);
2557
+ rejection = admission?.rejection ?? (admission?.peer ? undefined : 503);
2524
2558
  }
2525
- const rejection = connection.requestRejection(req);
2526
2559
  if (rejection !== undefined) {
2527
- diag.append({ ev: 'http.rejected.fail', status: rejection, method: req.method, path: String(req.url ?? '').split('?')[0], origin: req.headers?.origin ?? null });
2528
- return send(res, { error: { code: rejection === 401 ? 'E_UNAUTHENTICATED' : 'E_FORBIDDEN', message: 'request rejected by the connection trust fence' } }, rejection);
2560
+ const status = rejection === 401 || rejection === 403 ? rejection : 503;
2561
+ diag.append({ ev: 'http.rejected.fail', status, method: req.method, path: String(req.url ?? '').split('?')[0], origin: req.headers?.origin ?? null });
2562
+ if (status === 503) return send(res, { error: { code: 'E_TRUST_FENCE_UNAVAILABLE', message: 'connection service is unavailable' } }, status);
2563
+ return send(res, { error: { code: status === 401 ? 'E_UNAUTHENTICATED' : 'E_FORBIDDEN', message: 'request rejected by the connection trust fence' } }, status);
2529
2564
  }
2530
2565
  const url = new URL(req.url, 'http://local');
2531
2566
  await ready;
@@ -9,6 +9,7 @@ import {
9
9
  dependenciesDone,
10
10
  memberHasInProgress,
11
11
  memberHasPendingAcceptance,
12
+ STALLED_MEMBER_STATUSES,
12
13
  writeScopeConflict,
13
14
  } from './policy.js';
14
15
 
@@ -95,45 +96,64 @@ export function createTask(input) {
95
96
  };
96
97
  }
97
98
 
98
- /** A member claims a ready pending task; only `claim` enters claimHistory. */
99
- export function claimTask(task, actor, tasksById, options = {}) {
100
- assertRevision(task, options.expectedRevision);
101
- if (task.status !== 'pending') {
102
- fail(ERRORS.INVALID_STATE, `task ${task.id} is not pending`, { details: { status: task.status } });
99
+ /** Shared claim constraints for command validation and wake planning. */
100
+ function claimTaskRejection(task, memberId, tasksById) {
101
+ if (task?.status !== 'pending' || task.tombstone === true) {
102
+ return { code: ERRORS.INVALID_STATE, message: `task ${task?.id} is not pending`, details: { status: task?.status } };
103
103
  }
104
- const memberId = actor?.memberId;
105
- if ((actor?.kind !== 'agent' && actor?.kind !== 'human') || typeof memberId !== 'string') {
106
- fail(ERRORS.UNAUTHORIZED, 'only a Team member can claim a task');
104
+ if (typeof memberId !== 'string') {
105
+ return { code: ERRORS.UNAUTHORIZED, message: 'only a Team member can claim a task' };
107
106
  }
108
- if (task.assigneeId !== null && task.assigneeId !== memberId) {
109
- fail(ERRORS.ALREADY_CLAIMED, 'task is assigned to another member', {
107
+ if (task.assigneeId != null && task.assigneeId !== memberId) {
108
+ return {
109
+ code: ERRORS.ALREADY_CLAIMED, message: 'task is assigned to another member',
110
110
  details: { taskId: task.id, assigneeId: task.assigneeId },
111
- });
111
+ };
112
112
  }
113
113
  if (!dependenciesDone(task, tasksById)) {
114
- fail(ERRORS.BLOCKED, 'task has unfinished dependencies', {
114
+ return {
115
+ code: ERRORS.BLOCKED, message: 'task has unfinished dependencies',
115
116
  details: { taskId: task.id, blockedBy: task.blockedBy },
116
- });
117
+ };
117
118
  }
118
119
  // 写入范围与别人正在做的卡重叠:等那张卡交付再认领,避免两人同时改同一批文件互相覆盖。
119
120
  const clash = writeScopeConflict(task, tasksById);
120
121
  if (clash !== undefined) {
121
- fail(ERRORS.CONFLICT, `write scope ${clash.mine} overlaps ${clash.theirs} of in-progress task ${clash.task.id}; claim it after that task is submitted, or claim another task`, {
122
+ return {
123
+ code: ERRORS.CONFLICT,
124
+ message: `write scope ${clash.mine} overlaps ${clash.theirs} of in-progress task ${clash.task.id}; claim it after that task is submitted, or claim another task`,
122
125
  details: { taskId: task.id, conflictTaskId: clash.task.id, scope: clash.mine, conflictScope: clash.theirs },
123
- });
126
+ };
124
127
  }
125
128
  const awaiting = memberHasPendingAcceptance(tasksById, memberId);
126
129
  if (awaiting !== undefined) {
127
- fail(ERRORS.CONFLICT, 'member has a task awaiting acceptance; wait for QA before claiming the next one', {
130
+ return {
131
+ code: ERRORS.CONFLICT, message: 'member has a task awaiting acceptance; wait for QA before claiming the next one',
128
132
  details: { memberId, taskId: awaiting.id },
129
- });
133
+ };
130
134
  }
131
135
  const busy = memberHasInProgress(tasksById, memberId);
132
136
  if (busy !== undefined) {
133
- fail(ERRORS.CONFLICT, 'member already has an in_progress task', {
137
+ return {
138
+ code: ERRORS.CONFLICT, message: 'member already has an in_progress task',
134
139
  details: { memberId, taskId: busy.id },
135
- });
140
+ };
136
141
  }
142
+ return null;
143
+ }
144
+
145
+ export function canDispatchTask(state, task, memberId) {
146
+ const member = state?.members?.[memberId];
147
+ return member?.kind === 'agent' && member.status !== 'retired' && !STALLED_MEMBER_STATUSES.includes(member.status)
148
+ && claimTaskRejection(task, memberId, state.tasks) === null;
149
+ }
150
+
151
+ /** A member claims a ready pending task; only `claim` enters claimHistory. */
152
+ export function claimTask(task, actor, tasksById, options = {}) {
153
+ assertRevision(task, options.expectedRevision);
154
+ const memberId = actor?.kind === 'agent' || actor?.kind === 'human' ? actor.memberId : null;
155
+ const rejection = claimTaskRejection(task, memberId, tasksById);
156
+ if (rejection !== null) fail(rejection.code, rejection.message, { details: rejection.details });
137
157
  const patch = {
138
158
  status: 'in_progress',
139
159
  assigneeId: memberId,
package/lib/host/pmo.js CHANGED
@@ -1,4 +1,5 @@
1
- import { STALLED_MEMBER_STATUSES, dependenciesDone, teamRoles, writeScopeConflict } from '../domain/policy.js';
1
+ import { STALLED_MEMBER_STATUSES, dependenciesDone, isReviewCandidate, teamRoles, writeScopeConflict } from '../domain/policy.js';
2
+ import { canDispatchTask } from '../domain/task.js';
2
3
 
3
4
  /**
4
5
  * PMO decision policy.
@@ -125,21 +126,22 @@ export const PMO_DISPATCH_LIMIT = 3;
125
126
  * 判忙只看**实时回合**(宿主 turn/start → turn/end),不看账本投影:账本没有「回合结束」
126
127
  * 事件,成员一旦 session-bound 就永远是 running——#18 与 il2c 实账本(2997 次唤醒、
127
128
  * pmo_dispatch 0 次)都证明旧判定让补派成了死代码。每卡最多 PMO_DISPATCH_LIMIT 次、
128
- * 间隔至少 60 秒;责任人醒着却不认领,交给 stall/escalate 升级。
129
+ * 同一责任位的重复补派按 60、120 秒退避;仍未认领时交给 stall/escalate 升级。
129
130
  *
130
131
  * @param {any} task
131
132
  * @param {any} state 账本投影
132
- * @param {{ inTurn: (sessionId: string) => boolean, last?: { at: number, count: number }, now: number }} options
133
+ * @param {{ inTurn: (sessionId: string) => boolean, last?: { at: number, count: number, memberId: string }, now: number }} options
133
134
  * @returns {string | null}
134
135
  */
135
- export function planDispatch(task, state, { inTurn, last = { at: 0, count: 0 }, now }) {
136
- if (task?.status !== 'pending' || task.tombstone === true) return null;
137
- const responsibleId = task.assigneeId ?? task.ownerId;
138
- const responsible = state?.members?.[responsibleId];
139
- if (responsible === undefined || responsible.kind !== 'agent') return null;
140
- if (responsible.status === 'retired' || responsible.status === 'failed') return null;
136
+ export function planDispatch(task, state, { inTurn, last, now }) {
137
+ const responsibleId = task?.assigneeId ?? task?.ownerId;
138
+ if (!canDispatchTask(state, task, responsibleId)) return null;
139
+ const responsible = state.members[responsibleId];
141
140
  if (typeof responsible.sessionId === 'string' && inTurn(responsible.sessionId)) return null;
142
- if (last.count >= PMO_DISPATCH_LIMIT || now - last.at < 60_000) return null;
141
+ if (last?.memberId === responsibleId) {
142
+ if (last.count >= PMO_DISPATCH_LIMIT) return null;
143
+ if (last.count > 0 && now - last.at < MINUTE * 2 ** (last.count - 1)) return null;
144
+ }
143
145
  return responsibleId;
144
146
  }
145
147
 
@@ -236,24 +238,95 @@ export const STAFFING_ADVICE_COOLDOWN = 4 * 60 * MINUTE;
236
238
  /** 宿主同时运行的子智能体上限默认值(dsh-subagent maxActiveSubagents);实际值以容量报错里的数字为准。 */
237
239
  export const HOST_SUBAGENT_LIMIT = 8;
238
240
 
241
+ function taskAge(task, now) {
242
+ const since = Number(task.updatedAt ?? task.createdAt ?? now);
243
+ return Number.isFinite(since) ? Math.max(0, now - since) : 0;
244
+ }
245
+
246
+ function waitingSummary(tasks, now) {
247
+ let oldest = 0;
248
+ let total = 0;
249
+ for (const task of tasks) {
250
+ const age = taskAge(task, now);
251
+ oldest = Math.max(oldest, age);
252
+ total += age;
253
+ }
254
+ return { count: tasks.length, oldestMinutes: Math.round(oldest / MINUTE), meanMinutes: tasks.length ? Math.round(total / tasks.length / MINUTE) : 0 };
255
+ }
256
+
257
+ function tasksWithoutReviewer(state, tasks) {
258
+ const members = Object.values(state.members ?? {});
259
+ return tasks.filter((task) => !members.some((member) => isReviewCandidate(member, task, state)));
260
+ }
261
+
262
+ /** A read-only rollup of the existing queues and observed submissions in this window. */
263
+ export function staffingReview(state, events, { now, intervalMs, capacity, capacitySource = null, inTurn, advice = [], suppressed = [] }) {
264
+ const since = now - intervalMs;
265
+ const people = new Map(Object.values(state.members ?? {})
266
+ .filter((member) => member.kind === 'agent' && member.status !== 'retired')
267
+ .map(({ id, role, status }) => [id, { id, role: role || '未设置岗位', status, submitted: 0, accepted: 0, returned: 0 }]));
268
+ const submissions = new Map();
269
+ for (const event of events) {
270
+ if (!Number.isFinite(event.at) || event.at < since || event.at > now) continue;
271
+ const taskId = event.payload?.taskId;
272
+ if (typeof taskId !== 'string') continue;
273
+ if (event.type === 'task/submitted') {
274
+ const member = event.actor?.kind === 'agent' ? people.get(event.actor.memberId) : undefined;
275
+ submissions.set(taskId, member);
276
+ if (member) member.submitted += 1;
277
+ } else if (event.type === 'task/accepted' || event.type === 'task/changes-requested') {
278
+ const member = submissions.get(taskId);
279
+ if (member) member[event.type === 'task/accepted' ? 'accepted' : 'returned'] += 1;
280
+ submissions.delete(taskId);
281
+ }
282
+ }
283
+ const groups = new Map();
284
+ for (const member of people.values()) {
285
+ const group = groups.get(member.role) ?? { role: member.role, members: [], assigned: [], inProgress: 0 };
286
+ group.members.push({ ...member, returnRate: member.submitted ? member.returned / member.submitted : null });
287
+ groups.set(member.role, group);
288
+ }
289
+ const open = openTasks(state);
290
+ const waitingReview = open.filter(({ status }) => status === 'pending_acceptance');
291
+ const missingReviewers = tasksWithoutReviewer(state, waitingReview);
292
+ const activeMemberTurns = typeof inTurn === 'function'
293
+ ? [...people.keys()].map((id) => state.members[id].sessionId).filter((id) => typeof id === 'string' && inTurn(id)).length
294
+ : null;
295
+ for (const task of open) {
296
+ const group = groups.get(people.get(task.assigneeId)?.role);
297
+ if (!group) continue;
298
+ if (task.status === 'pending') group.assigned.push(task);
299
+ if (task.status === 'in_progress') group.inProgress += 1;
300
+ }
301
+ return {
302
+ since, now, capacity, capacitySource, activeMemberTurns,
303
+ claimable: waitingSummary(claimableTasks(state, open), now),
304
+ pendingAcceptance: waitingSummary(waitingReview, now),
305
+ pendingAcceptanceWithoutReviewer: { ...waitingSummary(missingReviewers, now), taskIds: missingReviewers.map(({ id }) => id) },
306
+ roles: [...groups.values()].map(({ assigned, ...group }) => ({ ...group, assignedQueue: waitingSummary(assigned, now) })),
307
+ advice,
308
+ suppressed,
309
+ };
310
+ }
311
+
239
312
  /**
240
313
  * 加人建议(用户 2026-11-20:从管理角度看推进过慢就该加人,由 Human 决定)。插件自己按看板判定,不靠模型:
241
314
  * - 开发不够:有可认领的待办等了 ≥ 30 分钟,却没有空闲开发(空闲开发会先被 planIdleStaffing 派活)。
242
315
  * 建议人数 = 等着的待办数,最多 3。
243
- * - 验收不够:待验收的卡等了 ≥ 30 分钟,且没有验收人,或每位验收人摊到 ≥ 2 张。建议加 1 名。
316
+ * - 验收不够:待验收的卡等了 ≥ 30 分钟,且卡片没有合格验收人、团队没有验收岗位或每个验收岗位摊到 ≥ 2 张。建议加 1 名。
244
317
  * 团队人数加上建议人数超过宿主同时在跑的上限时,理由里写明多出的人会排队、提速有限。
245
318
  * 该岗位有人停摆(failed / unavailable,等 Human 恢复)时改为「建议恢复」:人还在,只是停了,恢复比加人快,
246
319
  * 也不占新名额(实机 il2c 2026-11-20:验收人白砚 06:53 模型报错停摆,两张卡待验收 9 小时,旧版却说「团队没有验收人,建议加 1 名」)。
247
320
  * 同一类建议 4 小时内只提一次;上一条还没处理(unread)时不再提。冷却读账本里的收件箱,重启不丢。
248
321
  *
249
322
  * @param {any} state 账本投影
250
- * @param {{ now: number, inTurn: (sessionId: string) => boolean, capacity?: number, humanId?: string | null, wait?: number }} options 「慢」的门槛 wait 来自配置 staffingAdviceMinutes
323
+ * @param {{ now: number, inTurn: (sessionId: string) => boolean, capacity?: number, humanId?: string | null, wait?: number, onSuppressed?: (entry: object) => void }} options 「慢」的门槛 wait 来自配置 staffingAdviceMinutes
251
324
  * @returns {Array<{ role: 'developer' | 'qa', action: 'add' | 'recover', count: number, memberIds: string[], title: string, reasons: string[], taskIds: string[] }>}
252
325
  */
253
- export function planStaffingAdvice(state, { now, inTurn, capacity = HOST_SUBAGENT_LIMIT, humanId = null, wait = STAFFING_ADVICE_WAIT }) {
326
+ export function planStaffingAdvice(state, { now, inTurn, capacity = HOST_SUBAGENT_LIMIT, humanId = null, wait = STAFFING_ADVICE_WAIT, onSuppressed }) {
254
327
  const open = openTasks(state);
255
328
  if (open.length === 0) return [];
256
- const age = (task) => now - Number(task.updatedAt ?? task.createdAt ?? now);
329
+ const age = (task) => taskAge(task, now);
257
330
  const minutes = (ms) => Math.round(ms / MINUTE);
258
331
  const { qas, stalled } = teamRoles(state);
259
332
  const advice = [];
@@ -269,20 +342,30 @@ export function planStaffingAdvice(state, { now, inTurn, capacity = HOST_SUBAGEN
269
342
  : { role: 'developer', action: 'add', count: Math.min(waitingWork.length, 3), memberIds: [], reasons: [waited] }) });
270
343
  }
271
344
  const waitingReview = open.filter((task) => task.status === 'pending_acceptance' && age(task) >= wait);
272
- if (waitingReview.length > 0 && (qas.length === 0 || waitingReview.length >= 2 * qas.length)) {
273
- const waited = `${waitingReview.length} 张卡待验收已等 ${longest(waitingReview)} 分钟`;
274
- advice.push({ taskIds: waitingReview.map((task) => task.id), ...(stalled.qas.length > 0
275
- ? recover('qa', stalled.qas, waited)
276
- : { role: 'qa', action: 'add', count: 1, memberIds: [], reasons: [qas.length === 0
277
- ? `${waited},团队没有验收人`
278
- : `${waited},${qas.length} 位验收人每人摊到 ${Math.ceil(waitingReview.length / qas.length)} 张`] }) });
345
+ const missingReviewers = tasksWithoutReviewer(state, waitingReview);
346
+ if (waitingReview.length > 0 && (missingReviewers.length > 0 || qas.length === 0 || waitingReview.length >= 2 * qas.length)) {
347
+ const affected = missingReviewers.length > 0 ? missingReviewers : waitingReview;
348
+ const waited = `${affected.length} 张卡待验收已等 ${longest(affected)} 分钟`;
349
+ const restorable = stalled.qas.filter((member) =>
350
+ affected.some((task) => isReviewCandidate({ ...member, status: 'idle' }, task, state)));
351
+ const shortage = qas.length === 0 ? '团队没有验收人'
352
+ : missingReviewers.length > 0 ? '没有符合任务规则的验收人'
353
+ : `${qas.length} 位验收人每人摊到 ${Math.ceil(waitingReview.length / qas.length)} 张`;
354
+ advice.push({ taskIds: affected.map((task) => task.id), ...(restorable.length > 0
355
+ ? recover('qa', restorable, waited)
356
+ : { role: 'qa', action: 'add', count: 1, memberIds: [], reasons: [`${waited},${shortage}`] }) });
279
357
  }
280
358
  const headcount = Object.values(state?.members ?? {}).filter((member) => member?.kind === 'agent' && member.status !== 'retired' && !STALLED_MEMBER_STATUSES.includes(member.status)).length;
281
- const recent = (role) => Object.values(state?.inbox ?? {}).some((item) =>
359
+ const recent = (role) => Object.values(state?.inbox ?? {}).find((item) =>
282
360
  item.ref?.kind === 'staffing_advice' && item.ref.role === role
283
361
  && (humanId === null || item.memberId === humanId)
284
362
  && (item.state === 'unread' || now - Number(item.createdAt ?? 0) < STAFFING_ADVICE_COOLDOWN));
285
- return advice.filter((entry) => !recent(entry.role)).map((entry) => {
363
+ return advice.filter(({ role, action, taskIds }) => {
364
+ const prior = recent(role);
365
+ if (prior === undefined) return true;
366
+ onSuppressed?.({ role, action, taskIds, reason: prior.state === 'unread' ? 'unread-advice' : 'cooldown' });
367
+ return false;
368
+ }).map((entry) => {
286
369
  const reasons = [...entry.reasons];
287
370
  const who = entry.role === 'developer' ? '开发' : '验收';
288
371
  if (entry.action === 'recover') return { ...entry, reasons, title: `建议恢复停摆的${who}:${reasons.join(';')}` };
@@ -443,16 +443,6 @@ export class TeamService {
443
443
  // one done row with the duration in every case. 前置校验失败也必须留痕
444
444
  // (errors 档只留 .fail 行,校验抛出必须发生在 try 内才能落行)。
445
445
  const startedAt = Date.now();
446
- const failRow = (code, message) => {
447
- this.diag?.append({
448
- ev: 'dispatch.fail',
449
- type: command.type,
450
- code,
451
- projectId: command.projectId ?? null,
452
- message,
453
- elapsedMs: Date.now() - startedAt,
454
- });
455
- };
456
446
  this.diag?.append({
457
447
  ev: 'dispatch.start',
458
448
  type: command.type,
@@ -460,9 +450,8 @@ export class TeamService {
460
450
  memberId: actor?.memberId ?? null,
461
451
  projectId: command.projectId ?? null,
462
452
  });
463
- try {
464
- if (actor === undefined || (actor.kind !== 'human' && actor.kind !== 'agent')) {
465
- failRow(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
453
+ const checkCommand = () => {
454
+ if (actor?.kind !== 'human' && actor?.kind !== 'agent') {
466
455
  fail(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
467
456
  }
468
457
  // An agent actor must resolve to a live, non-retired member: otherwise a
@@ -470,62 +459,68 @@ export class TeamService {
470
459
  if (actor.kind === 'agent') {
471
460
  const actingMember = this.state.members?.[actor.memberId];
472
461
  if (actingMember === undefined || actingMember.kind !== 'agent') {
473
- failRow(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
474
462
  fail(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
475
463
  }
476
464
  if (actingMember.status === 'retired') {
477
- failRow(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
478
465
  fail(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
479
466
  }
480
467
  }
481
468
  this.checkBlueprintCommand(command, payload);
469
+ };
470
+ const dispatchExclusive = (work) => this.runExclusive(() => {
471
+ // A queued task mutation can outlive the actor's team membership.
472
+ checkCommand();
473
+ return work();
474
+ });
475
+ try {
476
+ checkCommand();
482
477
  switch (command.type) {
483
478
  case 'project.create': return await this.createProject(command, payload);
484
479
  case 'project.blueprint.prepare':
485
480
  case 'project.blueprint.recordTime':
486
481
  case 'project.blueprint.start':
487
482
  case 'project.blueprint.measure':
488
- case 'project.blueprint.expand': return await this.runExclusive(() => this.advanceBlueprint(command, payload));
483
+ case 'project.blueprint.expand': return await dispatchExclusive(() => this.advanceBlueprint(command, payload));
489
484
  case 'project.owner.update': return await this.changeProjectOwner(command, payload);
490
485
  case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
491
- case 'project.repair': return await this.runExclusive(() => this.repairLedger(command));
492
- case 'project.pmo.update': return await this.runExclusive(() => this.setProjectPmo(command, payload));
493
- case 'project.archive': return await this.runExclusive(() => this.setProjectArchive(command, payload));
494
- case 'project.runState': return await this.runExclusive(() => this.setProjectRunState(command, payload));
486
+ case 'project.repair': return await dispatchExclusive(() => this.repairLedger(command));
487
+ case 'project.pmo.update': return await dispatchExclusive(() => this.setProjectPmo(command, payload));
488
+ case 'project.archive': return await dispatchExclusive(() => this.setProjectArchive(command, payload));
489
+ case 'project.runState': return await dispatchExclusive(() => this.setProjectRunState(command, payload));
495
490
  case 'project.handoff': return await this.handoffProject(command, payload);
496
491
  case 'stream.post': return await this.postStream(command, payload);
497
492
  case 'member.add': return await this.addMember(command, payload);
498
493
  case 'member.bind': return await this.bindMemberSession(command, payload);
499
494
  case 'member.fail': return await this.failMember(command, payload);
500
- case 'member.retire': return await this.retireMember(command, payload);
495
+ case 'member.retire': return await dispatchExclusive(() => this.retireMember(command, payload));
501
496
  case 'member.profile.update': return await this.updateMemberProfile(command, payload);
502
497
  case 'member.evolve': return await this.evolveMember(command, payload);
503
498
  case 'member.distill': return await this.distillMember(command, payload);
504
- case 'member.leave': return await this.leaveMember(command, payload);
505
- case 'member.rejoin': return await this.rejoinMember(command, payload);
506
- case 'member.takeover': return await this.takeoverMember(command, payload);
499
+ case 'member.leave': return await dispatchExclusive(() => this.leaveMember(command, payload));
500
+ case 'member.rejoin': return await dispatchExclusive(() => this.rejoinMember(command, payload));
501
+ case 'member.takeover': return await dispatchExclusive(() => this.takeoverMember(command, payload));
507
502
  case 'member.message': return await this.messageMember(command, payload);
508
503
  case 'member.note': return await this.addMemberNote(command, payload);
509
504
  case 'member.skill': return await this.addMemberSkill(command, payload);
510
505
  case 'member.config.update': return await this.updateMemberConfig(command, payload);
511
506
  case 'member.retry': return await this.retryMember(command, payload);
512
- case 'task.create': return await this.runExclusive(() => this.createTask(command, payload));
513
- case 'task.claim': return await this.runExclusive(() => this.taskCommand(command, 'claim'));
514
- case 'task.release': return await this.runExclusive(() => this.taskCommand(command, 'release'));
515
- case 'task.assign': return await this.runExclusive(() => this.taskCommand(command, 'assign'));
516
- case 'task.submit': return await this.runExclusive(() => this.taskCommand(command, 'submit'));
517
- case 'task.accept': return await this.runExclusive(() => this.taskCommand(command, 'accept'));
518
- case 'task.request_changes': return await this.runExclusive(() => this.taskCommand(command, 'request_changes'));
519
- case 'task.cancel': return await this.runExclusive(() => this.taskCommand(command, 'cancel'));
520
- case 'task.reopen': return await this.runExclusive(() => this.taskCommand(command, 'reopen'));
521
- case 'task.reassign': return await this.runExclusive(() => this.taskCommand(command, 'reassign'));
522
- case 'task.delete': return await this.runExclusive(() => this.taskCommand(command, 'delete'));
523
- case 'task.convert': return await this.runExclusive(() => this.convert(command, payload));
507
+ case 'task.create': return await dispatchExclusive(() => this.createTask(command, payload));
508
+ case 'task.claim': return await dispatchExclusive(() => this.taskCommand(command, 'claim'));
509
+ case 'task.release': return await dispatchExclusive(() => this.taskCommand(command, 'release'));
510
+ case 'task.assign': return await dispatchExclusive(() => this.taskCommand(command, 'assign'));
511
+ case 'task.submit': return await dispatchExclusive(() => this.taskCommand(command, 'submit'));
512
+ case 'task.accept': return await dispatchExclusive(() => this.taskCommand(command, 'accept'));
513
+ case 'task.request_changes': return await dispatchExclusive(() => this.taskCommand(command, 'request_changes'));
514
+ case 'task.cancel': return await dispatchExclusive(() => this.taskCommand(command, 'cancel'));
515
+ case 'task.reopen': return await dispatchExclusive(() => this.taskCommand(command, 'reopen'));
516
+ case 'task.reassign': return await dispatchExclusive(() => this.taskCommand(command, 'reassign'));
517
+ case 'task.delete': return await dispatchExclusive(() => this.taskCommand(command, 'delete'));
518
+ case 'task.convert': return await dispatchExclusive(() => this.convert(command, payload));
524
519
  case 'task.follow': return await this.follow(command, payload);
525
520
  case 'thread.post': return await this.postThread(command, payload);
526
521
  case 'inbox.ack': return await this.ack(command, payload);
527
- case 'decision.request': return await this.runExclusive(() => this.requestDecision(command, payload));
528
- case 'decision.answer': return await this.runExclusive(() => this.answerDecision(command, payload));
522
+ case 'decision.request': return await dispatchExclusive(() => this.requestDecision(command, payload));
523
+ case 'decision.answer': return await dispatchExclusive(() => this.answerDecision(command, payload));
529
524
  default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
530
525
  }
531
526
  } catch (error) {
package/lib/host/waker.js CHANGED
@@ -11,6 +11,16 @@ import { pairedReviewer, projectOwnerId, reviewPairs } from '../domain/policy.js
11
11
  import { isBoardIdle } from '../ledger/fold.js';
12
12
  import { describeAttachments, normalizeAttachments } from '../domain/rich-message.js';
13
13
  import { blocksBlueprintTask } from '../domain/team-blueprint.js';
14
+ import { canDispatchTask } from '../domain/task.js';
15
+
16
+ const CLAIM_WAKE_REASONS = new Set(['task_assigned', 'pmo_dispatch', 'pmo_claim']);
17
+
18
+ export function canDeliverWake(state, { memberId, taskId, reason }) {
19
+ const task = state.tasks?.[taskId];
20
+ const ownerClaims = reason === 'task_created' && (task?.assigneeId == null || task.assigneeId === memberId);
21
+ if (ownerClaims || CLAIM_WAKE_REASONS.has(reason)) return canDispatchTask(state, task, memberId);
22
+ return agentMember(state, memberId, reason === 'route_changed') !== null;
23
+ }
14
24
 
15
25
  function text(value) {
16
26
  return typeof value === 'string' ? value : '';
@@ -20,14 +30,14 @@ function stringIds(value) {
20
30
  return Array.isArray(value) ? [...new Set(value.filter((id) => typeof id === 'string' && id !== ''))] : [];
21
31
  }
22
32
 
23
- function agentMember(state, memberId) {
33
+ function agentMember(state, memberId, allowFailed = false) {
24
34
  if (typeof memberId !== 'string') return null;
25
35
  const member = state.members?.[memberId];
26
36
  if (member === undefined || member.kind !== 'agent') return null;
27
37
  // failed 成员不自动唤醒(其 LLM 正在失败,自动唤醒只会烧预算):
28
38
  // 恢复走 member.retry(Human/Project owner 显式动作)或 Human 在成员
29
39
  // 资料里的「重试」;review 路径另经 eligibleReviewers 的同一排除。
30
- if (member.status === 'retired' || member.status === 'failed') return null;
40
+ if (member.status === 'retired' || (!allowFailed && member.status === 'failed')) return null;
31
41
  return member;
32
42
  }
33
43
 
@@ -136,8 +146,7 @@ export function planWakes(state, result, actor = {}, options = {}) {
136
146
  const blueprint = Boolean(Object.values(state.projects ?? {})[0]?.blueprint);
137
147
  const targets = new Map();
138
148
  const add = (memberId, taskId, reason, key, promptOverride) => {
139
- const member = agentMember(state, memberId);
140
- if (member === null) return;
149
+ if (!canDeliverWake(state, { memberId, taskId, reason })) return;
141
150
  // A thread author must not be woken by their own reply, and the reviewer
142
151
  // candidate is already filtered by eligibility. Other Agent-authored
143
152
  // events (notably a Lead creating a task owned by itself) still need a
@@ -163,10 +172,9 @@ export function planWakes(state, result, actor = {}, options = {}) {
163
172
  // 模型就是明确的修复动作,必须放行,否则改完仍然卡死。
164
173
  if (event?.type === 'member/config-updated' && event.payload?.routeChanged === true) {
165
174
  const memberId = event.payload.memberId;
166
- const member = typeof memberId === 'string' ? state.members?.[memberId] : undefined;
167
175
  // 只唤醒手上有未完成任务的成员:fold 已把 routeStale 记进账本,空闲成员下次被
168
176
  // 真正唤醒时自然在新路由下重建。否则改一次全员模型就空转激活 N 个会话(r08:6 次)。
169
- if (member !== undefined && member.kind === 'agent' && member.status !== 'retired' && unfinishedTasksFor(state, memberId).length > 0) {
177
+ if (canDeliverWake(state, { memberId, reason: 'route_changed' }) && unfinishedTasksFor(state, memberId).length > 0) {
170
178
  targets.set(`${memberId}:route_changed`, {
171
179
  memberId,
172
180
  taskId: null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.152",
3
+ "version": "0.4.154",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",