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,287 @@
1
+ // DSH 论文证据主干 v2(DSH Evidence Spine)
2
+ //
3
+ // 这是蓝图的纯领域层:负责旧数据迁移、版本化确认和论文就绪状态计算。
4
+ // 文件读写、工具注册与 UI 投影仍由 blueprint.js/httpdata.js 承担。
5
+
6
+ import { createHash } from 'node:crypto'
7
+
8
+ export const PAPER_STAGES = ['explore', 'frame', 'execute', 'synthesize', 'draft', 'audit']
9
+ export const EVIDENCE_DIRECTIONS = ['not_assessed', 'supports', 'contradicts', 'inconclusive', 'not_applicable']
10
+ export const EVIDENCE_STATES = ['planned', 'observed', 'verified', 'disputed', 'invalidated']
11
+ export const MANUSCRIPT_ROLES = ['main', 'validation', 'control', 'boundary', 'supplement', 'excluded']
12
+ export const PRESENTATION_MODES = ['undecided', 'figure', 'table', 'prose', 'supplement', 'omit']
13
+ export const SUBMISSION_ITEMS = ['dataCode', 'ethics', 'reporting', 'limitations']
14
+
15
+ const clone = (value) => {
16
+ try { return JSON.parse(JSON.stringify(value ?? {})) } catch { return {} }
17
+ }
18
+
19
+ const stringOf = (value, fallback = '') => typeof value === 'string' ? value : fallback
20
+ const enumOf = (value, allowed, fallback) => allowed.includes(value) ? value : fallback
21
+ const arrayOf = (value) => Array.isArray(value) ? value.filter(Boolean) : []
22
+
23
+ function stable(value) {
24
+ if (Array.isArray(value)) return value.map(stable)
25
+ if (value && typeof value === 'object') {
26
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stable(value[key])]))
27
+ }
28
+ return value
29
+ }
30
+
31
+ function semanticPayload(entity, entityId) {
32
+ if (entityId === 'core') {
33
+ return {
34
+ title: stringOf(entity.title), claim: stringOf(entity.claim), innovation: stringOf(entity.innovation),
35
+ venue: stringOf(entity.venue),
36
+ }
37
+ }
38
+ return {
39
+ title: stringOf(entity.title), claim: stringOf(entity.claim), purpose: stringOf(entity.purpose),
40
+ manuscriptRole: enumOf(entity.manuscriptRole, MANUSCRIPT_ROLES, 'main'),
41
+ claims: arrayOf(entity.claims).filter((c) => c.status !== 'retired').map((c) => ({
42
+ id: stringOf(c.id), text: stringOf(c.text), revision: Number(c.revision) || 1,
43
+ })),
44
+ }
45
+ }
46
+
47
+ export function semanticHashOf(entity, entityId) {
48
+ return createHash('sha256').update(JSON.stringify(stable(semanticPayload(entity || {}, entityId)))).digest('hex')
49
+ }
50
+
51
+ export function isConfirmationCurrent(entity, entityId) {
52
+ if (!entity || entity.confirmed !== true || !entity.confirmation) return false
53
+ const revision = Number(entity.revision) || 1
54
+ if (entity.confirmation.revisionId !== `${entityId}-r${revision}`) return false
55
+ // 路线 B(2026-11-13):领域层确认凭据显式记录 objectRevision——语义修改才推进 revision、
56
+ // 执行性更新(记录证据/链任务/改状态)不推进,因此 revision 相等即当前修订有效。
57
+ // 旧凭据(legacy-migration / 旧工具)没有 objectRevision 字段时回退语义哈希比对。
58
+ if (entity.confirmation.objectRevision != null) {
59
+ return Number(entity.confirmation.objectRevision) === revision
60
+ }
61
+ return entity.confirmation.contentHash === semanticHashOf(entity, entityId)
62
+ }
63
+
64
+ export function confirmEntityRevision(entity, entityId, options = {}) {
65
+ if (!entity || typeof entity !== 'object') throw new Error('无法确认空对象')
66
+ entity.revision = Math.max(1, Number(entity.revision) || 1)
67
+ const receipt = {
68
+ revisionId: `${entityId}-r${entity.revision}`,
69
+ contentHash: semanticHashOf(entity, entityId),
70
+ confirmedBy: stringOf(options.confirmedBy, 'user'),
71
+ confirmedAt: Number(options.confirmedAt) || Date.now(),
72
+ source: stringOf(options.source, 'conversation'),
73
+ }
74
+ entity.confirmed = true
75
+ entity.confirmation = receipt
76
+ return receipt
77
+ }
78
+
79
+ export function reviseEntity(entity) {
80
+ if (!entity || typeof entity !== 'object') return entity
81
+ entity.revision = Math.max(1, Number(entity.revision) || 1) + 1
82
+ entity.confirmed = false
83
+ entity.confirmation = null
84
+ return entity
85
+ }
86
+
87
+ function normalizeConfirmation(entity, entityId) {
88
+ entity.revision = Math.max(1, Number(entity.revision) || 1)
89
+ if (entity.confirmed === true && !entity.confirmation) {
90
+ // 兼容旧版 confirmed=true:保留既有授权,同时明确标记为迁移凭据。
91
+ confirmEntityRevision(entity, entityId, {
92
+ source: 'legacy-migration',
93
+ confirmedBy: 'user',
94
+ confirmedAt: Number(entity.updatedAt) || 1,
95
+ })
96
+ } else if (!isConfirmationCurrent(entity, entityId)) {
97
+ entity.confirmed = false
98
+ entity.confirmation = null
99
+ }
100
+ }
101
+
102
+ function normalizeSubmission(raw) {
103
+ const out = {}
104
+ for (const key of SUBMISSION_ITEMS) {
105
+ const row = raw && typeof raw[key] === 'object' ? raw[key] : {}
106
+ const status = ['pending', 'complete', 'not_applicable'].includes(row.status) ? row.status : 'pending'
107
+ out[key] = { status, note: stringOf(row.note), updatedAt: Number(row.updatedAt) || 0 }
108
+ }
109
+ return out
110
+ }
111
+
112
+ function normalizeResult(raw) {
113
+ const r = raw && typeof raw === 'object' ? raw : {}
114
+ const id = stringOf(r.id)
115
+ const legacyNegative = r.status === 'negative'
116
+ const legacyDropped = r.status === 'dropped'
117
+ const primaryClaimId = `${id}-claim-1`
118
+ let claims = arrayOf(r.claims).map((c, index) => ({
119
+ id: stringOf(c.id, `${id}-claim-${index + 1}`),
120
+ text: stringOf(c.text, index === 0 ? stringOf(r.claim) : ''),
121
+ revision: Math.max(1, Number(c.revision) || 1),
122
+ status: c.status === 'retired' ? 'retired' : 'active',
123
+ createdAt: Number(c.createdAt) || Number(r.updatedAt) || 0,
124
+ updatedAt: Number(c.updatedAt) || Number(r.updatedAt) || 0,
125
+ })).filter((c) => c.text)
126
+ if (claims.length === 0 && stringOf(r.claim)) {
127
+ claims = [{ id: primaryClaimId, text: stringOf(r.claim), revision: 1, status: 'active', createdAt: Number(r.updatedAt) || 0, updatedAt: Number(r.updatedAt) || 0 }]
128
+ }
129
+ const out = {
130
+ ...r,
131
+ id,
132
+ title: stringOf(r.title, id),
133
+ claim: stringOf(r.claim, claims[0] ? claims[0].text : ''),
134
+ purpose: stringOf(r.purpose),
135
+ status: stringOf(r.status, 'planned'),
136
+ direction: enumOf(r.direction, EVIDENCE_DIRECTIONS, legacyNegative ? 'contradicts' : r.status === 'supported' ? 'supports' : 'not_assessed'),
137
+ evidenceState: enumOf(r.evidenceState, EVIDENCE_STATES, r.status === 'supported' ? 'verified' : legacyNegative ? 'observed' : 'planned'),
138
+ manuscriptRole: enumOf(r.manuscriptRole, MANUSCRIPT_ROLES, legacyDropped ? 'excluded' : legacyNegative ? 'boundary' : 'main'),
139
+ presentation: {
140
+ mode: enumOf(r.presentation && r.presentation.mode, PRESENTATION_MODES, 'undecided'),
141
+ rationale: stringOf(r.presentation && r.presentation.rationale),
142
+ },
143
+ claims,
144
+ claimSeq: Math.max(claims.length, Number(r.claimSeq) || 0),
145
+ evidence: arrayOf(r.evidence).map((e, index) => ({
146
+ id: stringOf(e.id, `${id}-ev-${index + 1}`),
147
+ claimIds: arrayOf(e.claimIds).map(String),
148
+ direction: enumOf(e.direction, EVIDENCE_DIRECTIONS, 'not_assessed'),
149
+ state: enumOf(e.state, EVIDENCE_STATES, 'planned'),
150
+ sourceLocator: stringOf(e.sourceLocator),
151
+ conditions: stringOf(e.conditions),
152
+ uncertainty: stringOf(e.uncertainty),
153
+ allowedInterpretation: stringOf(e.allowedInterpretation),
154
+ prohibitedInterpretation: stringOf(e.prohibitedInterpretation),
155
+ note: stringOf(e.note),
156
+ createdAt: Number(e.createdAt) || 0,
157
+ updatedAt: Number(e.updatedAt) || 0,
158
+ })),
159
+ evidenceSeq: Math.max(arrayOf(r.evidence).length, Number(r.evidenceSeq) || 0),
160
+ tasks: arrayOf(r.tasks).map(String),
161
+ figures: arrayOf(r.figures).map(String),
162
+ references: arrayOf(r.references),
163
+ screening: r.screening || null,
164
+ notes: stringOf(r.notes),
165
+ updatedAt: Number(r.updatedAt) || 0,
166
+ }
167
+ normalizeConfirmation(out, id)
168
+ return out
169
+ }
170
+
171
+ export function normalizePaperSpine(raw) {
172
+ const source = clone(raw)
173
+ const coreRaw = source.core && typeof source.core === 'object' ? source.core : {}
174
+ const core = {
175
+ ...coreRaw,
176
+ title: stringOf(coreRaw.title), claim: stringOf(coreRaw.claim), innovation: stringOf(coreRaw.innovation),
177
+ venue: stringOf(coreRaw.venue), updatedAt: Number(coreRaw.updatedAt) || 0,
178
+ }
179
+ normalizeConfirmation(core, 'core')
180
+ return {
181
+ ...source,
182
+ schemaVersion: 2,
183
+ stage: enumOf(source.stage, PAPER_STAGES, core.claim ? 'frame' : 'explore'),
184
+ stageUpdatedAt: Number(source.stageUpdatedAt) || 0,
185
+ core,
186
+ results: arrayOf(source.results).filter((r) => r && typeof r === 'object' && typeof r.id === 'string').map(normalizeResult),
187
+ narrative: stringOf(source.narrative),
188
+ resultSeq: Number(source.resultSeq) || 0,
189
+ submission: normalizeSubmission(source.submission),
190
+ updatedAt: Number(source.updatedAt) || 0,
191
+ }
192
+ }
193
+
194
+ const readiness = (blockers) => ({ state: blockers.length === 0 ? 'ready' : 'blocked', blockers })
195
+
196
+ export function paperSpineViewOf(rawBlueprint, teamState, figuresState, reviewCoverage = null) {
197
+ const bp = normalizePaperSpine(rawBlueprint)
198
+ const tasks = arrayOf(teamState && teamState.tasks).filter((t) => t && t.status !== 'deleted')
199
+ const taskById = new Map(tasks.map((t) => [t.id, t]))
200
+ const figures = Array.isArray(figuresState)
201
+ ? figuresState.filter(Boolean)
202
+ : Object.values(figuresState && typeof figuresState === 'object' ? figuresState : {}).filter(Boolean)
203
+ const figureById = new Map(figures.filter((f) => f && f.id).map((f) => [f.id, f]))
204
+ const reviewById = new Map(arrayOf(reviewCoverage && reviewCoverage.results).map((r) => [r.id, r]))
205
+ const submissionBlockers = SUBMISSION_ITEMS.filter((key) => !['complete', 'not_applicable'].includes(bp.submission[key].status))
206
+
207
+ const results = bp.results.map((r) => {
208
+ const excluded = r.manuscriptRole === 'excluded'
209
+ const taskIds = new Set(r.tasks)
210
+ for (const task of tasks) {
211
+ const ids = arrayOf(task.resultIds).map(String)
212
+ if (task.resultId) ids.push(String(task.resultId))
213
+ if (ids.includes(r.id)) taskIds.add(task.id)
214
+ }
215
+ const linkedTasks = [...taskIds].map((id) => taskById.get(id)).filter(Boolean)
216
+ const incompleteTasks = linkedTasks.filter((t) => !['completed', 'cancelled'].includes(t.status))
217
+ const linkedFigures = r.figures.map((id) => figureById.get(id)).filter(Boolean)
218
+ const approvedFigures = linkedFigures.filter((f) => f.audit && f.audit.overallStatus === 'approved')
219
+ const activeClaims = r.claims.filter((c) => c.status !== 'retired' && c.text)
220
+ const verifiedEvidence = r.evidence.filter((e) => e.state === 'verified' && e.sourceLocator && e.allowedInterpretation)
221
+ // 语义复核:只看「存在 verified 证据」会把仅有反向证据的 Result 判为就绪——
222
+ // supports 与 contradicts 都满足 old 条件。要求至少一条 supports 证据支撑该 Result。
223
+ const supportingEvidence = verifiedEvidence.filter((e) => String(e.direction || '') === 'supports')
224
+ const review = reviewById.get(r.id)
225
+
226
+ const scientificBlockers = []
227
+ if (!excluded) {
228
+ if (!isConfirmationCurrent(r, r.id)) scientificBlockers.push('当前 Result 修订尚未确认')
229
+ if (activeClaims.length === 0) scientificBlockers.push('尚无可检验 Claim')
230
+ if (verifiedEvidence.length === 0) scientificBlockers.push('尚无可核验证据')
231
+ else if (supportingEvidence.length === 0) scientificBlockers.push('现有证据不支撑该主张(仅有反向或中性证据)')
232
+ if (incompleteTasks.length > 0) scientificBlockers.push(`有 ${incompleteTasks.length} 项工作未完成`)
233
+ if (!review || review.severity !== 'pass') scientificBlockers.push(review && review.severity ? '主张审查尚未通过' : '尚未完成主张审查')
234
+ }
235
+ const scientific = excluded ? { state: 'excluded', blockers: [] } : readiness(scientificBlockers)
236
+
237
+ const manuscriptBlockers = []
238
+ if (!excluded) {
239
+ if (scientific.state !== 'ready') manuscriptBlockers.push('科学证据尚未就绪')
240
+ if (r.presentation.mode === 'undecided') manuscriptBlockers.push('尚未决定呈现方式')
241
+ if (r.presentation.mode === 'figure' && approvedFigures.length === 0) manuscriptBlockers.push('尚无批准图件')
242
+ const unverifiedRefs = r.references.filter((ref) => ref && !ref.verified).length
243
+ if (unverifiedRefs > 0) manuscriptBlockers.push(`有 ${unverifiedRefs} 条参考文献未核验`)
244
+ }
245
+ const manuscript = excluded ? { state: 'excluded', blockers: [] } : readiness(manuscriptBlockers)
246
+ const resultSubmissionBlockers = excluded ? [] : [
247
+ ...(manuscript.state === 'ready' ? [] : ['文稿尚未就绪']),
248
+ ...submissionBlockers.map((key) => `投稿检查未完成:${key}`),
249
+ ]
250
+
251
+ return {
252
+ id: r.id, title: r.title, claim: r.claim, purpose: r.purpose, excluded,
253
+ direction: r.direction, evidenceState: r.evidenceState, manuscriptRole: r.manuscriptRole,
254
+ presentation: r.presentation, confirmation: r.confirmation, revision: r.revision,
255
+ claims: activeClaims, evidence: r.evidence,
256
+ counts: {
257
+ claims: activeClaims.length, evidence: r.evidence.length, verifiedEvidence: verifiedEvidence.length,
258
+ tasks: linkedTasks.length, completedTasks: linkedTasks.filter((t) => t.status === 'completed').length,
259
+ figures: linkedFigures.length, approvedFigures: approvedFigures.length,
260
+ references: r.references.length, verifiedReferences: r.references.filter((ref) => ref && ref.verified).length,
261
+ },
262
+ readiness: { scientific, manuscript, submission: excluded ? { state: 'excluded', blockers: [] } : readiness(resultSubmissionBlockers) },
263
+ nextAction: scientific.blockers[0] || manuscript.blockers[0] || resultSubmissionBlockers[0] || '该 Result 已通过当前全部闸门',
264
+ }
265
+ })
266
+ const included = results.filter((r) => !r.excluded)
267
+ const counts = {
268
+ total: results.length,
269
+ included: included.length,
270
+ scientificReady: included.filter((r) => r.readiness.scientific.state === 'ready').length,
271
+ manuscriptReady: included.filter((r) => r.readiness.manuscript.state === 'ready').length,
272
+ submissionReady: included.filter((r) => r.readiness.submission.state === 'ready').length,
273
+ }
274
+ const firstBlocked = included.find((r) => r.readiness.submission.state !== 'ready')
275
+ return {
276
+ schemaVersion: 2,
277
+ stage: bp.stage,
278
+ core: {
279
+ title: bp.core.title, claim: bp.core.claim, revision: bp.core.revision,
280
+ confirmed: isConfirmationCurrent(bp.core, 'core'), confirmation: bp.core.confirmation,
281
+ },
282
+ submission: bp.submission,
283
+ counts,
284
+ results,
285
+ nextDecision: firstBlocked ? `${firstBlocked.id}:${firstBlocked.nextAction}` : included.length ? '全部 Result 已通过当前投稿闸门' : '先建立并确认文章 Result',
286
+ }
287
+ }
@@ -0,0 +1,259 @@
1
+ // dsh-science — Project State ↔ 现有领域读模型的桥接适配层(阶段 2)
2
+ //
3
+ // 设计真源 §8.1/§17:现有 host 能力(blueprint 工具、reviewer、figures、/state 读模型)
4
+ // 全部改为读 Project State、写 ProjectCommand。本模块提供唯一的双向映射:
5
+ // 1. blueprintViewOf(snapshot) —— 快照 → 旧 blueprint.json 形状的只读视图,
6
+ // 让 paperspine/reviewcov/blueprint 的读模型函数与 /state 快照继续工作;
7
+ // 2. importLegacyBlueprint —— 旧全局 blueprint.json 的只读导入(project.import-legacy,
8
+ // 带 migrationId 幂等与源 hash 台账);
9
+ // 3. sessionScopeOf(exec) —— 从工具 exec 提取可信 sessionId(host 侧 agent,不经客户端)。
10
+
11
+ import { createHash } from 'node:crypto'
12
+ import { resolveProjectContext, ensureProject } from './project-context.js'
13
+ import { executePaperCommands, contentHashOf, objectRevisionOf, COMMANDS } from './project-domain.js'
14
+ import { StoreError } from './project-store.js'
15
+
16
+ function log(msg) {
17
+ console.log(`[dsh-science project-adapter] ${msg}`)
18
+ }
19
+
20
+ // ---- 会话与 scope ---------------------------------------------------------------
21
+ // 工具 exec 的身份来自宿主 agent(exec.agent.session?.id ?? agent.id)——这是 host 侧
22
+ // 事实,不是客户端可伪造输入。无 sessions 服务(headless 测试/纯 host 组合)时按
23
+ // 独立 root 会话处理(每个会话一个项目,隔离语义不变)。
24
+ export function sessionIdOf(exec) {
25
+ const agent = exec && exec.agent
26
+ const sid = (agent && agent.session && agent.session.id) || (agent && agent.id) || null
27
+ return sid ? String(sid) : null
28
+ }
29
+
30
+ export function scopeOfExec(ctx, exec, { store } = {}) {
31
+ const sid = sessionIdOf(exec)
32
+ if (!sid) return { ok: false, code: 'unknown-session', message: '无法确定调用者会话(需要主会话上下文)' }
33
+ return resolveProjectContext(ctx, sid, { store })
34
+ }
35
+
36
+ // 读路径:绑定项目后返回 { ref, snapshot };未绑定 → { ref, snapshot: null }(空视图,不建项目)。
37
+ export function readScope(ctx, exec, { store } = {}) {
38
+ const scope = scopeOfExec(ctx, exec, { store })
39
+ if (!scope.ok) return scope
40
+ const ref = scope.ref
41
+ if (!ref.projectId) return { ok: true, ref, snapshot: null }
42
+ const snap = store.snapshotOf(ref.projectId)
43
+ if (snap && snap.corrupt) {
44
+ return { ok: false, code: 'snapshot-corrupt', message: '项目快照损坏,进入只读恢复模式' }
45
+ }
46
+ return { ok: true, ref, snapshot: snap ? snap.snapshot : null }
47
+ }
48
+
49
+ // 写路径:ensureProject(首写建项目)+ executePaperCommands。
50
+ export function writeCommands(ctx, exec, { store, mutationId, operations, expectedRevision = null, source = 'tool' }) {
51
+ const sid = sessionIdOf(exec)
52
+ if (!sid) return { kind: 'invalid', reason: '无法确定调用者会话' }
53
+ const ensured = ensureProject(ctx, sid, { store })
54
+ if (!ensured.ok) {
55
+ return { kind: ensured.code === 'fork-isolated' ? 'forbidden' : ensured.code === 'needs-binding' ? 'needs-binding' : 'invalid', reason: ensured.message || ensured.code }
56
+ }
57
+ return executePaperCommands(store, ensured.ref, {
58
+ mutationId,
59
+ expectedRevision,
60
+ source,
61
+ actor: { sessionId: sid, relationship: ensured.ref.relationship },
62
+ operations,
63
+ })
64
+ }
65
+
66
+ // 写权限断言(工具入口用):fork/成员直接拒绝,给出可执行恢复提示。
67
+ export function assertToolWriteAllowed(ref) {
68
+ if (!ref || !ref.capabilities || !ref.capabilities.writePaper) {
69
+ throw new StoreError('forbidden', '当前会话没有论文语义写权限(成员只能提交提案与任务回报;普通 fork 与父项目隔离)。请在队长/root 会话中执行。')
70
+ }
71
+ }
72
+
73
+ // ---- 快照 → 旧蓝图视图(读模型等价映射)--------------------------------------------
74
+ // 目标形状:lib/paperspine.js normalizePaperSpine / coverageOf / paperSpineViewOf /
75
+ // reviewCoverageOf 的输入。字段一一对应;确认凭据直接透传(含 objectRevision/contentHash)。
76
+ export function blueprintViewOf(snapshot) {
77
+ if (!snapshot) {
78
+ return normalizeShape({
79
+ schemaVersion: 2, stage: 'explore', stageUpdatedAt: 0,
80
+ core: { title: '', claim: '', innovation: '', venue: '', revision: 1, confirmed: false, confirmation: null, updatedAt: 0 },
81
+ results: [], narrative: '', resultSeq: 0,
82
+ submission: {}, updatedAt: 0,
83
+ })
84
+ }
85
+ const paper = snapshot.paper || {}
86
+ const view = normalizeShape({
87
+ schemaVersion: paper.schemaVersion || 2,
88
+ stage: paper.stage || 'explore',
89
+ stageNote: paper.stageNote || '',
90
+ stageUpdatedAt: paper.stageUpdatedAt || 0,
91
+ core: paper.core ? { ...paper.core } : null,
92
+ results: (paper.results || []).map((r) => ({ ...r })),
93
+ narrative: paper.narrative || '',
94
+ question: paper.question || '',
95
+ scope: paper.scope || '',
96
+ sourceSummary: paper.sourceSummary || '',
97
+ questionUpdatedAt: paper.questionUpdatedAt || 0,
98
+ resultSeq: paper.resultSeq || 0,
99
+ submission: paper.submission || {},
100
+ updatedAt: (snapshot.metadata && snapshot.metadata.updatedAt) || 0,
101
+ projectId: snapshot.projectId,
102
+ revision: snapshot.revision,
103
+ })
104
+ return view
105
+ }
106
+
107
+ function normalizeShape(view) {
108
+ // 兼容旧读模型对字段存在的假设
109
+ if (!view.core) {
110
+ view.core = { title: '', claim: '', innovation: '', venue: '', revision: 1, confirmed: false, confirmation: null, updatedAt: 0 }
111
+ }
112
+ for (const r of view.results || []) {
113
+ if (!Array.isArray(r.claims)) r.claims = []
114
+ if (!Array.isArray(r.evidence)) r.evidence = []
115
+ if (!Array.isArray(r.tasks)) r.tasks = []
116
+ if (!Array.isArray(r.figures)) r.figures = []
117
+ if (!Array.isArray(r.references)) r.references = []
118
+ if (!r.presentation) r.presentation = { mode: 'undecided', rationale: '' }
119
+ if (!r.manuscriptRole) r.manuscriptRole = 'main'
120
+ if (!r.direction) r.direction = 'not_assessed'
121
+ if (!r.evidenceState) r.evidenceState = 'planned'
122
+ if (!r.status) r.status = 'planned'
123
+ if (!r.revision) r.revision = 1
124
+ r.confirmed = r.confirmed === true
125
+ }
126
+ if (!view.submission || typeof view.submission !== 'object') view.submission = {}
127
+ view.results = Array.isArray(view.results) ? view.results : []
128
+ return view
129
+ }
130
+
131
+ // ---- 旧数据导入(project.import-legacy)--------------------------------------------
132
+ // 幂等:同 migrationId 返回原结果。整批操作在一个事务里(executePaperCommands 的批量语义),
133
+ // 失败整体回滚;导入是"提案/非确认"语义——旧数据里的 confirmed=true 保留为 legacy-migration
134
+ // 凭据(与旧 paperspine normalizeConfirmation 同语义),不自动提升证据状态。
135
+ // 旧 blueprint.json 只读导入:完整字段(core/results 主干 + 状态/证据/文献/任务/图件引用),
136
+ // 单事务全成全败;migrationId(源 hash)幂等;原文件永不删除(它本身就是备份)。
137
+ // dryRun=true 时只返回预览(将导入什么/跳过什么),不落任何写入。
138
+ export function importLegacyBlueprint(ctx, exec, { store, legacy, sourceFile, sourceHash, dryRun = false }) {
139
+ const migrationId = `legacy-blueprint-${sourceHash || hashSource(legacy)}`
140
+ const sid = sessionIdOf(exec)
141
+ if (!sid) return { ok: false, error: '无法确定调用者会话' }
142
+ // 预览绝不建项目(T5.1:预览只读)
143
+ if (dryRun) {
144
+ const scope = readScope(ctx, exec, { store })
145
+ if (!scope.ok) return { ok: false, error: scope.message || scope.code }
146
+ const core = legacy && typeof legacy.core === 'object' ? legacy.core : {}
147
+ const legacyResults = (Array.isArray(legacy.results) ? legacy.results : []).filter((r) => r && typeof r.id === 'string')
148
+ const confirmedCount = legacyResults.filter((r) => r && r.confirmed === true).length
149
+ return {
150
+ ok: true,
151
+ preview: true,
152
+ migrationId,
153
+ projectId: scope.ref.projectId,
154
+ operations: (core.claim || core.title ? 1 : 0) + legacyResults.length,
155
+ results: legacyResults.map((r) => ({ id: r.id, title: r.title || r.id, confirmed: r.confirmed === true })),
156
+ confirmedResults: confirmedCount,
157
+ note: `预览:将导入核心${core.claim ? '(有)' : '(无)'} + ${legacyResults.length} 个 Result(其中 ${confirmedCount} 个保留 legacy-migration 确认凭据)。${scope.ref.projectId ? '目标:当前项目。' : '目标:将新建项目(首次持久写时创建)。'}原文件保留为只读备份,不会删除或修改。`,
158
+ }
159
+ }
160
+ const ensured = ensureProject(ctx, sid, { store })
161
+ if (!ensured.ok) return { ok: false, error: ensured.message || ensured.code }
162
+ const projectId = ensured.ref.projectId
163
+ const effectiveSourceHash = sourceHash || hashSource(legacy)
164
+ const ledger = {
165
+ migrationId,
166
+ projectId,
167
+ source: sourceFile || 'blueprint.json',
168
+ sourceHash: effectiveSourceHash,
169
+ backupPath: sourceFile || '',
170
+ }
171
+ const existing = store.st.getLegacyImport.get(migrationId)
172
+ if (existing && existing.project_id === projectId) {
173
+ // T3:重复 migrationId 返回原回执(不覆盖台账、不推进 revision)。
174
+ const receiptRow = store.st.getReceipt.get(projectId, migrationId)
175
+ const receipt = receiptRow ? JSON.parse(receiptRow.receipt) : null
176
+ return {
177
+ ok: true,
178
+ duplicate: true,
179
+ migrationId,
180
+ projectId,
181
+ revision: receipt ? receipt.revision : undefined,
182
+ receipt,
183
+ note: '该来源已导入过当前项目(幂等返回原回执)。',
184
+ }
185
+ }
186
+ if (existing) {
187
+ return { ok: false, error: `该旧数据已导入过其他项目(${existing.project_id});请显式选择目标或换用新项目` }
188
+ }
189
+ const core = legacy && typeof legacy.core === 'object' ? legacy.core : {}
190
+ const operations = []
191
+ if (String(core.claim || '').trim() || String(core.title || '').trim()) {
192
+ operations.push({ command: 'paper.propose-core', payload: { title: core.title, claim: core.claim, innovation: core.innovation, venue: core.venue } })
193
+ }
194
+ const legacyResults = (Array.isArray(legacy.results) ? legacy.results : []).filter((r) => r && typeof r.id === 'string')
195
+ for (const r of legacyResults) {
196
+ operations.push({ command: 'paper.import-legacy-result', payload: { legacy: r } })
197
+ }
198
+ const confirmedCount = legacyResults.filter((r) => r && r.confirmed === true).length
199
+ if (operations.length === 0) {
200
+ return { ok: true, imported: 0, migrationId, projectId, note: '旧数据没有可导入的 core/results。' }
201
+ }
202
+ let result
203
+ try {
204
+ // T3:legacy_imports 台账与项目命令/审计/回执在同一事务提交(commit 后不再补写台账)。
205
+ result = executePaperCommands(store, ensured.ref, {
206
+ mutationId: migrationId,
207
+ source: 'legacy-import',
208
+ actor: { sessionId: sid, source: sourceFile || 'legacy-blueprint.json' },
209
+ operations,
210
+ legacyImport: ledger,
211
+ })
212
+ } catch (err) {
213
+ // after-commit 通知失败:业务事实与台账已提交,重试会命中幂等回执 → 不会重复导入;
214
+ // 提交前故障(before-command/after-snapshot/at-ledger)整批回滚,同样可安全重试。
215
+ const committed = Boolean(err && err.committed)
216
+ return {
217
+ ok: false,
218
+ error: committed
219
+ ? `导入在提交后通知阶段失败(业务事实与台账已提交,可安全重试):${(err && err.message) || err}`
220
+ : `导入事务失败(已回滚,可安全重试):${(err && err.message) || err}`,
221
+ committed,
222
+ migrationId,
223
+ projectId,
224
+ retrySafe: true,
225
+ revision: (() => { try { return store.snapshotOf(projectId).revision } catch { return undefined } })(),
226
+ }
227
+ }
228
+ if (result.kind === 'applied') {
229
+ log(`legacy blueprint imported: ${operations.length} ops → ${projectId} (${migrationId})`)
230
+ return { ok: true, imported: operations.length, migrationId, projectId, revision: result.receipt.revision, confirmedResults: confirmedCount, receipt: result.receipt }
231
+ }
232
+ if (result.kind === 'already-applied') {
233
+ return {
234
+ ok: true,
235
+ duplicate: true,
236
+ migrationId,
237
+ projectId,
238
+ revision: result.receipt ? result.receipt.revision : undefined,
239
+ receipt: result.receipt || null,
240
+ reconciled: result.reconciled === true,
241
+ ledgerOnly: result.ledgerOnly === true,
242
+ note: result.reconciled
243
+ ? '该来源已导入过当前项目;本次补齐了缺失的导入台账(未重复导入数据)。'
244
+ : result.ledgerOnly
245
+ ? '导入台账已存在(回执缺失的异常恢复):按已导入处理,未重复导入数据。'
246
+ : '该来源已导入过当前项目(幂等返回原回执)。',
247
+ }
248
+ }
249
+ if (result.code === 'legacy-import-conflict') {
250
+ return { ok: false, error: '该旧数据已导入过其他项目;请显式选择目标或换用新项目' }
251
+ }
252
+ return { ok: false, error: result.reason || '导入失败' }
253
+ }
254
+
255
+ function hashSource(value) {
256
+ return createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex').slice(0, 16)
257
+ }
258
+
259
+ export { COMMANDS, contentHashOf, objectRevisionOf }