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
@@ -0,0 +1,227 @@
1
+ // dsh-science — 工作区 Project Catalog(路线 B T7 / T-A6)
2
+ //
3
+ // 输入只能是当前 sessionId。输出是课题摘要和 opaque open handle。
4
+ // 打开课题只返回已绑定 root,供 uiWorkspace.openSession 使用,不静默 attach。
5
+
6
+ import { createHmac, timingSafeEqual } from 'node:crypto'
7
+ import { existsSync, readFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { dataDirOf } from './store.js'
10
+ import { resolveProjectContext } from './project-context.js'
11
+ import { liveSessionOf, workspaceFactOf, workspaceKeyOf } from './workspace-key.js'
12
+
13
+ export const LEGACY_UNASSIGNED = 'legacy-unassigned'
14
+ export const WORKSPACE_ASSIGNED = 'assigned'
15
+
16
+ const STAGE_LABELS = Object.freeze({
17
+ explore: '研究探索',
18
+ frame: '文章结构',
19
+ execute: '任务细化',
20
+ synthesize: '分析与绘图',
21
+ draft: '论文写作',
22
+ audit: '汇报与投稿',
23
+ })
24
+
25
+ const RUNNING = new Set(['claimed', 'in_progress', 'running', 'working'])
26
+ const QUESTION_EXCERPT = 160
27
+ const FORBIDDEN_SUMMARY_KEYS = ['projectId', 'rootSessionId', 'workspaceKey', 'workspace_key', 'path', 'cwd', 'snapshot', 'sqlite']
28
+
29
+ export function openHandleOf(secret, { sessionId, projectId, rootSessionId }) {
30
+ const payload = Buffer.from(JSON.stringify({
31
+ v: 1,
32
+ s: String(sessionId || ''),
33
+ p: String(projectId || ''),
34
+ r: String(rootSessionId || ''),
35
+ })).toString('base64url')
36
+ const mac = createHmac('sha256', String(secret || '')).update(payload).digest('base64url')
37
+ return `${payload}.${mac}`
38
+ }
39
+
40
+ export function verifyOpenHandle(secret, handle, sessionId) {
41
+ const text = String(handle || '')
42
+ const dot = text.lastIndexOf('.')
43
+ if (dot <= 0) return null
44
+ const payload = text.slice(0, dot)
45
+ const mac = text.slice(dot + 1)
46
+ const expected = createHmac('sha256', String(secret || '')).update(payload).digest('base64url')
47
+ const left = Buffer.from(expected)
48
+ const right = Buffer.from(mac)
49
+ if (left.length !== right.length || !timingSafeEqual(left, right)) return null
50
+ let body = null
51
+ try { body = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) } catch { return null }
52
+ if (!body || body.v !== 1 || String(body.s || '') !== String(sessionId || '')) return null
53
+ if (!body.p || !body.r) return null
54
+ return { projectId: String(body.p), rootSessionId: String(body.r) }
55
+ }
56
+
57
+ function loadTeamTasks() {
58
+ try {
59
+ const file = join(dataDirOf(), 'team.json')
60
+ if (!existsSync(file)) return []
61
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
62
+ return Array.isArray(parsed && parsed.tasks) ? parsed.tasks : []
63
+ } catch {
64
+ return []
65
+ }
66
+ }
67
+
68
+ function tasksFor(projectId, rootSessionId) {
69
+ return loadTeamTasks().filter((task) => {
70
+ if (!task || typeof task !== 'object') return false
71
+ if (task.projectId && String(task.projectId) === String(projectId)) return true
72
+ if (!task.projectId && task.rootSessionId && String(task.rootSessionId) === String(rootSessionId)) return true
73
+ return false
74
+ })
75
+ }
76
+
77
+ function isBlocked(task) {
78
+ if (!task) return false
79
+ if (task.status === 'blocked' || task.isBlocked === true || task.blocked === true) return true
80
+ return Array.isArray(task.blockers) && task.blockers.length > 0
81
+ }
82
+
83
+ export function attentionOf(snapshot, tasks) {
84
+ const paper = snapshot && snapshot.paper && typeof snapshot.paper === 'object' ? snapshot.paper : {}
85
+ const core = paper.core && typeof paper.core === 'object' ? paper.core : null
86
+ let attention = 0
87
+ if (core && (core.claim || core.title) && core.confirmed !== true) attention += 1
88
+ for (const result of Array.isArray(paper.results) ? paper.results : []) {
89
+ if (!result || result.confirmed === true) continue
90
+ if (result.status === 'dropped' || result.manuscriptRole === 'excluded') continue
91
+ attention += 1
92
+ }
93
+ let running = 0
94
+ let blocked = 0
95
+ for (const task of Array.isArray(tasks) ? tasks : []) {
96
+ if (RUNNING.has(String(task.status || ''))) running += 1
97
+ if (isBlocked(task)) blocked += 1
98
+ else if (task.status === 'failed') attention += 1
99
+ }
100
+ return { attention, running, blocked }
101
+ }
102
+
103
+ function excerptOf(text) {
104
+ const value = String(text || '').replace(/\s+/g, ' ').trim()
105
+ if (value.length <= QUESTION_EXCERPT) return value
106
+ return `${value.slice(0, QUESTION_EXCERPT)}…`
107
+ }
108
+
109
+ function publicSummary(row, snapshot, { current, openable, handle }) {
110
+ const paper = snapshot && snapshot.paper && typeof snapshot.paper === 'object' ? snapshot.paper : {}
111
+ const stage = String(paper.stage || 'explore')
112
+ const counts = attentionOf(snapshot, tasksFor(row.projectId, row.rootSessionId))
113
+ return {
114
+ title: String((snapshot && snapshot.metadata && snapshot.metadata.title) || row.title || '未命名课题'),
115
+ questionExcerpt: excerptOf(paper.question || ''),
116
+ stage,
117
+ stageLabel: STAGE_LABELS[stage] || '研究探索',
118
+ attentionCount: counts.attention,
119
+ runningCount: counts.running,
120
+ blockedCount: counts.blocked,
121
+ updatedAt: Number((snapshot && snapshot.metadata && snapshot.metadata.updatedAt) || row.updatedAt || 0),
122
+ current: current === true,
123
+ openable: openable === true,
124
+ openHandle: handle,
125
+ }
126
+ }
127
+
128
+ export function summaryLeaks(value) {
129
+ const found = []
130
+ const walk = (node, path) => {
131
+ if (!node || typeof node !== 'object') return
132
+ for (const [key, child] of Object.entries(node)) {
133
+ if (FORBIDDEN_SUMMARY_KEYS.includes(key)) found.push(path ? `${path}.${key}` : key)
134
+ if (child && typeof child === 'object') walk(child, path ? `${path}.${key}` : key)
135
+ }
136
+ }
137
+ walk(value, '')
138
+ return found
139
+ }
140
+
141
+ function chosenWorkspaceFact(ctx, sessionId, ref) {
142
+ const own = workspaceFactOf(ctx, sessionId)
143
+ if (own.status === 'unique' || own.status === 'ambiguous') return own
144
+ if (ref && ref.rootSessionId && String(ref.rootSessionId) !== String(sessionId)) {
145
+ return workspaceFactOf(ctx, ref.rootSessionId)
146
+ }
147
+ return own
148
+ }
149
+
150
+ export function backfillWorkspaceKeys(store, ctx) {
151
+ const rows = store.listProjectAuthRows()
152
+ const out = []
153
+ for (const row of rows) {
154
+ if (row.workspaceStatus === WORKSPACE_ASSIGNED && row.workspaceKey) {
155
+ out.push({ projectId: row.projectId, status: WORKSPACE_ASSIGNED, changed: false })
156
+ continue
157
+ }
158
+ const fact = workspaceFactOf(ctx, row.rootSessionId)
159
+ if (fact.status !== 'unique') {
160
+ out.push({ projectId: row.projectId, status: LEGACY_UNASSIGNED, changed: false, reason: fact.status })
161
+ continue
162
+ }
163
+ const assigned = store.assignWorkspaceKey(row.projectId, workspaceKeyOf(fact.path))
164
+ out.push({ projectId: row.projectId, status: WORKSPACE_ASSIGNED, changed: assigned.changed })
165
+ }
166
+ return out
167
+ }
168
+
169
+ export function catalogForSession(ctx, sessionId, { store }) {
170
+ const scope = resolveProjectContext(ctx, sessionId, { store })
171
+ if (!scope.ok) return { status: 404, body: { error: scope.code || 'unknown-session' } }
172
+ const chosen = chosenWorkspaceFact(ctx, sessionId, scope.ref)
173
+ if (chosen.status === 'ambiguous') {
174
+ return { status: 200, body: { catalogRevision: 0, generatedAt: Date.now(), assignment: 'ambiguous', projects: [] } }
175
+ }
176
+ if (chosen.status !== 'unique') {
177
+ const assignment = scope.ref && scope.ref.projectId ? 'workspace-unknown' : 'unbound'
178
+ return { status: 200, body: { catalogRevision: 0, generatedAt: Date.now(), assignment, projects: [] } }
179
+ }
180
+ backfillWorkspaceKeys(store, ctx)
181
+ const key = workspaceKeyOf(chosen.path)
182
+ const rows = store.listCatalogProjects(key)
183
+ const secret = store.catalogSecret()
184
+ const currentId = scope.ref && scope.ref.projectId ? String(scope.ref.projectId) : ''
185
+ const currentAuth = currentId ? store.projectAuthOf(currentId) : null
186
+ let assignment = 'unbound'
187
+ if (currentAuth && currentAuth.workspaceStatus === LEGACY_UNASSIGNED) assignment = LEGACY_UNASSIGNED
188
+ else if (currentAuth && currentAuth.workspaceStatus === WORKSPACE_ASSIGNED) assignment = WORKSPACE_ASSIGNED
189
+ const projects = rows.map((row) => {
190
+ const snap = store.snapshotOf(row.projectId)
191
+ const snapshot = snap && !snap.corrupt ? snap.snapshot : null
192
+ return publicSummary(row, snapshot, {
193
+ current: currentId !== '' && row.projectId === currentId,
194
+ openable: Boolean(liveSessionOf(ctx, row.rootSessionId)),
195
+ handle: openHandleOf(secret, { sessionId, projectId: row.projectId, rootSessionId: row.rootSessionId }),
196
+ })
197
+ })
198
+ const revision = projects.reduce((max, item) => Math.max(max, Number(item.updatedAt) || 0), 0)
199
+ return {
200
+ status: 200,
201
+ body: { catalogRevision: revision, generatedAt: Date.now(), assignment, projects },
202
+ }
203
+ }
204
+
205
+ export function openCatalogProject(ctx, sessionId, body, { store }) {
206
+ const scope = resolveProjectContext(ctx, sessionId, { store })
207
+ if (!scope.ok) return { status: 404, body: { error: scope.code || 'unknown-session' } }
208
+ const chosen = chosenWorkspaceFact(ctx, sessionId, scope.ref)
209
+ if (chosen.status !== 'unique') return { status: 403, body: { error: 'forbidden' } }
210
+ const verified = verifyOpenHandle(store.catalogSecret(), body && body.openHandle, sessionId)
211
+ if (!verified) return { status: 403, body: { error: 'forbidden' } }
212
+ const auth = store.projectAuthOf(verified.projectId)
213
+ if (!auth || auth.workspaceStatus !== WORKSPACE_ASSIGNED || auth.workspaceKey !== workspaceKeyOf(chosen.path)) {
214
+ return { status: 403, body: { error: 'forbidden' } }
215
+ }
216
+ if (String(auth.rootSessionId) !== verified.rootSessionId) return { status: 403, body: { error: 'forbidden' } }
217
+ if (!liveSessionOf(ctx, auth.rootSessionId)) {
218
+ return {
219
+ status: 409,
220
+ body: {
221
+ kind: 'unavailable',
222
+ message: '原会话当前不在线。请先在 DSH 工作区中打开该会话,或回到当时的对话。当前会话不会被改绑到这个课题。',
223
+ },
224
+ }
225
+ }
226
+ return { status: 200, body: { kind: 'open', sessionId: String(auth.rootSessionId) } }
227
+ }
@@ -0,0 +1,282 @@
1
+ // dsh-science — 项目作用域解析(ProjectContext,T0.4 spike → 阶段 1 正式 module)
2
+ //
3
+ // 设计真源 §7:客户端不得提交任意 projectId/root session/磁盘路径;宿主根据当前
4
+ // session 在服务端解析 ProjectRef。本模块是唯一的 session → scope 解析 seam:
5
+ // host 工具、Project Remote act、HTTP 路由都必须经它取 scope,不得自行推断。
6
+ //
7
+ // 解析规则(spike 冻结版,阶段 1 按此扩展):
8
+ // 1. 只认 live session(ctx.sessions.get);查不到 → unknown-session,不猜。
9
+ // 2. 队友身份必须由 roster 证明(team.json 成员的 childId + spawn 时记录的
10
+ // parentSessionId);官方 ctx.agentTeams.tryMembership 可用时优先采用。
11
+ // 只有 parentSession 不构成队友证据——普通 fork 也有父 session。
12
+ // 3. 有 parentSession 但不在 roster → fork:写时复制隔离,绝不继承父项目。
13
+ // 4. root/attached 绑定查 Project Store:primaryRootSessionId 或 attachedRootSessionIds。
14
+ // 5. 未绑定时 relationship='unbound':读取放行(空状态),首次持久写才建项目。
15
+
16
+ import { existsSync, readFileSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { dataDirOf } from './store.js'
19
+ import { workspaceFactOf, workspaceKeyOf } from './workspace-key.js'
20
+
21
+ function log(msg) {
22
+ console.log(`[dsh-science project-context] ${msg}`)
23
+ }
24
+
25
+ // ---- roster(身份事实的只读视图)---------------------------------------------
26
+ // team.json 是本插件自管团队的 roster(成员=命名子代理,spawn 时记录 childId 与
27
+ // 真实父会话)。这里只读 members,绝不写;损坏按空 roster 处理(宁缺毋滥)。
28
+ function rosterMembers() {
29
+ try {
30
+ const file = join(dataDirOf(), 'team.json')
31
+ if (!existsSync(file)) return []
32
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
33
+ const members = Array.isArray(parsed && parsed.members) ? parsed.members : []
34
+ return members.filter((m) => m && typeof m === 'object' && typeof m.name === 'string')
35
+ } catch {
36
+ return []
37
+ }
38
+ }
39
+
40
+ // 官方 Agent Team 身份在工具执行路径(有 agent 实例)经 tryMembership 核对;
41
+ // scope 解析只有 sessionId,统一用自管 roster 的 childId 精确匹配(spawn 时记录,等价可信)。
42
+
43
+ /**
44
+ * 把当前 session 解析为 ProjectRef。这是唯一 scope seam。
45
+ * @param ctx Cordis host context(需要 sessions 服务)
46
+ * @param sessionId 当前会话 id —— 客户端只能提交这一项
47
+ * @param opts.store Project Store(resolveProjectRef 用;测试注入)
48
+ */
49
+ export function resolveProjectContext(ctx, sessionId, opts = {}) {
50
+ const sid = String(sessionId || '')
51
+ if (!sid) return { ok: false, code: 'unknown-session', message: '缺少会话 id' }
52
+ if (!ctx) return { ok: false, code: 'unknown-session', message: '宿主上下文不可用' }
53
+ let sessions = null
54
+ try {
55
+ sessions = ctx.get('sessions')
56
+ } catch {
57
+ try {
58
+ sessions = ctx.sessions
59
+ } catch {
60
+ sessions = null
61
+ }
62
+ }
63
+ let session = null
64
+ let noSessionService = false
65
+ if (!sessions || typeof sessions.get !== 'function') {
66
+ // 无 sessions 服务(纯 host/headless 组合):把调用者视作独立 root 会话——
67
+ // sessionId 来自宿主 agent(host 侧事实),隔离语义不变;web 组合始终有 sessions。
68
+ noSessionService = true
69
+ } else {
70
+ try {
71
+ session = sessions.get(sid)
72
+ } catch (err) {
73
+ log(`sessions.get failed: ${err && err.message}`)
74
+ session = undefined
75
+ }
76
+ if (!session) return { ok: false, code: 'unknown-session', message: `会话 ${sid} 不在线` }
77
+ }
78
+
79
+ const header = noSessionService ? { id: sid, parentSession: null } : (session.header || {})
80
+ const parentSessionId = header.parentSession ? String(header.parentSession) : null
81
+
82
+ // 队友证据:roster 的 childId 精确匹配(scope 解析只有 sessionId,拿不到 agent 实例,
83
+ // 官方 tryMembership(agent) 无法在此调用;自管 roster 的 childId 即子会话 id,等价可信)。
84
+ let teammateOf = null
85
+ const members = rosterMembers()
86
+ const member = members.find((m) => String(m.childId || '') === sid)
87
+ if (member && member.parentSessionId) {
88
+ teammateOf = String(member.parentSessionId)
89
+ }
90
+
91
+ const store = opts.store || null
92
+ if (teammateOf) {
93
+ // 队友与队长共用 root;绑定来自队长的 root session,不来自队友自己。
94
+ const binding = store ? store.bindingOfRootSession(teammateOf) : null
95
+ return {
96
+ ok: true,
97
+ ref: {
98
+ projectId: binding ? binding.projectId : null,
99
+ rootSessionId: teammateOf,
100
+ currentSessionId: sid,
101
+ relationship: 'teammate',
102
+ capabilities: { read: true, propose: true, writePaper: false, dispatch: false },
103
+ },
104
+ }
105
+ }
106
+
107
+ if (parentSessionId) {
108
+ // 普通 fork / 非成员子代理:写时复制隔离。父项目的绑定不继承(首版无自动 merge)。
109
+ // L2:fork 的能力标志全 false——其写能力只能经"新建项目/显式 attach"流程显式授予。
110
+ return {
111
+ ok: true,
112
+ ref: {
113
+ projectId: null,
114
+ rootSessionId: sid,
115
+ currentSessionId: sid,
116
+ relationship: 'fork',
117
+ forkOf: parentSessionId,
118
+ capabilities: { read: false, propose: false, writePaper: false, dispatch: false },
119
+ },
120
+ }
121
+ }
122
+
123
+ // root session:查自己的绑定(primary 或 attached)。
124
+ const binding = store ? store.bindingOfRootSession(sid) : null
125
+ if (binding) {
126
+ const isCaptain = binding.primaryRootSessionId === sid
127
+ return {
128
+ ok: true,
129
+ ref: {
130
+ projectId: binding.projectId,
131
+ rootSessionId: binding.primaryRootSessionId,
132
+ currentSessionId: sid,
133
+ relationship: isCaptain ? 'root' : 'attached',
134
+ capabilities: {
135
+ read: true,
136
+ propose: true,
137
+ writePaper: isCaptain,
138
+ dispatch: isCaptain,
139
+ },
140
+ },
141
+ }
142
+ }
143
+ return {
144
+ ok: true,
145
+ ref: {
146
+ projectId: null,
147
+ rootSessionId: sid,
148
+ currentSessionId: sid,
149
+ relationship: 'unbound',
150
+ capabilities: { read: true, propose: true, writePaper: true, dispatch: true },
151
+ },
152
+ }
153
+ }
154
+
155
+ // ---- 写权限断言(领域边界,供 execute 前调用)--------------------------------
156
+ export const CAPABILITY_ERRORS = {
157
+ 'no-project': '当前会话尚未绑定科研项目',
158
+ 'forbidden': '当前会话没有论文语义写权限(成员只能提交提案与任务回报)',
159
+ 'fork-isolated': '普通 fork 与父项目写时复制隔离,不能直接写入父项目',
160
+ }
161
+
162
+ export function assertPaperWriteAllowed(ref) {
163
+ if (!ref || !ref.capabilities) return { ok: false, code: 'no-project' }
164
+ if (ref.relationship === 'fork') return { ok: false, code: 'fork-isolated' }
165
+ if (!ref.capabilities.writePaper) return { ok: false, code: 'forbidden' }
166
+ return { ok: true }
167
+ }
168
+
169
+ export function assertReadAllowed(ref) {
170
+ if (!ref || !ref.capabilities) return { ok: false, code: 'no-project' }
171
+ if (ref.relationship === 'fork') return { ok: false, code: 'fork-isolated' }
172
+ if (!ref.capabilities.read) return { ok: false, code: 'forbidden' }
173
+ return { ok: true }
174
+ }
175
+
176
+ // ---- 台账条目的项目归属(路线 B T1)--------------------------------------------
177
+ // reviews.json / figures.json / figure-plans.json 是升级前的全局 JSON 台账。
178
+ // 归属判定优先级(唯一授权仍是 session→ProjectRef):
179
+ // 1. 记录显式携带 projectId(T1 之后的新写入)——必须与当前 ref.projectId 相同;
180
+ // 2. 记录显式携带 rootSessionId(派单任务、图件/图件计划新写入)——必须与
181
+ // 当前 ref.rootSessionId 相同;
182
+ // 3. 记录的 sessionId 是稳定链接:经 roster(成员 childId→父会话)或 Project Store
183
+ // 的 root 绑定解析出 rootSessionId(能唯一确定时同时得到 projectId)——视为已回填;
184
+ // 4. 都无法确定 → legacy-unscoped:只在 legacy 只读视图出现,不进入任何项目卡片。
185
+ // 注意:不得用跨项目重复的 res-N 或“未绑定 Result”推断归属。
186
+ function rosterRootMap() {
187
+ const map = new Map()
188
+ for (const m of rosterMembers()) {
189
+ if (m.childId && m.parentSessionId) map.set(String(m.childId), String(m.parentSessionId))
190
+ }
191
+ return map
192
+ }
193
+
194
+ export function projectAttributionOf(ref) {
195
+ return {
196
+ projectId: ref && ref.projectId ? String(ref.projectId) : null,
197
+ rootSessionId: ref && ref.rootSessionId ? String(ref.rootSessionId) : null,
198
+ }
199
+ }
200
+
201
+ /**
202
+ * 创建一个带缓存的台账作用域解析器(一次请求内解析 roster/绑定,避免逐条读盘)。
203
+ * @param opts.store Project Store(读取 root 绑定;测试可注入)
204
+ */
205
+ export function createRecordScopeResolver({ store } = {}) {
206
+ const rootCache = new Map()
207
+ const memberRoots = rosterRootMap()
208
+ const bindingOf = (rootSessionId) => {
209
+ if (!store || typeof store.bindingOfRootSession !== 'function') return null
210
+ try {
211
+ return store.bindingOfRootSession(String(rootSessionId)) || null
212
+ } catch {
213
+ return null
214
+ }
215
+ }
216
+ const rootSessionIdOf = (sessionId) => {
217
+ const sid = String(sessionId || '')
218
+ if (!sid) return null
219
+ if (rootCache.has(sid)) return rootCache.get(sid)
220
+ let root = memberRoots.get(sid) || null
221
+ if (!root) {
222
+ const binding = bindingOf(sid)
223
+ root = binding && binding.primaryRootSessionId ? String(binding.primaryRootSessionId) : null
224
+ }
225
+ // 普通 root 会话是自己的 root;无法证明是成员子会话时按自身处理(仍不会跨项目匹配)。
226
+ if (!root) root = sid
227
+ rootCache.set(sid, root)
228
+ return root
229
+ }
230
+ function scopeOf(record) {
231
+ if (!record || typeof record !== 'object') {
232
+ return { projectId: null, rootSessionId: null, source: 'invalid' }
233
+ }
234
+ const projectId = record.projectId ? String(record.projectId) : null
235
+ const rootSessionId = record.rootSessionId ? String(record.rootSessionId) : null
236
+ if (projectId || rootSessionId) return { projectId, rootSessionId, source: 'attributed' }
237
+ if (record.sessionId) {
238
+ const root = rootSessionIdOf(record.sessionId)
239
+ if (root) {
240
+ const binding = bindingOf(root)
241
+ return {
242
+ projectId: binding && binding.projectId ? String(binding.projectId) : null,
243
+ rootSessionId: root,
244
+ source: 'session-link',
245
+ }
246
+ }
247
+ }
248
+ return { projectId: null, rootSessionId: null, source: 'legacy-unscoped' }
249
+ }
250
+ function inScope(record, ref) {
251
+ if (!record || !ref) return false
252
+ const scope = scopeOf(record)
253
+ if (scope.projectId) return Boolean(ref.projectId) && String(scope.projectId) === String(ref.projectId)
254
+ if (scope.rootSessionId) return Boolean(ref.rootSessionId) && String(scope.rootSessionId) === String(ref.rootSessionId)
255
+ return false
256
+ }
257
+ return { rootSessionIdOf, scopeOf, inScope }
258
+ }
259
+
260
+ // 单条判定便捷入口(少量记录/测试用;批量过滤请复用 createRecordScopeResolver)。
261
+ export function isRecordInProjectScope(record, ref, { store } = {}) {
262
+ if (!record || !ref) return false
263
+ return createRecordScopeResolver({ store }).inScope(record, ref)
264
+ }
265
+
266
+ // ---- 首写建项目(设计 §7.2.1)--------------------------------------------------
267
+ // 只看卡片、点技能或普通聊天不得制造空项目:只有第一笔持久写(ensureProject 显式调用)
268
+ // 才创建 project + captain 绑定。队友的队长 root 未绑定时返回 needs-binding(不猜测归属)。
269
+ export function ensureProject(ctx, sessionId, { store, title = '' } = {}) {
270
+ const scope = resolveProjectContext(ctx, sessionId, { store })
271
+ if (!scope.ok) return scope
272
+ const ref = scope.ref
273
+ if (ref.projectId) return { ok: true, ref, created: false }
274
+ if (ref.relationship === 'fork') return { ok: false, code: 'fork-isolated', message: CAPABILITY_ERRORS['fork-isolated'] }
275
+ if (ref.relationship === 'teammate') return { ok: false, code: 'needs-binding', message: '队长的会话尚未绑定项目;请在队长会话中建立研究问题后再协作' }
276
+ if (!ref.capabilities.writePaper) return { ok: false, code: 'forbidden', message: CAPABILITY_ERRORS.forbidden }
277
+ const fact = workspaceFactOf(ctx, ref.rootSessionId)
278
+ const workspaceKey = fact.status === 'unique' ? workspaceKeyOf(fact.path) : ''
279
+ const projectId = store.createProject({ rootSessionId: ref.rootSessionId, title, workspaceKey })
280
+ const reread = resolveProjectContext(ctx, sessionId, { store })
281
+ return { ok: true, ref: reread.ref || { ...ref, projectId }, created: true }
282
+ }