dsh-science-plugin 0.0.0-stage → 0.14.0

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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/agents/_README.md +5 -0
  4. package/agents/analyst.md +27 -0
  5. package/agents/figure-expert.md +35 -0
  6. package/agents/literature-scout.md +32 -0
  7. package/agents/presentation.md +78 -0
  8. package/agents/reviewer.md +32 -0
  9. package/agents/simulator.md +30 -0
  10. package/agents/topic-designer.md +26 -0
  11. package/agents/trainer.md +36 -0
  12. package/agents/writer.md +44 -0
  13. package/assets/mascots/analyst.svg +33 -0
  14. package/assets/mascots/designer.svg +33 -0
  15. package/assets/mascots/figure.svg +35 -0
  16. package/assets/mascots/idle.svg +9 -0
  17. package/assets/mascots/lead.svg +33 -0
  18. package/assets/mascots/presentation.svg +40 -0
  19. package/assets/mascots/reviewer.svg +31 -0
  20. package/assets/mascots/scout.svg +31 -0
  21. package/assets/mascots/simulator.svg +33 -0
  22. package/assets/mascots/thinking.svg +23 -0
  23. package/assets/mascots/trainer.svg +32 -0
  24. package/assets/mascots/working.svg +9 -0
  25. package/assets/mascots/writer.svg +33 -0
  26. package/client/client.js +3425 -0
  27. package/client/client.js.map +7 -0
  28. package/cordis.patch.yml +12 -0
  29. package/docs/DEVLOG.md +864 -0
  30. package/docs/SPEC.md +452 -0
  31. package/docs/recipes/agent-teams-science.md +46 -0
  32. package/docs/research/2026-11-12-academic-figure-skill-/350/257/204/344/274/260.md +33 -0
  33. package/docs/research/2026-11-12-/347/224/237/347/211/251/347/247/221/347/240/224/350/203/275/345/212/233/344/270/216/345/267/245/344/275/234/345/217/260/351/233/206/346/210/220/350/260/203/347/240/224.md +169 -0
  34. package/docs/research/2026-11-12-/347/247/221/347/240/224/347/273/230/345/233/276/345/274/200/346/272/220/346/226/271/346/241/210/350/260/203/347/240/224.md +52 -0
  35. package/docs/research/2026-11-13-/345/257/271/350/257/235/351/251/261/345/212/250/347/247/221/347/240/224/345/267/245/344/275/234/345/217/260/344/272/247/345/223/201/347/255/226/347/225/245/350/260/203/347/240/224.md +319 -0
  36. package/docs/research/2026-11-13-/350/267/257/347/272/277B/346/212/200/346/234/257/345/217/257/350/241/214/346/200/247/344/270/216/344/275/216/347/274/272/351/231/267/350/256/276/350/256/241/350/260/203/347/240/224.md +65 -0
  37. package/docs/superpowers/specs/2026-11-12-/347/247/221/347/240/224/345/267/245/344/275/234/345/217/260/351/207/215/346/236/204/350/256/276/350/256/241.md +364 -0
  38. package/docs/superpowers/specs/2026-11-13-/345/257/271/350/257/235/344/274/230/345/205/210/347/247/221/347/240/224/345/215/241/347/211/207/345/267/245/344/275/234/345/217/260/351/207/215/346/236/204/350/256/276/350/256/241.md +607 -0
  39. package/icon.svg +6 -0
  40. package/lib/action-cards.js +194 -0
  41. package/lib/artifact-index.js +131 -0
  42. package/lib/blueprint.js +1487 -0
  43. package/lib/dag.js +69 -0
  44. package/lib/db.js +386 -0
  45. package/lib/figureqa.js +290 -0
  46. package/lib/figures.js +732 -0
  47. package/lib/httpdata-auth.js +91 -0
  48. package/lib/httpdata.js +862 -0
  49. package/lib/index.js +329 -0
  50. package/lib/lit.js +100 -0
  51. package/lib/paperspine.js +287 -0
  52. package/lib/project-adapter.js +259 -0
  53. package/lib/project-catalog.js +227 -0
  54. package/lib/project-context.js +282 -0
  55. package/lib/project-domain.js +849 -0
  56. package/lib/project-remote.js +348 -0
  57. package/lib/project-store.js +653 -0
  58. package/lib/rail-team.js +47 -0
  59. package/lib/resources.js +94 -0
  60. package/lib/reviewcov.js +238 -0
  61. package/lib/reviewer.js +638 -0
  62. package/lib/reviewruns.js +95 -0
  63. package/lib/roles.js +41 -0
  64. package/lib/router.js +133 -0
  65. package/lib/skeleton-context.js +181 -0
  66. package/lib/skillmenu.js +993 -0
  67. package/lib/ssh.js +637 -0
  68. package/lib/status.js +138 -0
  69. package/lib/store.js +50 -0
  70. package/lib/team.js +945 -0
  71. package/lib/vendor/ssh2.bundle.cjs +20124 -0
  72. package/lib/workspace-key.js +64 -0
  73. package/locale/en.json +7 -0
  74. package/locale/zh.json +7 -0
  75. package/package.json +71 -6
  76. package/skills/sci-autoresearch/SKILL.md +41 -0
  77. package/skills/sci-figures/SKILL.md +91 -0
  78. package/skills/sci-figures/references/journal-requirements.md +22 -0
  79. package/skills/sci-figures/references/r-figures.md +106 -0
  80. package/skills/sci-figures/scripts/figure_export.py +45 -0
  81. package/skills/sci-figures/scripts/style_presets.py +82 -0
  82. package/skills/sci-hypothesis/SKILL.md +37 -0
  83. package/skills/sci-polish/SKILL.md +28 -0
  84. package/skills/sci-remote-jobs/SKILL.md +48 -0
  85. package/skills/sci-simulation/SKILL.md +70 -0
  86. package/skills/sci-simulation/references/tool-dossiers/_TEMPLATE.md +25 -0
  87. package/skills/sci-simulation/references/tool-dossiers/ase.md +42 -0
  88. package/skills/sci-simulation/references/tool-dossiers/gaussian.md +42 -0
  89. package/skills/sci-simulation/references/tool-dossiers/gromacs.md +37 -0
  90. package/skills/sci-simulation/references/tool-dossiers/lammps.md +34 -0
  91. package/skills/sci-simulation/references/tool-dossiers/quantum-espresso.md +34 -0
  92. package/skills/sci-simulation/references/universal-tool-onboarding.md +117 -0
  93. package/skills/sci-slides/SKILL.md +73 -0
  94. package/skills/sci-slides/scripts/make_deck.py +332 -0
  95. package/skills/sci-writing/SKILL.md +33 -0
package/lib/team.js ADDED
@@ -0,0 +1,945 @@
1
+ // dsh-science — 科研团队(自研实现,建在稳定的 ctx.subagents spawn/fork 原语上)
2
+ // 说明:npm 的 experimental agent-team 包(0.1.5-alpha.2)与 dsh 0.2.2-rc.1 不兼容(启动即禁用),
3
+ // 因此参照 agent-teams 插件的做法:成员 = 命名子代理(spawn, fresh context, delivery 'parent'),
4
+ // 任务板 = 本插件文件状态($DSH_HOME/dsh-science/team.json + 工作区镜像),派发 = 建任务 + sendMessage 唤醒成员。
5
+ // 队长 = 主会话(lead),Router 约束由 index.js 的 systemPrompt section 提供。
6
+
7
+ import { readFileSync, writeFileSync, renameSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { dataDirOf, blockedGateOf } from './store.js'
10
+ import { normalizedBlockedBy } from './dag.js'
11
+ import { ROLES, DEFAULT_TEAM, rolePrompt, roleLabel } from './roles.js'
12
+ import { alignTaskToResult, pruneTasksFromResults } from './blueprint.js'
13
+ import { readScope, blueprintViewOf, sessionIdOf } from './project-adapter.js'
14
+ import { resolveProjectContext } from './project-context.js'
15
+ import { assertDispatchGate } from './project-domain.js'
16
+ import { ensureRouterSection } from './router.js'
17
+ // v0.9.0 角色级 skill 菜单:spawn 提示词末尾追加「扩展技能库」段(已安装技能 INDEX.md 路径清单)
18
+ // + simulator 专属的通用计算模拟规范(新工具上手 8 步规范绝对路径)。技能不进全局 registry,
19
+ // 只经这段提示词对对应角色成员生效(跨角色隔离),成员用读文件工具按需取用。
20
+ import { roleSkillSectionText, universalOnboardingText, formatSkillWakeText, setMemberWakeHook } from './skillmenu.js'
21
+
22
+ function log(msg) {
23
+ console.log(`[dsh-science team] ${msg}`)
24
+ }
25
+
26
+ const teamFile = () => join(dataDirOf(), 'team.json')
27
+
28
+ // T2:registerTeamTools 注入的 Project Store。旧全局团队台账(成员无 parentSessionId、
29
+ // 任务无 rootSessionId)在升级时只有能唯一确定所属 root 才回填,否则保持 legacy-unscoped。
30
+ let activeStore = null
31
+
32
+ const REVIEW_SCOPES = ['turn', 'computation', 'evidence', 'journal']
33
+ const REVIEW_SCOPE_TEXT = {
34
+ turn: '审查最近一轮回复:数字溯源/断言-执行一致性/伪造迹象。',
35
+ computation: '审查计算过程:软件版本、参数、随机种子、收敛证据四要素;输入文件是否经过查手册协议。',
36
+ evidence: '审查文章证据:每个 claim 的证据链、图表与描述一致性(表格程序化解析)。',
37
+ journal: '期刊审稿模拟:以目标期刊审稿人视角出 major/minor 意见(新颖性/方法/统计/结论强度)。',
38
+ }
39
+ // 依赖闸门的「终态」:failed/cancelled 也已结束,若仍视为未满足会让下游任务永久卡死。
40
+ const DONE_STATUSES = new Set(['completed', 'failed', 'cancelled', 'deleted'])
41
+
42
+ // 队长协议懒注册(v0.6.0 fix1):全局 section 已删,协议单一来源在 lib/router.js(scoped)。
43
+ // 队长调用建队/派单工具时补挂一次(ensureRouterSection 内部有幂等与成员豁免守卫)。
44
+ function ensureLeadProtocol(ctx, exec) {
45
+ try {
46
+ ensureRouterSection(ctx, exec && exec.agent)
47
+ } catch {
48
+ /* 注册失败不影响工具执行 */
49
+ }
50
+ }
51
+
52
+ // 任务板损坏隔离(X3,对齐 blueprint fix4):解析失败或结构非法(members/tasks 缺失或非数组)
53
+ // → 坏文件改名备份为 team.json.corrupt-<ts>(quarantine,备份保留)+ console.error 报警,
54
+ // 返回空任务板。文件不存在(首跑常态)不算损坏。
55
+ function quarantineTeam(reason) {
56
+ const backupName = `team.json.corrupt-${Date.now()}`
57
+ try {
58
+ renameSync(teamFile(), join(dataDirOf(), backupName))
59
+ console.error(`[dsh-science team] team.json ${reason},已隔离备份为 ${backupName}`)
60
+ } catch (berr) {
61
+ console.error(`[dsh-science team] team.json ${reason}且隔离备份失败(${berr && berr.message})`)
62
+ }
63
+ }
64
+
65
+ // T2:旧全局团队台账的迁移归属。
66
+ // 升级前 members 只有 parentSessionId、tasks 只有可选的 rootSessionId;它们没有 projectId。
67
+ // 只有稳定链接能唯一确定 root 时才回填(成员父会话链 / 任务唯一同名成员);其余一律标
68
+ // legacy-unscoped:不进入任何项目视图,也不参与项目内工具查找。禁止用“当前只有一个项目”
69
+ // 之类的安装形状推断归属——项目可能建立在旧数据之后。
70
+
71
+ function attributedMember(member, scope) {
72
+ if (scope && (scope.projectId || scope.rootSessionId)) {
73
+ return {
74
+ ...member,
75
+ projectId: member.projectId ? String(member.projectId) : (scope.projectId || null),
76
+ rootSessionId: member.rootSessionId ? String(member.rootSessionId) : (scope.rootSessionId || null),
77
+ }
78
+ }
79
+ return { ...member, legacyUnscoped: true }
80
+ }
81
+
82
+ // 条目级归一(H2)+ 项目归属迁移(T2):合法顶层形状也可能夹带 null/标量成员或任务、
83
+ // blockedBy 非数组;这些条目无法被任何工具使用,读档时直接剔除/归一。
84
+ // opts.store:调用方注入的 Project Store(保留给迁移/调试;归属迁移只依据稳定链接)。
85
+ export function sanitizeTeamState(parsed, opts = {}) {
86
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
87
+ return { members: [], tasks: [], taskSeq: 0 }
88
+ }
89
+ const rawMembers = (Array.isArray(parsed.members) ? parsed.members : []).filter(
90
+ (m) => m && typeof m === 'object' && typeof m.name === 'string',
91
+ )
92
+ const rawTasks = (Array.isArray(parsed.tasks) ? parsed.tasks : [])
93
+ .filter((t) => t && typeof t === 'object' && typeof t.id === 'string')
94
+ .map((t) => ({ ...t, blockedBy: normalizedBlockedBy(t) }))
95
+
96
+ const byChildId = new Map()
97
+ for (const m of rawMembers) if (m.childId) byChildId.set(String(m.childId), m)
98
+ const resolvedRoots = new Map()
99
+ const resolving = new Set()
100
+ const scopeOfMember = (member) => {
101
+ if (!member) return null
102
+ if (resolvedRoots.has(member)) return resolvedRoots.get(member)
103
+ if (resolving.has(member)) return null // 环形 parent 链:不猜测归属
104
+ resolving.add(member)
105
+ let scope = null
106
+ if (member.projectId || member.rootSessionId) {
107
+ scope = {
108
+ projectId: member.projectId ? String(member.projectId) : null,
109
+ rootSessionId: member.rootSessionId ? String(member.rootSessionId) : null,
110
+ }
111
+ } else if (member.parentSessionId) {
112
+ const parent = byChildId.get(String(member.parentSessionId))
113
+ const parentScope = parent ? scopeOfMember(parent) : null
114
+ scope = parentScope && (parentScope.projectId || parentScope.rootSessionId)
115
+ ? parentScope
116
+ : { projectId: null, rootSessionId: String(member.parentSessionId) }
117
+ }
118
+ resolving.delete(member)
119
+ resolvedRoots.set(member, scope)
120
+ return scope
121
+ }
122
+ const members = rawMembers.map((member) => attributedMember(member, scopeOfMember(member)))
123
+
124
+ const membersByName = new Map()
125
+ for (const member of members) {
126
+ const key = String(member.name)
127
+ if (!membersByName.has(key)) membersByName.set(key, [])
128
+ membersByName.get(key).push(member)
129
+ }
130
+ const tasks = rawTasks.map((task) => {
131
+ if (task.projectId || task.rootSessionId) return task
132
+ // 旧任务能由唯一同名成员唯一确定 root 时回填(审查任务尤其依赖这条迁移路径)。
133
+ const candidates = (membersByName.get(String(task.assignee || '')) || []).filter((m) => m.rootSessionId && !m.legacyUnscoped)
134
+ const roots = [...new Set(candidates.map((m) => String(m.rootSessionId)))]
135
+ if (roots.length === 1) {
136
+ const owner = candidates.find((m) => String(m.rootSessionId) === roots[0])
137
+ return {
138
+ ...task,
139
+ projectId: owner && owner.projectId ? String(owner.projectId) : null,
140
+ rootSessionId: roots[0],
141
+ }
142
+ }
143
+ return { ...task, legacyUnscoped: true }
144
+ })
145
+ return {
146
+ ...parsed,
147
+ members,
148
+ tasks,
149
+ taskSeq: typeof parsed.taskSeq === 'number' ? parsed.taskSeq : 0,
150
+ }
151
+ }
152
+
153
+ function loadTeam() {
154
+ let raw = null
155
+ try {
156
+ raw = readFileSync(teamFile(), 'utf8')
157
+ } catch (err) {
158
+ if (err && err.code !== 'ENOENT') {
159
+ console.error(`[dsh-science team] team.json read failed (treated as empty): ${err && err.message}`)
160
+ }
161
+ return { members: [], tasks: [], taskSeq: 0 }
162
+ }
163
+ let parsed = null
164
+ try {
165
+ parsed = JSON.parse(raw)
166
+ } catch (err) {
167
+ quarantineTeam(`解析失败(${err && err.message})`)
168
+ return { members: [], tasks: [], taskSeq: 0 }
169
+ }
170
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || !Array.isArray(parsed.members) || !Array.isArray(parsed.tasks)) {
171
+ quarantineTeam('结构非法(不是任务板对象或缺 members/tasks 数组)')
172
+ return { members: [], tasks: [], taskSeq: 0 }
173
+ }
174
+ const clean = sanitizeTeamState(parsed, { store: activeStore })
175
+ // v0.8.0:taskSeq 与现存 task-N 最大序号对齐(同 lib/blueprint.js normalizeIdSeq 思路)——
176
+ // 历史会话/并发写回可能让 taskSeq 落后于实际任务数(实测:34 条任务 taskSeq=31),再派发
177
+ // 就会生成重复 task-N id(presenter 首派即撞 task-31)。读档即对齐,一次性自愈。
178
+ let maxTaskSeq = 0
179
+ for (const t of clean.tasks) {
180
+ const m = /^task-(\d+)$/.exec(t.id)
181
+ if (m) maxTaskSeq = Math.max(maxTaskSeq, Number(m[1]))
182
+ }
183
+ if (maxTaskSeq > clean.taskSeq) {
184
+ log(`taskSeq ${clean.taskSeq} 落后于现存最大 task id(task-${maxTaskSeq}),读档对齐`)
185
+ clean.taskSeq = maxTaskSeq
186
+ }
187
+ return clean
188
+ }
189
+
190
+ // T2:成员身份 = (rootSessionId, name)。同一显示名可在不同项目各有一份;查找从不跨 root。
191
+ function memberRootOf(member) {
192
+ return member && member.rootSessionId ? String(member.rootSessionId) : null
193
+ }
194
+
195
+ function findMember(state, rootSessionId, memberName) {
196
+ const root = String(rootSessionId || '')
197
+ if (!root) return null
198
+ return (state.members || []).find(
199
+ (m) => m && String(m.name) === String(memberName) && memberRootOf(m) === root,
200
+ ) || null
201
+ }
202
+
203
+ function membersInRoot(state, rootSessionId) {
204
+ const root = String(rootSessionId || '')
205
+ if (!root) return []
206
+ return (state.members || []).filter((m) => m && memberRootOf(m) === root)
207
+ }
208
+
209
+ // 不依赖 agent 实例的 root 解析(技能唤醒等模块级调用用):优先 roster 的父会话,
210
+ // 其次 Project Store 的 root 绑定;都不命中时视为独立 root 会话自身。
211
+ function rootSessionIdOfAgent(ctx, agent, store) {
212
+ const sid = sessionIdOf({ agent })
213
+ if (!sid) return null
214
+ const scope = resolveScopeOf(ctx, sid, store)
215
+ return scope && scope.rootSessionId ? String(scope.rootSessionId) : String(sid)
216
+ }
217
+
218
+ function resolveScopeOf(ctx, sessionId, store) {
219
+ const s = String(sessionId || '')
220
+ if (!s) return null
221
+ try {
222
+ const scope = resolveProjectContext(ctx, s, { store })
223
+ return scope && scope.ok ? scope.ref : null
224
+ } catch {
225
+ return null
226
+ }
227
+ }
228
+
229
+ // 唤醒单个成员:signal 必传(SubagentSendMessageOptions.signal 必填,dispose 竞态下
230
+ // deliverFollowup 调 options.signal.throwIfAborted());任何 throw 一律视为失败——
231
+ // 不再特判 throwIfAborted(v0.11.0 HIGH-1:该分支只覆盖假阳性路径,真实投递从未发生)。
232
+ // T2:成员按 (rootSessionId, name) 查找——跨项目同名成员不会被误唤醒。
233
+ async function wakeMember(ctx, agent, memberName, text, { rootSessionId = null, store = null } = {}) {
234
+ const state = loadTeam()
235
+ const root = rootSessionId || rootSessionIdOfAgent(ctx, agent, store)
236
+ const m = root ? findMember(state, root, memberName) : null
237
+ const childId = m && m.childId
238
+ if (!childId) {
239
+ return { woken: false, error: `成员 ${memberName} 不在当前项目(或未记录 childId)。先在本项目 sci_team_spawn,不要跨项目唤醒。` }
240
+ }
241
+ try {
242
+ await ctx.subagents.sendMessage(
243
+ agent, childId, [{ type: 'text', text }],
244
+ { signal: AbortSignal.timeout(15000) },
245
+ )
246
+ return { woken: true }
247
+ } catch (err) {
248
+ const msg = String(err && err.message)
249
+ // HIGH-3:跨会话成员不可达(UNAUTHORIZED)→ 清除过期 childId;成员身份(root+name)保留,
250
+ // 下次 spawn 会在本项目内重新激活同一成员。
251
+ if (msg.includes('not belong') || msg.includes('unauthorized') || msg.includes('UNAUTHORIZED')) {
252
+ if (m) {
253
+ m.childId = null
254
+ m.parentSessionId = null
255
+ try {
256
+ // L12:与 persist 同款原子写(tmp+rename),避免崩溃窗口损坏 roster
257
+ const text = JSON.stringify(state, null, 2)
258
+ const tmp = `${teamFile()}.tmp`
259
+ try {
260
+ writeFileSync(tmp, text, 'utf8')
261
+ renameSync(tmp, teamFile())
262
+ } catch {
263
+ writeFileSync(teamFile(), text, 'utf8')
264
+ }
265
+ } catch { /* 清除失败不影响错误上报 */ }
266
+ log(`stale childId cleared for ${memberName}@${root} (cross-session): ${msg}`)
267
+ }
268
+ return { woken: false, error: `成员 ${memberName} 属于其他父会话(childId 已清除,请重新 sci_team_spawn):${msg}`, staleMember: true }
269
+ }
270
+ return { woken: false, error: msg }
271
+ }
272
+ }
273
+
274
+ // spawn 后新装 skill 自动唤醒(brief 待办 8):只唤醒当前 root 下已 spawn 的本角色成员。
275
+ export async function wakeRoleMembers(ctx, agent, role, entry, opts = {}) {
276
+ const store = opts.store || activeStore
277
+ const root = rootSessionIdOfAgent(ctx, agent, store)
278
+ const state = loadTeam()
279
+ const targets = root ? membersInRoot(state, root).filter((m) => m && m.role === role && m.childId) : []
280
+ const text = formatSkillWakeText(entry)
281
+ const woken = []
282
+ const failed = []
283
+ for (const m of targets) {
284
+ const r = await wakeMember(ctx, agent, m.name, text, { rootSessionId: root, store })
285
+ if (r.woken) woken.push(m.name)
286
+ else failed.push({ name: m.name, error: r.error || 'unknown' })
287
+ }
288
+ log(`skill auto-wake: role=${role} root=${root || '?'} targets=${targets.length} woken=${woken.length} failed=${failed.length}`)
289
+ return { woken, failed, targets: targets.length }
290
+ }
291
+
292
+ export function registerTeamTools(ctx, opts = {}) {
293
+ const mirror = opts.mirror
294
+ const store = opts.store || null
295
+ activeStore = store
296
+
297
+ // 原子写:先写 .tmp 再 renameSync 覆盖目标(rename 失败时退回直接写,避免状态丢失)
298
+ function persist(state, exec) {
299
+ const text = JSON.stringify(state, null, 2)
300
+ const tmp = `${teamFile()}.tmp`
301
+ try {
302
+ writeFileSync(tmp, text, 'utf8')
303
+ renameSync(tmp, teamFile())
304
+ } catch (err) {
305
+ log(`atomic persist fallback: ${err && err.message}`)
306
+ writeFileSync(teamFile(), text, 'utf8')
307
+ }
308
+ if (mirror) mirror('team.json', text, exec)
309
+ }
310
+
311
+ // ---- 项目作用域(T2)--------------------------------------------------------
312
+ // 所有团队工具先经这里解析当前 ProjectRef(服务端 session→scope 唯一 seam);
313
+ // 成员按 (rootSessionId, name) 查找,任务按 projectId/rootSessionId 判定归属。
314
+ function scopeOfExec(exec) {
315
+ const scopeRead = (() => {
316
+ try {
317
+ const r = readScope(ctx, exec, { store })
318
+ return r && r.ok ? r.ref : null
319
+ } catch {
320
+ return null
321
+ }
322
+ })()
323
+ if (scopeRead) return scopeRead
324
+ const sid = sessionIdOf(exec)
325
+ return sid
326
+ ? { projectId: null, rootSessionId: String(sid), currentSessionId: String(sid), relationship: 'unknown', capabilities: { read: false, propose: false, writePaper: false, dispatch: false } }
327
+ : null
328
+ }
329
+ function requireScope(exec) {
330
+ const ref = scopeOfExec(exec)
331
+ if (!ref) throw new Error('无法确定调用者:无法解析当前会话作用域(需要主会话/成员上下文)')
332
+ return ref
333
+ }
334
+ function attributionOf(ref) {
335
+ return {
336
+ projectId: ref && ref.projectId ? String(ref.projectId) : null,
337
+ rootSessionId: ref && ref.rootSessionId ? String(ref.rootSessionId) : null,
338
+ }
339
+ }
340
+ function taskInScope(task, ref) {
341
+ if (!task || !ref) return false
342
+ if (task.projectId) return Boolean(ref.projectId) && String(task.projectId) === String(ref.projectId)
343
+ if (task.rootSessionId) return Boolean(ref.rootSessionId) && String(task.rootSessionId) === String(ref.rootSessionId)
344
+ // 旧全局任务板:只有尚未绑定项目、且不是隔离 fork 的会话保留兼容维护路径;
345
+ // 一旦存在项目绑定,任务必须显式归属才能进入项目视图或工具作用域。
346
+ return !ref.projectId && ref.relationship !== 'fork'
347
+ }
348
+ function memberInScope(member, ref) {
349
+ if (!member || !ref) return false
350
+ if (member.projectId) return Boolean(ref.projectId) && String(member.projectId) === String(ref.projectId)
351
+ if (member.rootSessionId) return Boolean(ref.rootSessionId) && String(member.rootSessionId) === String(ref.rootSessionId)
352
+ return !ref.projectId && ref.relationship !== 'fork'
353
+ }
354
+ const wakeInScope = (ref) => (agent, memberName, text) =>
355
+ wakeMember(ctx, agent, memberName, text, { rootSessionId: ref && ref.rootSessionId ? ref.rootSessionId : null, store })
356
+
357
+ // M1(M2 安全审查):调用者身份断言——队长=不在 roster 的调用者;成员=childId 命中 roster。
358
+ // 任务板是派单闸门与覆盖分析的执行事实源:成员只能推进自己名下任务到执行中/失败,
359
+ // completed/cancelled/deleted 与删除/群发一律队长(整合与清理是队长的论文语义职责)。
360
+ function callerOf(exec) {
361
+ const agent = exec && exec.agent
362
+ if (!agent) return { kind: 'anonymous' }
363
+ const callerId = String(agent.id || '')
364
+ const state = loadTeam()
365
+ // childId 是全局唯一子会话 id,因此可用于证明成员身份;成员所属项目由记录里的
366
+ // rootSessionId/projectId 决定(调用者不能用一个 childId 冒充其他 root 的成员)。
367
+ const member = state.members.find((m) => m && m.childId && String(m.childId) === callerId)
368
+ return member ? { kind: 'member', member, agent } : { kind: 'lead', agent }
369
+ }
370
+ function assertLead(exec, action) {
371
+ const caller = callerOf(exec)
372
+ if (caller.kind === 'member') {
373
+ throw new Error(`只有队长可以${action};当前调用者是团队成员 ${caller.member.name}。请把请求发回队长,由队长核对后执行。`)
374
+ }
375
+ // 安全复核:'lead' 原先只表示「不在 roster 里」,附挂(attached)只读会话也满足,
376
+ // 因此必须再校验派单能力,否则只读会话能借队长身份建成员/改任务。
377
+ // 只拒绝明确受限的关系:attached(附挂只读)、teammate(成员已在上分支拦下)、
378
+ // fork(写时复制隔离)。root / unbound(独立根会话)/ unknown(无 session 服务)保留队长能力。
379
+ const ref = scopeOfExec(exec)
380
+ const relationship = ref && ref.relationship
381
+ if (relationship === 'fork') {
382
+ throw new Error(`只有队长可以${action};fork 与父项目写时复制隔离,不能改动任务板。`)
383
+ }
384
+ if (relationship === 'attached' || relationship === 'teammate') {
385
+ throw new Error(`只有队长可以${action};当前会话没有派单权限(附挂会话只读)。`)
386
+ }
387
+ return caller
388
+ }
389
+
390
+ // T2:统一派单内核——普通派单与审查派单共用创建、持久化、唤醒、claimed、蓝图对齐
391
+ // 与失败补偿(对齐失败清除 resultId 标记,唤醒失败任务保持 pending)。
392
+ async function dispatchTask(exec, ref, {
393
+ subject,
394
+ desc,
395
+ assignee = null,
396
+ blockedBy = [],
397
+ resultIds = [],
398
+ isReview = false,
399
+ taskRole = null,
400
+ } = {}) {
401
+ const agent = exec && exec.agent
402
+ const state = loadTeam()
403
+ state.taskSeq = (state.taskSeq || 0) + 1
404
+ const id = `task-${state.taskSeq}`
405
+ const ids = [...new Set((Array.isArray(resultIds) ? resultIds : []).map((value) => String(value || '').trim()).filter(Boolean))]
406
+ const task = {
407
+ id,
408
+ subject: String(subject || '').slice(0, 200),
409
+ desc: String(desc || '').slice(0, 4000),
410
+ assignee: assignee ? String(assignee) : null,
411
+ status: 'pending',
412
+ blockedBy: (Array.isArray(blockedBy) ? blockedBy : []).map(String),
413
+ ...(isReview ? { isReview: true } : {}),
414
+ // 双向对齐回写(v0.6.0 fix5/X4):task 对象也记录 resultId/resultIds
415
+ //(团队 tab 任务行据此显示 res-N 徽章;对齐失败时清除该标记)。
416
+ resultId: ids.length > 0 ? ids[0] : null,
417
+ resultIds: ids,
418
+ taskRole: taskRole || (ids.length > 1 ? 'shared' : 'result_specific'),
419
+ ...attributionOf(ref),
420
+ createdAt: Date.now(),
421
+ }
422
+ state.tasks.push(task)
423
+ // 任务板截断(>200):同时把被截掉的 task id 从蓝图 result.tasks 里摘除(防死引用)
424
+ if (state.tasks.length > 200) {
425
+ const removed = state.tasks.slice(0, state.tasks.length - 200).map((t) => t && t.id).filter(Boolean)
426
+ state.tasks = state.tasks.slice(-200)
427
+ if (removed.length > 0) {
428
+ try {
429
+ pruneTasksFromResults(ctx, removed, { store, exec, mirror })
430
+ } catch (err) {
431
+ log(`prune truncated tasks from blueprint failed: ${err && err.message}`)
432
+ }
433
+ }
434
+ }
435
+ persist(state, exec)
436
+ let wakeResult = { woken: false }
437
+ let taskAfterWake = task
438
+ if (task.assignee) {
439
+ const wakeText = `${isReview ? '新审查任务' : '新任务'} ${id}:${task.subject}\n\n${task.desc}${task.blockedBy.length ? `\n(依赖:${task.blockedBy.join(', ')},若未完成请先在任务板确认)` : ''}\n\n完成后把结果作为消息发回队长。`
440
+ wakeResult = await wakeInScope(ref)(agent, task.assignee, wakeText)
441
+ if (wakeResult.woken) {
442
+ // 唤醒成功即视为成员已领任务:pending → claimed(持久化到任务板)
443
+ // 读-改-写:唤醒期间成员侧可能已回写任务板,先重读 state 再改,避免用 stale 副本覆盖
444
+ const st2 = loadTeam()
445
+ const t2 = st2.tasks.find((x) => x.id === id)
446
+ if (t2) {
447
+ t2.status = 'claimed'
448
+ t2.claimedAt = Date.now()
449
+ persist(st2, exec)
450
+ taskAfterWake = t2
451
+ }
452
+ }
453
+ }
454
+ log(`task dispatched: ${id}@${ref.rootSessionId || '?'} → ${task.assignee || 'unowned'} (${taskAfterWake.status})`)
455
+ // 文章蓝图对齐(v0.6.0):带 result 时把任务挂到对应 result(对齐失败不阻断派发,只回报原因)。
456
+ // 单 Result 保持对象形状(审查派单既有契约),多 Result 返回逐项数组。
457
+ let alignment = null
458
+ if (ids.length > 0) {
459
+ try {
460
+ alignment = ids.length === 1
461
+ ? alignTaskToResult(ctx, id, ids[0], { store, exec, mirror })
462
+ : ids.map((selectedId) => alignTaskToResult(ctx, id, selectedId, { store, exec, mirror }))
463
+ } catch (err) {
464
+ log(`blueprint align failed for ${id} → ${ids.join(',')}: ${err && err.message}`)
465
+ alignment = { error: String(err && err.message) }
466
+ // X4:对齐失败不给 task.resultId——回写清除,避免团队 tab 出现指向未对齐 result 的徽章
467
+ try {
468
+ const st3 = loadTeam()
469
+ const t3 = st3.tasks.find((x) => x.id === id)
470
+ if (t3 && (t3.resultId || t3.resultIds)) {
471
+ t3.resultId = null
472
+ t3.resultIds = []
473
+ t3.updatedAt = Date.now()
474
+ persist(st3, exec)
475
+ }
476
+ } catch (e2) {
477
+ log(`clear resultId after failed align for ${id} failed: ${e2 && e2.message}`)
478
+ }
479
+ }
480
+ }
481
+ return { id, task: taskAfterWake, wake: wakeResult, alignment }
482
+ }
483
+
484
+ async function spawnMember(exec, role, nameOverride, ref) {
485
+ const def = ROLES[role]
486
+ if (!def) throw new Error(`未知角色 ${role}。可用:${Object.keys(ROLES).join(' | ')}`)
487
+ const agent = exec && exec.agent
488
+ if (!agent) throw new Error('无法确定调用者(需要主会话)')
489
+ if (!ref || !ref.rootSessionId) throw new Error('无法确定当前项目作用域,不能生成团队成员')
490
+ ensureLeadProtocol(ctx, exec)
491
+ const prompt = rolePrompt(role)
492
+ if (!prompt) throw new Error(`角色提示词缺失:${role}`)
493
+ const name = (nameOverride || def.member).toLowerCase().replace(/[^a-z0-9-]/g, '-')
494
+ const state = loadTeam()
495
+ // T2:成员身份是 (rootSessionId, name)。其他项目的同名成员不是冲突,也不同步复用。
496
+ const existing = findMember(state, ref.rootSessionId, name)
497
+ if (existing) {
498
+ // HIGH-3 配套:spawn 按名复用时校验 role 一致(role=writer name=reviewer 会派错角色)。
499
+ if (existing.role && existing.role !== role) {
500
+ throw new Error(`成员 ${name} 在本项目已存在且角色为 ${existing.role},与请求的 ${role} 不匹配。请换名或先清理该成员。`)
501
+ }
502
+ if (existing.childId) {
503
+ return {
504
+ ok: true,
505
+ name,
506
+ role: existing.role || role,
507
+ childId: existing.childId,
508
+ reused: true,
509
+ note: '成员已存在,复用现有成员(返回 childId)——直接用 sci_team_send 按成员名唤醒即可。',
510
+ }
511
+ }
512
+ // childId 已被 HIGH-3 清理(会话失效):同一成员身份在本项目内重新激活,不需要改名。
513
+ const reactivated = await activateChild(def, role, name, agent, prompt)
514
+ existing.childId = reactivated
515
+ existing.parentSessionId = (agent && (agent.id || agent.sessionId)) || null
516
+ if (!existing.projectId && ref.projectId) existing.projectId = String(ref.projectId)
517
+ existing.spawnedAt = Date.now()
518
+ persist(state, exec)
519
+ log(`member re-activated: ${name}@${ref.rootSessionId} (${role}) childId=${reactivated}`)
520
+ return { ok: true, name, role, childId: reactivated, reused: true, reactivated: true }
521
+ }
522
+ const childId = await activateChild(def, role, name, agent, prompt)
523
+ state.members.push({
524
+ name,
525
+ role,
526
+ label: def.label,
527
+ childId,
528
+ // F5(v0.7.1):记录 spawn 时的真实父会话 id(成员会话跳转用——客户端 openMemberSession
529
+ // 优先于「当前主会话」推断;httpdata /state 对 team.members 原样透传)。
530
+ // Agent 身份 = agent.id(dsh-agent/types Agent 接口;sessionId 为旧字段名兜底)
531
+ parentSessionId: (agent && (agent.id || agent.sessionId)) || null,
532
+ ...attributionOf(ref),
533
+ spawnedAt: Date.now(),
534
+ })
535
+ persist(state, exec)
536
+ log(`member spawned: ${name}@${ref.rootSessionId} (${role}) childId=${childId}`)
537
+ return { ok: true, name, role, childId }
538
+ }
539
+
540
+ async function activateChild(def, role, name, agent, prompt) {
541
+ // v0.9.0:团队协作规范之后追加 ① simulator 通用模拟规范(新工具 8 步上手)② 该角色已安装
542
+ // 扩展技能的 INDEX.md 索引段(无已安装技能时 roleSkillSectionText 返回 '',提示词保持精简)。
543
+ const fullPrompt = `${prompt}\n\n${teamProtocolText()}${universalOnboardingText(role)}${roleSkillSectionText(role)}`
544
+ const childId = `sci-${name}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
545
+ try {
546
+ const activation = await ctx.subagents.startActivation({
547
+ delivery: 'parent',
548
+ childId,
549
+ provider: 'spawn',
550
+ label: `dsh-science:${role}:${name}`,
551
+ request: {
552
+ prompt: [{ type: 'text', text: fullPrompt }],
553
+ parent: agent,
554
+ },
555
+ signal: AbortSignal.timeout(120000),
556
+ })
557
+ return activation.childId || childId
558
+ } catch (err) {
559
+ log(`spawn FAILED stack: ${err && err.stack}`)
560
+ throw err
561
+ }
562
+ }
563
+
564
+ function teamProtocolText() {
565
+ return [
566
+ '## 团队协作规范(dsh-science)',
567
+ '- 你是科研团队的专职成员,由队长(lead)通过消息给你派任务。',
568
+ '- 收到任务消息后:按你的角色提示词执行,完成后把结果作为回复发回(结果会送达队长)。',
569
+ '- 严格遵守角色提示词中的工具纪律与输出合同;超出职责/需要新资源时如实说明,不要编造。',
570
+ ].join('\n')
571
+ }
572
+
573
+ // -- 生成成员 ---------------------------------------------------------------
574
+ ctx.tools.register({
575
+ name: 'sci_team_spawn',
576
+ description: `生成科研团队专职成员(可续跑的命名子代理)。role 可选:${Object.keys(ROLES).join(' | ')}。需要主会话调用。`,
577
+ parameters: {
578
+ role: { type: 'string' /*必填*/, description: `角色 id:${Object.keys(ROLES).join(' | ')}` },
579
+ name: { type: 'string', description: '成员名(缺省用角色默认名)' },
580
+ },
581
+ output: {
582
+ schema: { type: 'object' },
583
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
584
+ },
585
+ async execute(args, exec) {
586
+ assertLead(exec, '生成团队成员')
587
+ const ref = requireScope(exec)
588
+ return spawnMember(exec, String(args.role), args.name ? String(args.name) : undefined, ref)
589
+ },
590
+ })
591
+
592
+ // -- 整队生成 ----------------------------------------------------------------
593
+ ctx.tools.register({
594
+ name: 'sci_team_spawn_all',
595
+ description: `按默认科研编制一次性生成全部成员(${DEFAULT_TEAM.join(', ')})。当前项目已有的跳过。`,
596
+ parameters: {},
597
+ output: {
598
+ schema: { type: 'object' },
599
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
600
+ },
601
+ async execute(args, exec) {
602
+ assertLead(exec, '生成团队成员')
603
+ const ref = requireScope(exec)
604
+ const results = []
605
+ for (const role of DEFAULT_TEAM) {
606
+ try {
607
+ const def = ROLES[role]
608
+ const state = loadTeam()
609
+ // T2:只看当前 root 的成员——其他项目已有同名默认成员不算“已存在”。
610
+ if (findMember(state, ref.rootSessionId, def.member)) {
611
+ results.push({ name: def.member, role, skipped: true })
612
+ continue
613
+ }
614
+ results.push(await spawnMember(exec, role, def.member, ref))
615
+ } catch (err) {
616
+ results.push({ role, error: String(err && err.message) })
617
+ }
618
+ }
619
+ return { ok: true, results }
620
+ },
621
+ })
622
+
623
+ // -- 任务派发 ----------------------------------------------------------------
624
+ ctx.tools.register({
625
+ name: 'sci_team_dispatch',
626
+ description:
627
+ '仅供队长派发科研任务。单一工作传 result_id;共享质控/公共方法传 result_ids,全部目标 Result 与核心的当前修订均须已确认,否则创建任务前拒绝。assignee 填成员名;blocked_by 默认软警告,config.json 设 blockedGate=hard 时依赖未达终态拒绝。',
628
+ parameters: {
629
+ subject: { type: 'string' /*必填*/, description: '任务标题(一句话)' },
630
+ task_desc: { type: 'string' /*必填*/, description: '任务详细描述:目标、输入、期望输出' },
631
+ assignee: { type: 'string', description: '成员名(可缺省=待领)' },
632
+ blocked_by: { type: 'array', description: '依赖任务 id 数组(task-1 等);依赖须为终态(completed/failed/cancelled)才满足(闸门模式见工具描述)' },
633
+ result_id: { type: 'string' /*必填*/, description: '必填:已获用户确认的文章蓝图 result id(res-N,见 sci_blueprint_overview);文章核心与该 result 均须 confirmed=true' },
634
+ result_ids: { type: 'array', description: '共享工作可传多个已确认 result id;与 result_id 二选一,重复项自动去除' },
635
+ task_role: { type: 'string', description: 'result_specific | shared;绑定多个 Result 时自动为 shared' },
636
+ },
637
+ output: {
638
+ schema: { type: 'object' },
639
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
640
+ },
641
+ async execute(args, exec) {
642
+ const agent = exec && exec.agent
643
+ if (!agent) throw new Error('无法确定调用者')
644
+ ensureLeadProtocol(ctx, exec)
645
+ // 任何执行派单都必须落到已确认的文章承诺上;检查发生在 taskSeq 递增前,
646
+ // 因此拒绝不会留下任务板副作用。
647
+ const resultIds = [...new Set([
648
+ ...(Array.isArray(args && args.result_ids) ? args.result_ids : []),
649
+ args && args.result_id,
650
+ ].map((value) => String(value || '').trim()).filter(Boolean))]
651
+ if (resultIds.length === 0) {
652
+ throw new Error('result_id 或 result_ids 为必填项——每个执行任务必须归属至少一个已确认的 Result。先用 sci_blueprint_overview 查看蓝图;缺少结果时用 sci_result_add 创建并确认。')
653
+ }
654
+ const state = loadTeam()
655
+ const callerId = String(agent.id || '')
656
+ const callerMember = state.members.find((m) => m && m.childId && String(m.childId) === callerId)
657
+ if (callerMember) {
658
+ throw new Error(`只有队长可以派单;当前调用者是团队成员 ${callerMember.name || callerId}。请把任务建议发回队长,由队长核对蓝图确认状态后派发。`)
659
+ }
660
+ // 阶段 2:派单硬闸门改由 Project State 强制(核心与全部目标 Result 当前修订已确认);
661
+ // 断言在任务序号递增前执行——拒绝不产生任务板副作用。
662
+ const scope = readScope(ctx, exec, { store })
663
+ if (!scope.ok) throw new Error(`无法解析派单会话作用域:${scope.message || scope.code}`)
664
+ // M3(语义审查):正式派单是 captain 职责——attached root(dispatch=false)拒绝
665
+ if (!scope.ref.capabilities || !scope.ref.capabilities.dispatch) {
666
+ throw new Error('只有队长(captain root)可以派发执行任务;当前会话对该项目只有读取/提案权限。')
667
+ }
668
+ if (!scope.snapshot) {
669
+ throw new Error('当前会话尚未绑定科研项目——先建立核心主张与 Result(sci_blueprint_set / sci_result_add)并确认后才能派单。')
670
+ }
671
+ try {
672
+ assertDispatchGate(scope.snapshot, resultIds)
673
+ } catch (err) {
674
+ const msg = String((err && err.message) || err)
675
+ if (/显式携带/.test(msg)) throw new Error('派单必须显式携带 result_id 或 result_ids——每个执行任务必须归属至少一个已确认的 Result。先用 sci_blueprint_overview 查看蓝图;缺少结果时用 sci_result_add 创建并确认。')
676
+ if (/尚未建立/.test(msg)) throw new Error('文章蓝图核心尚未建立——未获用户确认的核心主张不能派发执行任务。先向用户复述核心主张与创新点并获明确同意,再调用 sci_blueprint_confirm kind=core。')
677
+ if (/核心当前修订尚未确认/.test(msg)) throw new Error('文章蓝图核心尚未确认——未获用户确认的核心主张不能派发执行任务。先向用户复述核心主张与创新点并获明确同意,再调用 sci_blueprint_confirm kind=core。')
678
+ throw err
679
+ }
680
+ const ref = scope.ref
681
+ // blocked_by 闸门(v0.11.0):依赖必须属于当前项目;未达终态 → 默认 warn,
682
+ // config.json blockedGate=hard → 拒绝派发(任务板不新增)。跨项目/不存在按 missing 计。
683
+ const blockedBy = Array.isArray(args.blocked_by) ? args.blocked_by.map(String) : []
684
+ const gateMode = blockedGateOf()
685
+ const unresolvedDeps = blockedBy
686
+ .map((depId) => {
687
+ const dep = state.tasks.find((t) => t && t.id === depId && taskInScope(t, ref))
688
+ return { id: depId, status: dep ? String(dep.status || 'unknown') : 'missing' }
689
+ })
690
+ .filter((d) => !DONE_STATUSES.has(d.status))
691
+ if (gateMode === 'hard' && unresolvedDeps.length > 0) {
692
+ const detail = unresolvedDeps.map((d) => `${d.id}(${d.status === 'missing' ? '不存在或不属于当前项目' : d.status})`).join('、')
693
+ throw new Error(`依赖未满足,硬闸门拒绝派发:${detail}。先完成依赖任务再派发本任务;如需改为软警告,在 ${join(dataDirOf(), 'config.json')} 设 "blockedGate": "warn"。`)
694
+ }
695
+ // T2:assignee 必须在当前项目内——其他项目的同名成员不是可派单对象,也不要求改名。
696
+ if (args.assignee) {
697
+ const target = findMember(state, ref.rootSessionId, String(args.assignee))
698
+ if (!target) {
699
+ throw new Error(`成员 ${args.assignee} 不在当前项目(属于其他项目的会话),不能跨项目派单。先在本项目 sci_team_spawn。`)
700
+ }
701
+ }
702
+ const dispatched = await dispatchTask(exec, ref, {
703
+ subject: String(args.subject),
704
+ desc: String(args.task_desc || ''),
705
+ assignee: args.assignee ? String(args.assignee) : null,
706
+ blockedBy,
707
+ resultIds,
708
+ taskRole: resultIds.length > 1 || args.task_role === 'shared' ? 'shared' : 'result_specific',
709
+ })
710
+ const out = { ok: true, taskId: dispatched.id, task: dispatched.task, wake: dispatched.wake }
711
+ if (blockedBy.length > 0) out.dependencyGate = { mode: gateMode, unresolved: unresolvedDeps }
712
+ if (dispatched.alignment) out.blueprintAlign = dispatched.alignment
713
+ return out
714
+ },
715
+ })
716
+
717
+ // -- 团队状态 ----------------------------------------------------------------
718
+ ctx.tools.register({
719
+ name: 'sci_team_status',
720
+ description: '查看科研团队现状:成员(角色)与任务板(状态/负责人/依赖)。',
721
+ parameters: {},
722
+ output: {
723
+ schema: { type: 'object' },
724
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
725
+ },
726
+ async execute(args, exec) {
727
+ const ref = requireScope(exec)
728
+ const state = loadTeam()
729
+ return {
730
+ members: state.members.filter((m) => memberInScope(m, ref)).map((m) => ({
731
+ name: String(m.name),
732
+ role: String(m.role || ''),
733
+ label: String(m.label || m.role || m.name),
734
+ // 成员会话跳转只使用当前 root 下的 childId(其他项目的 childId 不下发)。
735
+ childId: m.childId ? String(m.childId) : null,
736
+ })),
737
+ tasks: state.tasks.filter((t) => taskInScope(t, ref)).slice(-50).map((t) => ({
738
+ id: String(t.id),
739
+ subject: String(t.subject || ''),
740
+ status: String(t.status || 'pending'),
741
+ assignee: t.assignee ? String(t.assignee) : null,
742
+ blockedBy: Array.isArray(t.blockedBy) ? t.blockedBy.map(String) : [],
743
+ resultIds: [...new Set([...(Array.isArray(t.resultIds) ? t.resultIds : []), t.resultId].filter(Boolean).map(String))],
744
+ taskRole: t.taskRole === 'shared' ? 'shared' : 'result_specific',
745
+ })),
746
+ }
747
+ },
748
+ })
749
+
750
+ // -- 审查派发 ----------------------------------------------------------------
751
+ ctx.tools.register({
752
+ name: 'sci_review_send',
753
+ description:
754
+ '把审查工作派给团队 reviewer 成员(未生成则自动生成)。scope: turn(回答审查) | computation(计算过程) | evidence(文章证据) | journal(期刊审稿模拟)。审查任务默认不要求对齐到蓝图 result(质量闸门,非证据工作);确需归档到某 result 时可传 result_id。',
755
+ parameters: {
756
+ scope: { type: 'string' /*必填*/, description: 'turn | computation | evidence | journal' },
757
+ target: { type: 'string', description: '审查对象说明(turn 号/文件路径/章节名)' },
758
+ note: { type: 'string', description: '补充要求' },
759
+ result_id: { type: 'string', description: '可选:文章蓝图 result id(res-N);提供时该审查任务挂入该 result(一般不需要)' },
760
+ },
761
+ output: {
762
+ schema: { type: 'object' },
763
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
764
+ },
765
+ async execute(args, exec) {
766
+ assertLead(exec, '派发审查任务')
767
+ const scope = String(args.scope || '')
768
+ if (!REVIEW_SCOPES.includes(scope)) {
769
+ throw new Error(`scope 非法:${scope || '(空)'}(可选:${REVIEW_SCOPES.join(' | ')})`)
770
+ }
771
+ ensureLeadProtocol(ctx, exec)
772
+ const ref = requireScope(exec)
773
+ const state = loadTeam()
774
+ if (!membersInRoot(state, ref.rootSessionId).some((m) => m.role === 'reviewer')) {
775
+ await spawnMember(exec, 'reviewer', ROLES.reviewer.member, ref)
776
+ }
777
+ const scopeText = {
778
+ turn: REVIEW_SCOPE_TEXT.turn,
779
+ computation: REVIEW_SCOPE_TEXT.computation,
780
+ evidence: REVIEW_SCOPE_TEXT.evidence,
781
+ journal: REVIEW_SCOPE_TEXT.journal,
782
+ }[scope]
783
+ // 蓝图深度绑定(v0.9.0 Track 2 B3):evidence scope 自动带上蓝图 claims 逐条核对清单
784
+ //(蓝图存在且有 result 时)——审查员逐条核对 claim 的证据链,而不是凭印象泛审。
785
+ let claimsSection = ''
786
+ if (scope === 'evidence') {
787
+ try {
788
+ const scopeRead = readScope(ctx, exec, { store })
789
+ const bp = scopeRead.ok && scopeRead.snapshot ? blueprintViewOf(scopeRead.snapshot) : { results: [], core: {} }
790
+ const claimed = (bp.results || []).filter((r) => r && (r.claim || '').trim())
791
+ if (claimed.length > 0) {
792
+ const rows = []
793
+ for (const r of claimed) {
794
+ const claims = (Array.isArray(r.claims) ? r.claims : []).filter((c) => c && c.status !== 'retired' && String(c.text || '').trim())
795
+ const taskText = (Array.isArray(r.tasks) ? r.tasks : []).join('、') || '无'
796
+ const figureText = (Array.isArray(r.figures) ? r.figures : []).join('、') || '无'
797
+ if (claims.length === 0) rows.push(`- ${r.id}@r${r.revision || 1}: ${r.claim};任务 ${taskText},图表 ${figureText}`)
798
+ else for (const claim of claims) rows.push(`- ${claim.id}@r${claim.revision || 1}: ${claim.text};任务 ${taskText},图表 ${figureText}`)
799
+ }
800
+ claimsSection = `\n\n蓝图 Claim 逐条核对清单(每条都要在 findings 里给出结论,check=blueprint-claim;claim 字段原样填写冒号前稳定标识符):\n${rows.join('\n')}`
801
+ }
802
+ } catch {
803
+ /* 蓝图缺失/损坏不阻断审查派发 */
804
+ }
805
+ }
806
+ const subject = `[${scope}] 审查:${String(args.target || '最近工作').slice(0, 80)}`
807
+ const desc = `${scopeText}${claimsSection}${args.note ? `\n补充要求:${args.note}` : ''}\n目标对象:${args.target || '最近工作'}\n\n输出 findings JSON。`
808
+ const resultId = args.result_id ? String(args.result_id) : null
809
+ // T2:审查派单与普通派单共用 dispatchTask 内核(创建/落盘/唤醒/claimed/对齐/失败补偿)。
810
+ const dispatched = await dispatchTask(exec, ref, {
811
+ subject,
812
+ desc,
813
+ assignee: 'reviewer',
814
+ blockedBy: [],
815
+ resultIds: resultId ? [resultId] : [],
816
+ isReview: true,
817
+ })
818
+ log(`review dispatched: ${dispatched.id}@${ref.rootSessionId || '?'} (${dispatched.wake.woken ? 'claimed' : 'pending'}${resultId ? ', aligned' : ''})`)
819
+ const out = { ok: true, taskId: dispatched.id, reviewer: 'reviewer', isReview: true, wake: dispatched.wake }
820
+ if (dispatched.alignment) out.blueprintAlign = dispatched.alignment
821
+ return out
822
+ },
823
+ })
824
+
825
+ // -- 任务状态回写(队长在成员回报结果后标记完成)--------------------------------
826
+ // X2:status 枚举扩展 cancelled(主动取消,区别于 failed)——coverage 对 cancelled 豁免对齐,
827
+ // 客户端进度图例按灰色计数。
828
+ const TASK_STATUSES = ['pending', 'claimed', 'in_progress', 'completed', 'failed', 'cancelled']
829
+ ctx.tools.register({
830
+ name: 'sci_team_update_task',
831
+ description: '更新团队任务板状态。成员回报结果后由队长调用标记 completed(或 failed/in_progress/cancelled)。task_id 形如 task-3。',
832
+ parameters: {
833
+ task_id: { type: 'string' /*必填*/, description: '任务 id(task-N)' },
834
+ status: { type: 'string' /*必填*/, description: `枚举:${TASK_STATUSES.join(' | ')}` },
835
+ result_note: { type: 'string', description: '结果摘要(可选,记录成员产出要点)' },
836
+ },
837
+ output: {
838
+ schema: { type: 'object' },
839
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
840
+ },
841
+ async execute(args, exec) {
842
+ const ref = requireScope(exec)
843
+ const state = loadTeam()
844
+ const task = state.tasks.find((t) => t.id === String(args.task_id))
845
+ if (!task) throw new Error(`任务 ${args.task_id} 不存在`)
846
+ const status = String(args.status)
847
+ if (!TASK_STATUSES.includes(status)) {
848
+ throw new Error(`非法 status "${status}"(可用枚举:${TASK_STATUSES.join(' | ')})`)
849
+ }
850
+ const caller = callerOf(exec)
851
+ // T2:任务必须先属于调用者的项目作用域;跨项目只按“另一个会话”拒绝,不泄漏对方任务内容。
852
+ const callerRef = caller.kind === 'member'
853
+ ? { projectId: caller.member.projectId || ref.projectId || null, rootSessionId: caller.member.rootSessionId || ref.rootSessionId }
854
+ : ref
855
+ if (!taskInScope(task, callerRef)) {
856
+ throw new Error(`任务 ${task.id} 属于另一个会话(${task.rootSessionId || task.projectId || '未归属的旧任务'}),不能跨项目操作任务板。`)
857
+ }
858
+ if (caller.kind === 'member') {
859
+ // 成员仅可推进自己名下任务的执行状态;completed(整合完成)与 cancelled/deleted 由队长决定
860
+ if (task.assignee !== caller.member.name) {
861
+ throw new Error(`成员只能更新自己名下的任务;任务 ${task.id} 的负责人是 ${task.assignee || '(未分配)'}。`)
862
+ }
863
+ if (!['in_progress', 'failed'].includes(status)) {
864
+ throw new Error(`成员只能把任务标记为 in_progress | failed;completed/cancelled 由队长核对回报后统一标记。请把结果发回队长。`)
865
+ }
866
+ }
867
+ task.status = status
868
+ if (args.result_note) task.result = String(args.result_note).slice(0, 2000)
869
+ task.updatedAt = Date.now()
870
+ persist(state, exec)
871
+ return { ok: true, taskId: task.id, status: task.status }
872
+ },
873
+ })
874
+
875
+ // -- 任务删除(X2):标记 deleted(tombstone 保留在任务板上)+ 从蓝图 result.tasks 摘除 ----
876
+ // 与 cancelled 的区别:deleted 表示"这条任务不该存在"(误派/废弃),终态且从文章归属中摘除;
877
+ // 记录仍保留(墓碑),进度图例按灰色计数,审计可查。
878
+ ctx.tools.register({
879
+ name: 'sci_team_delete_task',
880
+ description:
881
+ '删除团队任务板上的任务:任务标记 deleted(墓碑保留,可审计),并从文章蓝图 result.tasks 中摘除对齐(若有)。误派/废弃任务用本工具清理;status 已是 deleted 时幂等返回。',
882
+ parameters: {
883
+ task_id: { type: 'string' /*必填*/, description: '任务 id(task-N)' },
884
+ },
885
+ output: {
886
+ schema: { type: 'object' },
887
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
888
+ },
889
+ async execute(args, exec) {
890
+ assertLead(exec, '删除任务')
891
+ const ref = requireScope(exec)
892
+ const state = loadTeam()
893
+ const task = state.tasks.find((t) => t.id === String(args.task_id))
894
+ if (!task) throw new Error(`任务 ${args.task_id} 不存在`)
895
+ if (!taskInScope(task, ref)) {
896
+ throw new Error(`任务 ${task.id} 属于另一个会话(${task.rootSessionId || task.projectId || '未归属的旧任务'}),不能跨项目删除。`)
897
+ }
898
+ if (task.status === 'deleted') {
899
+ return { ok: true, taskId: task.id, status: 'deleted', note: '任务已是 deleted(幂等,无变化)。' }
900
+ }
901
+ task.status = 'deleted'
902
+ task.deletedAt = Date.now()
903
+ task.updatedAt = task.deletedAt
904
+ persist(state, exec)
905
+ // 蓝图摘除(调 lib/blueprint.js 摘除逻辑):从所有 result.tasks 移除该任务 id(幂等)
906
+ let blueprintPrune = { pruned: false }
907
+ try {
908
+ blueprintPrune = { pruned: pruneTasksFromResults(ctx, [task.id], { store, exec, mirror }) }
909
+ } catch (err) {
910
+ log(`blueprint prune failed for ${task.id}: ${err && err.message}`)
911
+ blueprintPrune = { pruned: false, error: String(err && err.message) }
912
+ }
913
+ log(`task deleted: ${task.id}(tombstone 保留)`)
914
+ return { ok: true, taskId: task.id, status: 'deleted', deletedAt: task.deletedAt, blueprintPrune }
915
+ },
916
+ })
917
+
918
+ // -- 给成员发消息 --------------------------------------------------------------
919
+ ctx.tools.register({
920
+ name: 'sci_team_send',
921
+ description: '向指定团队成员发消息(唤起其处理)。to 为成员名。',
922
+ parameters: {
923
+ to: { type: 'string' /*必填*/, description: '成员名' },
924
+ message: { type: 'string' /*必填*/, description: '消息内容' },
925
+ },
926
+ output: {
927
+ schema: { type: 'object' },
928
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
929
+ },
930
+ async execute(args, exec) {
931
+ const agent = exec && exec.agent
932
+ if (!agent) throw new Error('无法确定调用者')
933
+ assertLead(exec, '向成员发消息')
934
+ const ref = requireScope(exec)
935
+ const wakeResult = await wakeInScope(ref)(agent, String(args.to), String(args.message).slice(0, 4000))
936
+ if (!wakeResult.woken) throw new Error(`成员 ${args.to} 不在当前项目或不可达:${wakeResult.error}`)
937
+ return { ok: true, to: args.to }
938
+ },
939
+ })
940
+
941
+ // 新装 skill 自动唤醒:skillmenu.installSkill 成功后回调,按 role 唤醒已 spawn 成员
942
+ setMemberWakeHook((agent, role, entry) => wakeRoleMembers(ctx, agent, role, entry, { store }))
943
+
944
+ log('team tools registered (spawn/spawn_all/dispatch/status/review_send/send on ctx.subagents)')
945
+ }