dsh-science-plugin 0.0.0-stage → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/agents/_README.md +5 -0
- package/agents/analyst.md +27 -0
- package/agents/figure-expert.md +35 -0
- package/agents/literature-scout.md +32 -0
- package/agents/presentation.md +78 -0
- package/agents/reviewer.md +32 -0
- package/agents/simulator.md +30 -0
- package/agents/topic-designer.md +26 -0
- package/agents/trainer.md +36 -0
- package/agents/writer.md +44 -0
- package/assets/mascots/analyst.svg +33 -0
- package/assets/mascots/designer.svg +33 -0
- package/assets/mascots/figure.svg +35 -0
- package/assets/mascots/idle.svg +9 -0
- package/assets/mascots/lead.svg +33 -0
- package/assets/mascots/presentation.svg +40 -0
- package/assets/mascots/reviewer.svg +31 -0
- package/assets/mascots/scout.svg +31 -0
- package/assets/mascots/simulator.svg +33 -0
- package/assets/mascots/thinking.svg +23 -0
- package/assets/mascots/trainer.svg +32 -0
- package/assets/mascots/working.svg +9 -0
- package/assets/mascots/writer.svg +33 -0
- package/client/client.js +3425 -0
- package/client/client.js.map +7 -0
- package/cordis.patch.yml +10 -0
- package/docs/DEVLOG.md +864 -0
- package/docs/SPEC.md +452 -0
- package/docs/recipes/agent-teams-science.md +46 -0
- package/docs/research/2026-11-12-academic-figure-skill-/350/257/204/344/274/260.md +33 -0
- 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
- 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
- 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
- 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
- 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
- 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
- package/icon.svg +6 -0
- package/lib/action-cards.js +194 -0
- package/lib/artifact-index.js +131 -0
- package/lib/blueprint.js +1487 -0
- package/lib/dag.js +69 -0
- package/lib/db.js +386 -0
- package/lib/figureqa.js +290 -0
- package/lib/figures.js +732 -0
- package/lib/httpdata-auth.js +91 -0
- package/lib/httpdata.js +863 -0
- package/lib/index.js +330 -0
- package/lib/lit.js +100 -0
- package/lib/paperspine.js +287 -0
- package/lib/project-adapter.js +259 -0
- package/lib/project-catalog.js +227 -0
- package/lib/project-context.js +282 -0
- package/lib/project-domain.js +849 -0
- package/lib/project-remote.js +348 -0
- package/lib/project-store.js +653 -0
- package/lib/rail-team.js +47 -0
- package/lib/resources.js +94 -0
- package/lib/reviewcov.js +238 -0
- package/lib/reviewer.js +638 -0
- package/lib/reviewruns.js +95 -0
- package/lib/roles.js +41 -0
- package/lib/router.js +133 -0
- package/lib/skeleton-context.js +181 -0
- package/lib/skillmenu.js +994 -0
- package/lib/ssh.js +637 -0
- package/lib/status.js +138 -0
- package/lib/store.js +50 -0
- package/lib/team.js +945 -0
- package/lib/vendor/ssh2.bundle.cjs +20124 -0
- package/lib/workspace-key.js +64 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +72 -4
- package/skills/sci-autoresearch/SKILL.md +41 -0
- package/skills/sci-figures/SKILL.md +91 -0
- package/skills/sci-figures/references/journal-requirements.md +22 -0
- package/skills/sci-figures/references/r-figures.md +106 -0
- package/skills/sci-figures/scripts/figure_export.py +45 -0
- package/skills/sci-figures/scripts/style_presets.py +82 -0
- package/skills/sci-hypothesis/SKILL.md +37 -0
- package/skills/sci-polish/SKILL.md +28 -0
- package/skills/sci-remote-jobs/SKILL.md +48 -0
- package/skills/sci-simulation/SKILL.md +70 -0
- package/skills/sci-simulation/references/tool-dossiers/_TEMPLATE.md +25 -0
- package/skills/sci-simulation/references/tool-dossiers/ase.md +42 -0
- package/skills/sci-simulation/references/tool-dossiers/gaussian.md +42 -0
- package/skills/sci-simulation/references/tool-dossiers/gromacs.md +37 -0
- package/skills/sci-simulation/references/tool-dossiers/lammps.md +34 -0
- package/skills/sci-simulation/references/tool-dossiers/quantum-espresso.md +34 -0
- package/skills/sci-simulation/references/universal-tool-onboarding.md +117 -0
- package/skills/sci-slides/SKILL.md +73 -0
- package/skills/sci-slides/scripts/make_deck.py +332 -0
- package/skills/sci-writing/SKILL.md +33 -0
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
// dsh-science — 项目领域层(Project Domain,阶段 1)
|
|
2
|
+
//
|
|
3
|
+
// 设计真源 §8:ProjectCommand 是唯一业务写 seam 的领域动作词汇;execute() 之外没有
|
|
4
|
+
// 任何直接写库路径。本模块职责:
|
|
5
|
+
// 1. snapshot 的领域形状(ProjectSnapshot,沿用 Paper Spine v2 词汇);
|
|
6
|
+
// 2. 单操作 applyOperation(snapshot, op, now) —— 纯函数,领域约束都在这里拒绝;
|
|
7
|
+
// 3. executeBatch(store, ref, batch) —— 一个 mutationId + expectedRevision + 多个
|
|
8
|
+
// operation,单事务全成全败,只推进一次 project revision,语义变化的对象各自
|
|
9
|
+
// 推进 object revision 并使旧确认失效;
|
|
10
|
+
// 4. 派单硬闸门(paper.dispatch-gate):核心与全部目标 Result 当前 revision 已确认,
|
|
11
|
+
// 在创建任务序号/外部副作用之前调用。
|
|
12
|
+
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
14
|
+
import { StoreError, emptyPaperState, emptySnapshot } from './project-store.js'
|
|
15
|
+
import { PAPER_STAGES, EVIDENCE_DIRECTIONS, EVIDENCE_STATES, MANUSCRIPT_ROLES, PRESENTATION_MODES, SUBMISSION_ITEMS } from './paperspine.js'
|
|
16
|
+
import { rememberRevision } from './skeleton-context.js'
|
|
17
|
+
import { linkArtifact, registerArtifact, relinkArtifact, indexItemOf, cleanIndexList } from './artifact-index.js'
|
|
18
|
+
|
|
19
|
+
export { emptyPaperState, emptySnapshot }
|
|
20
|
+
|
|
21
|
+
export const RESULT_STATUSES = ['planned', 'in_progress', 'supported', 'negative', 'dropped']
|
|
22
|
+
export const CLAIM_STATUSES = ['active', 'retired']
|
|
23
|
+
|
|
24
|
+
export const COMMANDS = Object.freeze([
|
|
25
|
+
'paper.propose-core',
|
|
26
|
+
'paper.propose-result',
|
|
27
|
+
'paper.update-result',
|
|
28
|
+
'paper.record-evidence',
|
|
29
|
+
'paper.record-claim',
|
|
30
|
+
'paper.retire-claim',
|
|
31
|
+
'paper.set-focus',
|
|
32
|
+
'paper.record-next-decision',
|
|
33
|
+
'paper.confirm-revision',
|
|
34
|
+
'paper.set-question',
|
|
35
|
+
'paper.set-stage',
|
|
36
|
+
'paper.set-submission-check',
|
|
37
|
+
'paper.link-task',
|
|
38
|
+
'paper.unlink-task',
|
|
39
|
+
'paper.link-artifact',
|
|
40
|
+
'paper.unlink-artifact',
|
|
41
|
+
'paper.link-reference',
|
|
42
|
+
'paper.verify-reference',
|
|
43
|
+
'paper.remove-reference',
|
|
44
|
+
'paper.set-screening',
|
|
45
|
+
'paper.set-narrative',
|
|
46
|
+
'paper.import-legacy-result',
|
|
47
|
+
'paper.archive-object',
|
|
48
|
+
'paper.record-proposal',
|
|
49
|
+
'paper.register-artifact',
|
|
50
|
+
'paper.relink-artifact',
|
|
51
|
+
'paper.dispatch-gate',
|
|
52
|
+
'project.set-metadata',
|
|
53
|
+
'project.attach-session',
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
function log(msg) {
|
|
57
|
+
console.log(`[dsh-science project-domain] ${msg}`)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function hashOf(value) {
|
|
61
|
+
return createHash('sha256').update(JSON.stringify(value)).digest('hex')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const str = (v, max = 4000) => String(v == null ? '' : v).slice(0, max)
|
|
65
|
+
const numOr = (v, f) => (Number.isFinite(Number(v)) ? Number(v) : f)
|
|
66
|
+
|
|
67
|
+
// ---- 对象工具 ------------------------------------------------------------------
|
|
68
|
+
export function objectRevisionOf(obj) { return Math.max(1, numOr(obj && obj.revision, 1)) }
|
|
69
|
+
|
|
70
|
+
export function contentHashOf(obj) {
|
|
71
|
+
const { revision: _r, confirmed: _c, confirmation: _conf, contentHash: _h, updatedAt: _u, history: _hist, ...content } = obj || {}
|
|
72
|
+
return hashOf(content)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function findObject(snapshot, objectId) {
|
|
76
|
+
const paper = snapshot.paper
|
|
77
|
+
if (objectId === 'core') return paper.core
|
|
78
|
+
return (paper.results || []).find((r) => r && r.id === objectId) || null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// 语义修改:新 object revision + 确认失效。非语义字段(状态/证据状态等执行事实)不失效。
|
|
82
|
+
// T6 确认摘要字段(用户确认时看到的内容):
|
|
83
|
+
// core = title / claim / innovation / venue
|
|
84
|
+
// result= title / claim / purpose / manuscriptRole
|
|
85
|
+
// 纳入/排除决定 = result.manuscriptRole(excluded)与 result.status 跨越 dropped;
|
|
86
|
+
// 派单目标 = dispatch-gate 的显式 resultIds + 上述纳入/排除字段。以上字段变化必须推进
|
|
87
|
+
// 对象 revision(进而 hash)并使旧确认不可用;证据状态/方向/呈现决策/notes 等执行事实不失效。
|
|
88
|
+
const SEMANTIC_CORE_FIELDS = ['title', 'claim', 'innovation', 'venue']
|
|
89
|
+
const SEMANTIC_RESULT_FIELDS = ['title', 'claim', 'purpose', 'manuscriptRole']
|
|
90
|
+
|
|
91
|
+
// touchObject:字段值实际变化才生效;semanticFields 中有字段真的变化时才推进对象
|
|
92
|
+
// revision 并使确认失效(对齐旧工具语义:提供了字段但值未变 ≠ 语义修改)。
|
|
93
|
+
function touchObject(obj, fields, { semanticFields = [], now }) {
|
|
94
|
+
let changed = false
|
|
95
|
+
let semanticChanged = false
|
|
96
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
97
|
+
if (value === undefined) continue
|
|
98
|
+
if (JSON.stringify(obj[key]) !== JSON.stringify(value) && semanticFields.includes(key)) semanticChanged = true
|
|
99
|
+
}
|
|
100
|
+
if (semanticChanged) rememberRevision(obj, 'revise', now)
|
|
101
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
102
|
+
if (value === undefined) continue
|
|
103
|
+
if (JSON.stringify(obj[key]) !== JSON.stringify(value)) {
|
|
104
|
+
obj[key] = value
|
|
105
|
+
changed = true
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (changed && semanticChanged) {
|
|
109
|
+
obj.revision = objectRevisionOf(obj) + 1
|
|
110
|
+
obj.confirmed = false
|
|
111
|
+
obj.confirmation = null
|
|
112
|
+
}
|
|
113
|
+
if (changed) obj.updatedAt = now
|
|
114
|
+
return changed
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function findResult(snapshot, resultId) {
|
|
118
|
+
const r = (snapshot.paper.results || []).find((x) => x && x.id === String(resultId))
|
|
119
|
+
if (!r) {
|
|
120
|
+
throw new StoreError('object-not-found', `Result ${resultId} 不存在(现有:${(snapshot.paper.results || []).map((x) => x.id).join('、') || '空'})`)
|
|
121
|
+
}
|
|
122
|
+
return r
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---- 确认(对象级 CAS)----------------------------------------------------------
|
|
126
|
+
export function applyConfirm(snapshot, payload, now) {
|
|
127
|
+
const objectId = str(payload.objectId, 100)
|
|
128
|
+
const obj = findObject(snapshot, objectId)
|
|
129
|
+
if (!obj) throw new StoreError('object-not-found', `对象 ${objectId} 不存在`)
|
|
130
|
+
const objectRevision = objectRevisionOf(obj)
|
|
131
|
+
const currentHash = contentHashOf(obj)
|
|
132
|
+
// M9:确认必须绑定对象 revision(防盲确认);T4:同时必须绑定对象内容哈希。
|
|
133
|
+
if (payload.expectedObjectRevision == null) {
|
|
134
|
+
throw new StoreError('invalid-command', `确认 ${objectId} 必须携带 expectedObjectRevision(确认绑定当前对象修订)`)
|
|
135
|
+
}
|
|
136
|
+
if (payload.expectedHash == null || String(payload.expectedHash).trim() === '') {
|
|
137
|
+
throw new StoreError('invalid-command', `确认 ${objectId} 必须携带 expectedHash(确认绑定当前对象内容哈希)`)
|
|
138
|
+
}
|
|
139
|
+
if (numOr(payload.expectedObjectRevision, -1) !== objectRevision) {
|
|
140
|
+
throw new StoreError('object-conflict', `对象 ${objectId} revision 过期(当前 ${objectRevision},请求基于 ${numOr(payload.expectedObjectRevision, -1)})`, { objectRevision, currentHash })
|
|
141
|
+
}
|
|
142
|
+
if (String(payload.expectedHash) !== currentHash) {
|
|
143
|
+
throw new StoreError('object-conflict', `对象 ${objectId} 内容已变化(hash 不一致)`, { objectRevision, currentHash })
|
|
144
|
+
}
|
|
145
|
+
const receipt = {
|
|
146
|
+
revisionId: `${objectId}-r${objectRevision}`,
|
|
147
|
+
// H1:确认显式记录 objectRevision;闸门以 revision 比对(语义修改才推进 revision,
|
|
148
|
+
// 执行性更新如记录证据/链任务/改状态不推进——不会把已确认对象锁死在闸门外)。
|
|
149
|
+
objectRevision,
|
|
150
|
+
contentHash: currentHash,
|
|
151
|
+
confirmedBy: 'user',
|
|
152
|
+
confirmedAt: now,
|
|
153
|
+
source: str(payload.source, 40) || 'conversation',
|
|
154
|
+
}
|
|
155
|
+
obj.confirmed = true
|
|
156
|
+
obj.confirmation = receipt
|
|
157
|
+
snapshot.decisions.confirmedReceipts.push({
|
|
158
|
+
objectId, objectRevision, contentHash: currentHash, confirmedAt: now, source: receipt.source,
|
|
159
|
+
})
|
|
160
|
+
return { objectId, objectRevision, contentHash: currentHash }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---- 派单硬闸门 ------------------------------------------------------------------
|
|
164
|
+
// 设计 §8.6:显式 resultIds;核心与全部目标 Result 当前 revision 已确认。
|
|
165
|
+
// H1:比对 confirmation.objectRevision(而非全量 contentHash)——执行性更新不使确认失效。
|
|
166
|
+
export function assertDispatchGate(snapshot, resultIds) {
|
|
167
|
+
const ids = [...new Set((Array.isArray(resultIds) ? resultIds : []).map((x) => String(x || '').trim()).filter(Boolean))]
|
|
168
|
+
if (ids.length === 0) {
|
|
169
|
+
throw new StoreError('dispatch-gate', '派单必须显式携带至少一个 resultId;不得从 active Result 或当前页面推断', { missing: true })
|
|
170
|
+
}
|
|
171
|
+
const core = snapshot.paper.core
|
|
172
|
+
if (!core || !core.claim) {
|
|
173
|
+
throw new StoreError('dispatch-gate', '文章核心尚未建立——先确立核心主张再派单', { core: false })
|
|
174
|
+
}
|
|
175
|
+
const coreRev = objectRevisionOf(core)
|
|
176
|
+
if (!core.confirmed || !core.confirmation || Number(core.confirmation.objectRevision || -1) !== coreRev) {
|
|
177
|
+
throw new StoreError('dispatch-gate', `核心当前修订尚未确认(r${coreRev})——未确认的主张不能派发执行任务`, { objectId: 'core', objectRevision: coreRev })
|
|
178
|
+
}
|
|
179
|
+
const blocked = []
|
|
180
|
+
for (const id of ids) {
|
|
181
|
+
const r = findResult(snapshot, id)
|
|
182
|
+
if (r.manuscriptRole === 'excluded' || r.status === 'dropped') {
|
|
183
|
+
blocked.push({ resultId: id, reason: `Result ${id} 已排除出正文` })
|
|
184
|
+
continue
|
|
185
|
+
}
|
|
186
|
+
const rev = objectRevisionOf(r)
|
|
187
|
+
if (!r.confirmed || !r.confirmation || Number(r.confirmation.objectRevision || -1) !== rev) {
|
|
188
|
+
blocked.push({ resultId: id, reason: `Result ${id} 当前修订(r${rev})尚未确认` })
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (blocked.length > 0) {
|
|
192
|
+
throw new StoreError('dispatch-gate', `派单闸门未通过:${blocked.map((b) => b.reason).join(';')}`, { blocked })
|
|
193
|
+
}
|
|
194
|
+
return { resultIds: ids, confirmedAtRevision: snapshot.revision }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---- 单操作 -----------------------------------------------------------------------
|
|
198
|
+
// 返回 { changedKeys, objects };拒绝 = StoreError。快照就地修改。
|
|
199
|
+
export function applyOperation(snapshot, op, now) {
|
|
200
|
+
const command = String(op.command || '')
|
|
201
|
+
const p = op.payload || {}
|
|
202
|
+
switch (command) {
|
|
203
|
+
case 'paper.propose-core': {
|
|
204
|
+
if (!snapshot.paper.core) {
|
|
205
|
+
snapshot.paper.core = { title: '', claim: '', innovation: '', venue: '', revision: 1, confirmed: false, confirmation: null, updatedAt: now }
|
|
206
|
+
}
|
|
207
|
+
const core = snapshot.paper.core
|
|
208
|
+
const fields = {}
|
|
209
|
+
if (p.title !== undefined) fields.title = str(p.title, 300)
|
|
210
|
+
if (p.claim !== undefined) fields.claim = str(p.claim, 1000)
|
|
211
|
+
if (p.innovation !== undefined) fields.innovation = str(p.innovation, 1000)
|
|
212
|
+
if (p.venue !== undefined) fields.venue = str(p.venue, 200)
|
|
213
|
+
const changed = touchObject(core, fields, { semanticFields: SEMANTIC_CORE_FIELDS, now })
|
|
214
|
+
if (!changed) return { changedKeys: [], objects: [] }
|
|
215
|
+
return { changedKeys: ['paper.core'], objects: [{ objectId: 'core', objectRevision: objectRevisionOf(core) }] }
|
|
216
|
+
}
|
|
217
|
+
case 'paper.propose-result': {
|
|
218
|
+
const claim = str(p.claim, 1000).trim()
|
|
219
|
+
if (!claim) throw new StoreError('invalid-command', 'paper.propose-result 需要 claim(可检验的子主张)')
|
|
220
|
+
// T6:移除 7 个 Result 硬上限;超过 5 个只在工具读模型给软提醒,不阻断科研自由。
|
|
221
|
+
const role = p.manuscriptRole === undefined ? 'main' : String(p.manuscriptRole)
|
|
222
|
+
if (!MANUSCRIPT_ROLES.includes(role)) throw new StoreError('invalid-command', `manuscriptRole 必须是:${MANUSCRIPT_ROLES.join(' | ')}`)
|
|
223
|
+
snapshot.paper.resultSeq = numOr(snapshot.paper.resultSeq, 0) + 1
|
|
224
|
+
const id = `res-${snapshot.paper.resultSeq}`
|
|
225
|
+
const result = {
|
|
226
|
+
id,
|
|
227
|
+
title: str(p.title, 200) || id,
|
|
228
|
+
claim,
|
|
229
|
+
purpose: str(p.purpose, 1000),
|
|
230
|
+
status: 'planned',
|
|
231
|
+
direction: 'not_assessed',
|
|
232
|
+
evidenceState: 'planned',
|
|
233
|
+
manuscriptRole: role,
|
|
234
|
+
presentation: { mode: 'undecided', rationale: '' },
|
|
235
|
+
claims: [{ id: `${id}-claim-1`, text: claim, revision: 1, status: 'active', createdAt: now, updatedAt: now }],
|
|
236
|
+
claimSeq: 1,
|
|
237
|
+
evidence: [],
|
|
238
|
+
evidenceSeq: 0,
|
|
239
|
+
tasks: [],
|
|
240
|
+
figures: [],
|
|
241
|
+
references: [],
|
|
242
|
+
notes: '',
|
|
243
|
+
revision: 1,
|
|
244
|
+
confirmed: false,
|
|
245
|
+
confirmation: null,
|
|
246
|
+
createdAt: now,
|
|
247
|
+
updatedAt: now,
|
|
248
|
+
}
|
|
249
|
+
snapshot.paper.results.push(result)
|
|
250
|
+
return { changedKeys: ['paper.results'], objects: [{ objectId: id, objectRevision: 1, created: true }] }
|
|
251
|
+
}
|
|
252
|
+
case 'paper.update-result': {
|
|
253
|
+
const r = findResult(snapshot, p.resultId)
|
|
254
|
+
const fields = {}
|
|
255
|
+
if (p.title !== undefined) fields.title = str(p.title, 200)
|
|
256
|
+
if (p.claim !== undefined) fields.claim = str(p.claim, 1000)
|
|
257
|
+
if (p.purpose !== undefined) fields.purpose = str(p.purpose, 1000)
|
|
258
|
+
if (p.manuscriptRole !== undefined) {
|
|
259
|
+
if (!MANUSCRIPT_ROLES.includes(String(p.manuscriptRole))) throw new StoreError('invalid-command', `manuscriptRole 必须是:${MANUSCRIPT_ROLES.join(' | ')}`)
|
|
260
|
+
fields.manuscriptRole = String(p.manuscriptRole)
|
|
261
|
+
}
|
|
262
|
+
if (p.status !== undefined) {
|
|
263
|
+
if (!RESULT_STATUSES.includes(String(p.status))) throw new StoreError('invalid-command', `status 必须是:${RESULT_STATUSES.join(' | ')}`)
|
|
264
|
+
fields.status = String(p.status)
|
|
265
|
+
}
|
|
266
|
+
if (p.direction !== undefined) {
|
|
267
|
+
if (!EVIDENCE_DIRECTIONS.includes(String(p.direction))) throw new StoreError('invalid-command', `direction 必须是:${EVIDENCE_DIRECTIONS.join(' | ')}`)
|
|
268
|
+
fields.direction = String(p.direction)
|
|
269
|
+
}
|
|
270
|
+
if (p.evidenceState !== undefined) {
|
|
271
|
+
if (!EVIDENCE_STATES.includes(String(p.evidenceState))) throw new StoreError('invalid-command', `evidenceState 必须是:${EVIDENCE_STATES.join(' | ')}`)
|
|
272
|
+
fields.evidenceState = String(p.evidenceState)
|
|
273
|
+
}
|
|
274
|
+
if (p.notes !== undefined) fields.notes = str(p.notes, 4000)
|
|
275
|
+
// M2(语义审查):阴性结果的重新评估说明是领域约束(不只工具提示)——
|
|
276
|
+
// 按「合并后状态」校验:已是 negative 的结果,后续任何更新都不能清空 notes,
|
|
277
|
+
// 否则一次普通的 notes:'' 更新即可绕过该约束。
|
|
278
|
+
if (String(fields.status ?? r.status) === 'negative') {
|
|
279
|
+
const effectiveNotes = fields.notes !== undefined ? fields.notes : r.notes
|
|
280
|
+
if (!String(effectiveNotes || '').trim()) {
|
|
281
|
+
throw new StoreError('invalid-command', 'status=negative 需要 notes 重新评估说明:该负面结果对核心主张意味着什么——调整本 result 的表述/方法重跑,还是动摇核心(证伪讨论)?')
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (p.presentationMode !== undefined) {
|
|
285
|
+
if (!PRESENTATION_MODES.includes(String(p.presentationMode))) throw new StoreError('invalid-command', `presentationMode 必须是:${PRESENTATION_MODES.join(' | ')}`)
|
|
286
|
+
fields.presentation = { ...(r.presentation || {}), mode: String(p.presentationMode), rationale: str(p.presentationRationale, 1000) || (r.presentation && r.presentation.rationale) || '' }
|
|
287
|
+
} else if (p.presentationRationale !== undefined) {
|
|
288
|
+
fields.presentation = { ...(r.presentation || {}), mode: (r.presentation && r.presentation.mode) || 'undecided', rationale: str(p.presentationRationale, 1000) }
|
|
289
|
+
}
|
|
290
|
+
// T6:能改变确认摘要/纳入排除/派单目标的字段必须推进 revision + 使旧确认失效。
|
|
291
|
+
// status 只有跨越 dropped 边界(纳入 ↔ 排除)才视为语义;进行中/已支持等执行事实仍不失效确认。
|
|
292
|
+
const semanticFields = [...SEMANTIC_RESULT_FIELDS]
|
|
293
|
+
if (fields.status !== undefined && ((r.status === 'dropped') !== (fields.status === 'dropped'))) {
|
|
294
|
+
semanticFields.push('status')
|
|
295
|
+
}
|
|
296
|
+
const previousClaim = r.claim
|
|
297
|
+
const changed = touchObject(r, fields, { semanticFields, now })
|
|
298
|
+
if (!changed) return { changedKeys: [], objects: [] }
|
|
299
|
+
// M1(语义审查):主 claim 文本变化时同步首个 active claim(该 claim 自身 revision 推进,
|
|
300
|
+
// 保留历史;证据绑定与审查核对清单继续使用稳定 claim id)。
|
|
301
|
+
// 阻断修复:只有「claim 文本真的变了」且「该 active claim 仍是原主主张的镜像」才同步——
|
|
302
|
+
// 主 claim 退休后首个 active claim 可能是用户手写子主张,不能被陈旧主主张文本覆盖;
|
|
303
|
+
// 覆盖前把旧文本压入 claim.history,保证可追溯。
|
|
304
|
+
if (fields.claim !== undefined && fields.claim !== previousClaim && Array.isArray(r.claims)) {
|
|
305
|
+
const primary = r.claims.find((c) => c && c.status !== 'retired')
|
|
306
|
+
if (primary && primary.text === previousClaim && primary.text !== r.claim) {
|
|
307
|
+
if (!Array.isArray(primary.history)) primary.history = []
|
|
308
|
+
primary.history.push({ text: primary.text, revision: numOr(primary.revision, 1), at: now })
|
|
309
|
+
primary.text = r.claim
|
|
310
|
+
primary.revision = numOr(primary.revision, 1) + 1
|
|
311
|
+
primary.updatedAt = now
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return { changedKeys: ['paper.results'], objects: [{ objectId: r.id, objectRevision: objectRevisionOf(r) }] }
|
|
315
|
+
}
|
|
316
|
+
case 'paper.record-claim': {
|
|
317
|
+
const r = findResult(snapshot, p.resultId)
|
|
318
|
+
const text = str(p.text, 1000).trim()
|
|
319
|
+
if (!text) throw new StoreError('invalid-command', 'paper.record-claim 需要 text')
|
|
320
|
+
r.claimSeq = numOr(r.claimSeq, r.claims.length) + 1
|
|
321
|
+
const id = `${r.id}-claim-${r.claimSeq}`
|
|
322
|
+
r.claims.push({ id, text, revision: 1, status: 'active', createdAt: now, updatedAt: now })
|
|
323
|
+
r.revision = objectRevisionOf(r) + 1
|
|
324
|
+
r.confirmed = false
|
|
325
|
+
r.confirmation = null
|
|
326
|
+
r.updatedAt = now
|
|
327
|
+
return { changedKeys: ['paper.results'], objects: [{ objectId: r.id, objectRevision: objectRevisionOf(r) }] }
|
|
328
|
+
}
|
|
329
|
+
case 'paper.retire-claim': {
|
|
330
|
+
// M6(语义审查):主张退休——保留 id 与证据引用,status=retired;语义修改推进
|
|
331
|
+
// Result revision 并使确认失效;退休后审查清单/语义哈希不再把它当 active 核对。
|
|
332
|
+
const r = findResult(snapshot, p.resultId)
|
|
333
|
+
const claimId = str(p.claimId, 120)
|
|
334
|
+
const claim = r.claims.find((c) => c && c.id === claimId)
|
|
335
|
+
if (!claim) throw new StoreError('object-not-found', `Claim ${claimId} 不存在(现有:${r.claims.map((c) => c.id).join('、') || '空'})`)
|
|
336
|
+
if (claim.status !== 'retired') {
|
|
337
|
+
claim.status = 'retired'
|
|
338
|
+
claim.retiredReason = str(p.reason, 1000)
|
|
339
|
+
claim.updatedAt = now
|
|
340
|
+
r.revision = objectRevisionOf(r) + 1
|
|
341
|
+
r.confirmed = false
|
|
342
|
+
r.confirmation = null
|
|
343
|
+
r.updatedAt = now
|
|
344
|
+
}
|
|
345
|
+
return { changedKeys: ['paper.results'], objects: [{ objectId: r.id, objectRevision: objectRevisionOf(r) }] }
|
|
346
|
+
}
|
|
347
|
+
case 'paper.record-evidence': {
|
|
348
|
+
const r = findResult(snapshot, p.resultId)
|
|
349
|
+
const direction = String(p.direction || '')
|
|
350
|
+
const state = String(p.state || '')
|
|
351
|
+
if (!EVIDENCE_DIRECTIONS.includes(direction)) throw new StoreError('invalid-command', `direction 必须是:${EVIDENCE_DIRECTIONS.join(' | ')}`)
|
|
352
|
+
if (!EVIDENCE_STATES.includes(state)) throw new StoreError('invalid-command', `state 必须是:${EVIDENCE_STATES.join(' | ')}`)
|
|
353
|
+
const claimIds = [...new Set((Array.isArray(p.claimIds) ? p.claimIds : []).map((x) => String(x)).filter(Boolean))]
|
|
354
|
+
if (claimIds.length === 0) throw new StoreError('invalid-command', 'claimIds 至少包含一个 Claim id')
|
|
355
|
+
const known = new Set(r.claims.map((c) => c.id))
|
|
356
|
+
const unknown = claimIds.filter((id) => !known.has(id))
|
|
357
|
+
if (unknown.length > 0) throw new StoreError('invalid-command', `未知 Claim:${unknown.join('、')}`)
|
|
358
|
+
const sourceLocator = str(p.sourceLocator, 2000).trim()
|
|
359
|
+
const allowedInterpretation = str(p.allowedInterpretation, 2000).trim()
|
|
360
|
+
if (state === 'verified' && (!sourceLocator || !allowedInterpretation)) {
|
|
361
|
+
throw new StoreError('invalid-command', 'state=verified 必须同时提供 sourceLocator 与 allowedInterpretation')
|
|
362
|
+
}
|
|
363
|
+
r.evidenceSeq = numOr(r.evidenceSeq, 0) + 1
|
|
364
|
+
r.evidence.push({
|
|
365
|
+
id: `${r.id}-ev-${r.evidenceSeq}`,
|
|
366
|
+
claimIds,
|
|
367
|
+
direction,
|
|
368
|
+
state,
|
|
369
|
+
sourceLocator,
|
|
370
|
+
conditions: str(p.conditions, 2000),
|
|
371
|
+
uncertainty: str(p.uncertainty, 2000),
|
|
372
|
+
allowedInterpretation,
|
|
373
|
+
prohibitedInterpretation: str(p.prohibitedInterpretation, 2000),
|
|
374
|
+
note: str(p.note, 2000),
|
|
375
|
+
createdAt: now,
|
|
376
|
+
updatedAt: now,
|
|
377
|
+
})
|
|
378
|
+
r.updatedAt = now
|
|
379
|
+
return { changedKeys: ['paper.results'], objects: [{ objectId: r.id, objectRevision: objectRevisionOf(r) }] }
|
|
380
|
+
}
|
|
381
|
+
case 'paper.set-focus': {
|
|
382
|
+
if (p.activeResultId !== undefined && p.activeResultId !== null) findResult(snapshot, p.activeResultId)
|
|
383
|
+
snapshot.focus.activeResultId = p.activeResultId === undefined ? snapshot.focus.activeResultId : (p.activeResultId === null ? null : String(p.activeResultId))
|
|
384
|
+
if (p.blockers !== undefined) {
|
|
385
|
+
snapshot.focus.blockers = (Array.isArray(p.blockers) ? p.blockers : []).map((b) => ({
|
|
386
|
+
summary: str(b && b.summary, 500),
|
|
387
|
+
detail: str(b && b.detail, 2000),
|
|
388
|
+
at: now,
|
|
389
|
+
}))
|
|
390
|
+
}
|
|
391
|
+
return { changedKeys: ['focus'], objects: [] }
|
|
392
|
+
}
|
|
393
|
+
case 'paper.record-next-decision': {
|
|
394
|
+
const text = str(p.text, 1000).trim()
|
|
395
|
+
if (!text) throw new StoreError('invalid-command', 'paper.record-next-decision 需要 text')
|
|
396
|
+
const entry = {
|
|
397
|
+
text,
|
|
398
|
+
objectId: p.objectId ? str(p.objectId, 100) : null,
|
|
399
|
+
status: 'pending',
|
|
400
|
+
proposedBy: str(p.proposedBy, 100) || 'assistant',
|
|
401
|
+
createdAt: now,
|
|
402
|
+
}
|
|
403
|
+
snapshot.focus.nextDecisions.push(entry)
|
|
404
|
+
if (snapshot.focus.nextDecisions.length > 20) snapshot.focus.nextDecisions.splice(0, snapshot.focus.nextDecisions.length - 20)
|
|
405
|
+
return { changedKeys: ['focus'], objects: [] }
|
|
406
|
+
}
|
|
407
|
+
case 'paper.confirm-revision': {
|
|
408
|
+
const info = applyConfirm(snapshot, p, now)
|
|
409
|
+
return { changedKeys: p.objectId === 'core' ? ['paper.core'] : ['paper.results'], objects: [info] }
|
|
410
|
+
}
|
|
411
|
+
case 'paper.set-question': {
|
|
412
|
+
// T6:研究问题/范围/来源摘要的显式写入命令。属于项目上下文,不是论文对象语义——
|
|
413
|
+
// 推进 project revision + 审计 + 卡片投影,但不自动确认/失效核心与 Result 的确认。
|
|
414
|
+
const fields = {}
|
|
415
|
+
if (p.question !== undefined) fields.question = str(p.question, 1000).trim()
|
|
416
|
+
if (p.scope !== undefined) fields.scope = str(p.scope, 2000).trim()
|
|
417
|
+
if (p.sourceSummary !== undefined) fields.sourceSummary = str(p.sourceSummary, 4000).trim()
|
|
418
|
+
if (Object.keys(fields).length === 0) {
|
|
419
|
+
throw new StoreError('invalid-command', 'paper.set-question 至少需要 question | scope | sourceSummary 之一')
|
|
420
|
+
}
|
|
421
|
+
let changed = false
|
|
422
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
423
|
+
if (String(snapshot.paper[key] || '') !== value) {
|
|
424
|
+
snapshot.paper[key] = value
|
|
425
|
+
changed = true
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (!changed) return { changedKeys: [], objects: [] }
|
|
429
|
+
snapshot.paper.questionUpdatedAt = now
|
|
430
|
+
return { changedKeys: ['paper.question'], objects: [] }
|
|
431
|
+
}
|
|
432
|
+
case 'paper.set-stage': {
|
|
433
|
+
// T6:阶段是描述性上下文,不是执行闸门;只校验枚举并记录说明。
|
|
434
|
+
// 正式派单只由 paper.dispatch-gate 把关(显式 resultIds + 核心/目标 Result 当前修订已确认)。
|
|
435
|
+
const stage = String(p.stage || '')
|
|
436
|
+
if (!PAPER_STAGES.includes(stage)) throw new StoreError('invalid-command', `stage 必须是:${PAPER_STAGES.join(' | ')}`)
|
|
437
|
+
snapshot.paper.stage = stage
|
|
438
|
+
snapshot.paper.stageNote = str(p.note, 1000)
|
|
439
|
+
snapshot.paper.stageUpdatedAt = now
|
|
440
|
+
return { changedKeys: ['paper'], objects: [] }
|
|
441
|
+
}
|
|
442
|
+
case 'paper.set-submission-check': {
|
|
443
|
+
const item = String(p.item || '')
|
|
444
|
+
if (!SUBMISSION_ITEMS.includes(item)) throw new StoreError('invalid-command', `item 必须是:${SUBMISSION_ITEMS.join(' | ')}`)
|
|
445
|
+
const status = String(p.status || '')
|
|
446
|
+
if (!['pending', 'complete', 'not_applicable'].includes(status)) throw new StoreError('invalid-command', 'status 必须是 pending | complete | not_applicable')
|
|
447
|
+
snapshot.paper.submission[item] = { status, note: str(p.note, 2000), updatedAt: now }
|
|
448
|
+
return { changedKeys: ['paper'], objects: [] }
|
|
449
|
+
}
|
|
450
|
+
case 'paper.link-task': {
|
|
451
|
+
const r = findResult(snapshot, p.resultId)
|
|
452
|
+
const taskId = str(p.taskId, 100)
|
|
453
|
+
if (!taskId) throw new StoreError('invalid-command', 'paper.link-task 需要 taskId')
|
|
454
|
+
if (!r.tasks.includes(taskId)) r.tasks.push(taskId)
|
|
455
|
+
const ref = { taskId, resultIds: [r.id], boundAt: now }
|
|
456
|
+
const existing = snapshot.links.taskRefs.find((x) => x.taskId === taskId)
|
|
457
|
+
if (existing) {
|
|
458
|
+
if (!existing.resultIds.includes(r.id)) existing.resultIds.push(r.id)
|
|
459
|
+
} else {
|
|
460
|
+
snapshot.links.taskRefs.push(ref)
|
|
461
|
+
}
|
|
462
|
+
return { changedKeys: ['links', 'paper.results'], objects: [] }
|
|
463
|
+
}
|
|
464
|
+
case 'paper.unlink-task': {
|
|
465
|
+
// 任务删除/改挂时解绑(幂等):从 result.tasks 与 taskRefs 摘除
|
|
466
|
+
const taskId = str(p.taskId, 100)
|
|
467
|
+
if (!taskId) throw new StoreError('invalid-command', 'paper.unlink-task 需要 taskId')
|
|
468
|
+
let touched = false
|
|
469
|
+
for (const r of snapshot.paper.results || []) {
|
|
470
|
+
if (Array.isArray(r.tasks) && r.tasks.includes(taskId)) {
|
|
471
|
+
r.tasks = r.tasks.filter((x) => x !== taskId)
|
|
472
|
+
r.updatedAt = now
|
|
473
|
+
touched = true
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const before = snapshot.links.taskRefs.length
|
|
477
|
+
snapshot.links.taskRefs = snapshot.links.taskRefs.filter((x) => x.taskId !== taskId)
|
|
478
|
+
if (snapshot.links.taskRefs.length !== before) touched = true
|
|
479
|
+
return touched ? { changedKeys: ['links', 'paper.results'], objects: [] } : { changedKeys: [], objects: [] }
|
|
480
|
+
}
|
|
481
|
+
case 'paper.unlink-artifact': {
|
|
482
|
+
const artifactId = str(p.artifactId, 100)
|
|
483
|
+
if (!artifactId) throw new StoreError('invalid-command', 'paper.unlink-artifact 需要 artifactId')
|
|
484
|
+
let touched = false
|
|
485
|
+
for (const r of snapshot.paper.results || []) {
|
|
486
|
+
if (Array.isArray(r.figures) && r.figures.includes(artifactId)) {
|
|
487
|
+
r.figures = r.figures.filter((x) => x !== artifactId)
|
|
488
|
+
r.updatedAt = now
|
|
489
|
+
touched = true
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
snapshot.links.artifactRefs = snapshot.links.artifactRefs.filter((x) => x.artifactId !== artifactId)
|
|
493
|
+
// 成果索引同步:解除关联后 artifactIndex 的 resultIds 也要摘掉(以 paper.figures 为准),
|
|
494
|
+
// 否则 state-view 的 materials 仍显示旧归属。
|
|
495
|
+
let indexTouched = false
|
|
496
|
+
const indexRecord = indexItemOf(snapshot, artifactId)
|
|
497
|
+
if (indexRecord && Array.isArray(indexRecord.resultIds)) {
|
|
498
|
+
const stillLinked = new Set()
|
|
499
|
+
for (const r of snapshot.paper.results || []) {
|
|
500
|
+
if (Array.isArray(r.figures) && r.figures.includes(artifactId)) stillLinked.add(r.id)
|
|
501
|
+
}
|
|
502
|
+
const kept = indexRecord.resultIds.filter((resultId) => stillLinked.has(resultId))
|
|
503
|
+
if (kept.length !== indexRecord.resultIds.length) {
|
|
504
|
+
indexRecord.resultIds = kept
|
|
505
|
+
indexRecord.updatedAt = now
|
|
506
|
+
indexTouched = true
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const changedKeys = []
|
|
510
|
+
if (touched) changedKeys.push('links', 'paper.results')
|
|
511
|
+
if (indexTouched) changedKeys.push('artifactIndex')
|
|
512
|
+
return { changedKeys, objects: [] }
|
|
513
|
+
return touched ? { changedKeys: ['links', 'paper.results', 'artifactIndex'], objects: [] } : { changedKeys: [], objects: [] }
|
|
514
|
+
}
|
|
515
|
+
case 'paper.link-artifact': {
|
|
516
|
+
const artifactId = str(p.artifactId, 100)
|
|
517
|
+
if (!artifactId) throw new StoreError('invalid-command', 'paper.link-artifact 需要 artifactId')
|
|
518
|
+
const resultIds = Array.isArray(p.resultIds)
|
|
519
|
+
? p.resultIds.map((x) => String(x))
|
|
520
|
+
: (p.resultId !== undefined ? [str(p.resultId, 100)] : [])
|
|
521
|
+
if (!resultIds.length || resultIds.some((x) => !x)) throw new StoreError('invalid-command', 'paper.link-artifact 需要 resultId 或 resultIds')
|
|
522
|
+
let touched = false
|
|
523
|
+
for (const resultId of resultIds) {
|
|
524
|
+
const r = findResult(snapshot, resultId)
|
|
525
|
+
if (!Array.isArray(r.figures)) r.figures = []
|
|
526
|
+
if (!r.figures.includes(artifactId)) { r.figures.push(artifactId); r.updatedAt = now; touched = true }
|
|
527
|
+
if (!snapshot.links.artifactRefs.some((x) => x.artifactId === artifactId && x.resultIds.includes(r.id))) {
|
|
528
|
+
snapshot.links.artifactRefs.push({ artifactId, resultIds: [r.id], boundAt: now })
|
|
529
|
+
touched = true
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
// 成果索引同步:已登记 artifact 的 resultIds/claimIds 一并追加,
|
|
533
|
+
// 使 materials 与成果归属在两条读模型下一致(原先该分支不可达,索引永不同步)。
|
|
534
|
+
let indexTouched = false
|
|
535
|
+
const indexRecord = indexItemOf(snapshot, artifactId)
|
|
536
|
+
if (indexRecord) {
|
|
537
|
+
const before = JSON.stringify([indexRecord.resultIds, indexRecord.claimIds])
|
|
538
|
+
indexRecord.resultIds = cleanIndexList([...(indexRecord.resultIds || []), ...resultIds])
|
|
539
|
+
if (Array.isArray(p.claimIds)) indexRecord.claimIds = cleanIndexList([...(indexRecord.claimIds || []), ...p.claimIds.map((x) => String(x))])
|
|
540
|
+
if (JSON.stringify([indexRecord.resultIds, indexRecord.claimIds]) !== before) { indexRecord.updatedAt = now; indexTouched = true }
|
|
541
|
+
}
|
|
542
|
+
const changedKeys = []
|
|
543
|
+
if (touched) changedKeys.push('links', 'paper.results')
|
|
544
|
+
if (indexTouched) changedKeys.push('artifactIndex')
|
|
545
|
+
return { changedKeys, objects: [] }
|
|
546
|
+
}
|
|
547
|
+
case 'paper.link-reference': {
|
|
548
|
+
const r = findResult(snapshot, p.resultId)
|
|
549
|
+
const usedAs = String(p.usedAs || '')
|
|
550
|
+
if (!['method', 'concept', 'background', 'evidence'].includes(usedAs)) {
|
|
551
|
+
throw new StoreError('invalid-command', 'usedAs 必须是 method | concept | background | evidence')
|
|
552
|
+
}
|
|
553
|
+
const doi = p.doi ? str(p.doi, 200).toLowerCase() : ''
|
|
554
|
+
const title = str(p.title, 300).trim()
|
|
555
|
+
if (!doi && !title) throw new StoreError('invalid-command', 'doi 与 title 至少提供一个')
|
|
556
|
+
const dup = r.references.find((x) => x.usedAs === usedAs && ((doi && x.doi === doi) || (!doi && title && x.title === title)))
|
|
557
|
+
if (!dup) {
|
|
558
|
+
r.references.push({ doi, title, usedAs, claimIds: [...new Set((Array.isArray(p.claimIds) ? p.claimIds : []).map(String))], relation: str(p.relation, 40) || (usedAs === 'method' ? 'method' : 'context'), sourceLocator: str(p.sourceLocator, 1000), providedTitle: str(p.providedTitle, 300), verified: p.verified === true, verifyError: str(p.verifyError, 300), checkedAt: p.verified === true ? now : 0, addedAt: now })
|
|
559
|
+
} else {
|
|
560
|
+
// 低-5:幂等合并;无实际变化时不产生 changedKeys(不推进项目 revision)
|
|
561
|
+
const merged = [...new Set([...(dup.claimIds || []), ...((Array.isArray(p.claimIds) ? p.claimIds : []).map(String))])]
|
|
562
|
+
if (merged.length !== (dup.claimIds || []).length || (p.sourceLocator && dup.sourceLocator !== str(p.sourceLocator, 1000))) {
|
|
563
|
+
dup.claimIds = merged
|
|
564
|
+
if (p.sourceLocator) dup.sourceLocator = str(p.sourceLocator, 1000)
|
|
565
|
+
return { changedKeys: ['paper.results'], objects: [] }
|
|
566
|
+
}
|
|
567
|
+
return { changedKeys: [], objects: [] }
|
|
568
|
+
}
|
|
569
|
+
return { changedKeys: ['paper.results'], objects: [] }
|
|
570
|
+
}
|
|
571
|
+
case 'paper.verify-reference': {
|
|
572
|
+
const r = findResult(snapshot, p.resultId)
|
|
573
|
+
const usedAs = String(p.usedAs || '')
|
|
574
|
+
if (!['method', 'concept', 'background', 'evidence'].includes(usedAs)) {
|
|
575
|
+
throw new StoreError('invalid-command', 'usedAs 必须是 method | concept | background | evidence')
|
|
576
|
+
}
|
|
577
|
+
const doi = str(p.doi, 200).toLowerCase()
|
|
578
|
+
const ref0 = r.references.find((x) => x.usedAs === usedAs && (doi ? x.doi === doi : true))
|
|
579
|
+
if (!ref0) throw new StoreError('object-not-found', `未找到(${usedAs}${doi ? ` doi:${doi}` : ''})的参考文献条目`)
|
|
580
|
+
ref0.verified = p.verified === true
|
|
581
|
+
ref0.verifyError = p.verified === true ? '' : str(p.verifyError, 300)
|
|
582
|
+
ref0.checkedAt = now
|
|
583
|
+
if (p.verified === true && p.title) ref0.title = str(p.title, 300)
|
|
584
|
+
return { changedKeys: ['paper.results'], objects: [] }
|
|
585
|
+
}
|
|
586
|
+
case 'paper.remove-reference': {
|
|
587
|
+
const r = findResult(snapshot, p.resultId)
|
|
588
|
+
const usedAs = String(p.usedAs || '')
|
|
589
|
+
const doi = str(p.doi, 200).toLowerCase()
|
|
590
|
+
const before = r.references.length
|
|
591
|
+
r.references = r.references.filter((x) => !(x.usedAs === usedAs && (doi ? x.doi === doi : true)))
|
|
592
|
+
if (r.references.length === before) throw new StoreError('object-not-found', `未找到(${usedAs}${doi ? ` doi:${doi}` : ''})的参考文献条目`)
|
|
593
|
+
return { changedKeys: ['paper.results'], objects: [] }
|
|
594
|
+
}
|
|
595
|
+
case 'paper.set-screening': {
|
|
596
|
+
const r = findResult(snapshot, p.resultId)
|
|
597
|
+
const decision = String(p.decision || '')
|
|
598
|
+
if (!['include', 'exclude', 'maybe'].includes(decision)) throw new StoreError('invalid-command', 'decision 必须是 include | exclude | maybe')
|
|
599
|
+
const note = str(p.screeningNote, 2000)
|
|
600
|
+
if (decision === 'exclude' && note.trim() === '') throw new StoreError('invalid-command', 'decision=exclude 需要 screeningNote 说明排除理由')
|
|
601
|
+
r.screening = { decision, note, decidedAt: now }
|
|
602
|
+
return { changedKeys: ['paper.results'], objects: [] }
|
|
603
|
+
}
|
|
604
|
+
case 'paper.set-narrative': {
|
|
605
|
+
snapshot.paper.narrative = str(p.narrative, 4000)
|
|
606
|
+
return { changedKeys: ['paper'], objects: [] }
|
|
607
|
+
}
|
|
608
|
+
case 'paper.import-legacy-result': {
|
|
609
|
+
// 阶段 5:旧 blueprint.json 的 result 完整字段导入(只读迁移语义)。
|
|
610
|
+
// 幂等:legacyId 已存在(或同名 claim 的 result 已存在)则跳过;旧 confirmed=true
|
|
611
|
+
// 保留为 legacy-migration 凭据(与旧 paperspine normalizeConfirmation 同语义)。
|
|
612
|
+
const legacy = p.legacy && typeof p.legacy === 'object' ? p.legacy : null
|
|
613
|
+
if (!legacy || typeof legacy.id !== 'string' || !legacy.id) throw new StoreError('invalid-command', 'paper.import-legacy-result 需要 legacy.id')
|
|
614
|
+
const existing = (snapshot.paper.results || []).find((r) => r && (r.id === legacy.id || r.legacyId === legacy.id))
|
|
615
|
+
if (existing) return { changedKeys: [], objects: [], skipped: legacy.id }
|
|
616
|
+
const id = typeof legacy.id === 'string' && /^res-\d+$/.test(legacy.id) ? legacy.id : `res-${numOr(snapshot.paper.resultSeq, 0) + 1}`
|
|
617
|
+
if (!snapshot.paper.results.some((r) => r && r.id === id)) snapshot.paper.resultSeq = Math.max(numOr(snapshot.paper.resultSeq, 0), Number(String(id).slice(4)) || 0)
|
|
618
|
+
const claims = (Array.isArray(legacy.claims) ? legacy.claims : []).filter((c) => c && typeof c === 'object' && typeof c.id === 'string').map((c) => ({
|
|
619
|
+
id: String(c.id), text: str(c.text, 1000), revision: numOr(c.revision, 1), status: c.status === 'retired' ? 'retired' : 'active', createdAt: now, updatedAt: now,
|
|
620
|
+
}))
|
|
621
|
+
const primaryClaimText = str(legacy.claim, 1000)
|
|
622
|
+
if (claims.length === 0 && primaryClaimText) claims.push({ id: `${id}-claim-1`, text: primaryClaimText, revision: 1, status: 'active', createdAt: now, updatedAt: now })
|
|
623
|
+
const result = {
|
|
624
|
+
id,
|
|
625
|
+
legacyId: String(legacy.id),
|
|
626
|
+
title: str(legacy.title, 200) || id,
|
|
627
|
+
claim: primaryClaimText || (claims[0] ? claims[0].text : ''),
|
|
628
|
+
purpose: str(legacy.purpose, 1000),
|
|
629
|
+
status: RESULT_STATUSES.includes(String(legacy.status)) ? String(legacy.status) : 'planned',
|
|
630
|
+
direction: EVIDENCE_DIRECTIONS.includes(String(legacy.direction)) ? String(legacy.direction) : 'not_assessed',
|
|
631
|
+
evidenceState: EVIDENCE_STATES.includes(String(legacy.evidenceState)) ? String(legacy.evidenceState) : 'planned',
|
|
632
|
+
manuscriptRole: MANUSCRIPT_ROLES.includes(String(legacy.manuscriptRole)) ? String(legacy.manuscriptRole) : 'main',
|
|
633
|
+
presentation: {
|
|
634
|
+
mode: PRESENTATION_MODES.includes(legacy.presentation && legacy.presentation.mode) ? legacy.presentation.mode : 'undecided',
|
|
635
|
+
rationale: str(legacy.presentation && legacy.presentation.rationale, 1000),
|
|
636
|
+
},
|
|
637
|
+
claims,
|
|
638
|
+
claimSeq: claims.length,
|
|
639
|
+
evidence: (Array.isArray(legacy.evidence) ? legacy.evidence : []).filter((e) => e && typeof e === 'object').map((e, i) => ({
|
|
640
|
+
id: typeof e.id === 'string' && e.id ? String(e.id) : `${id}-ev-${i + 1}`,
|
|
641
|
+
claimIds: (Array.isArray(e.claimIds) ? e.claimIds : []).map(String),
|
|
642
|
+
direction: EVIDENCE_DIRECTIONS.includes(String(e.direction)) ? String(e.direction) : 'not_assessed',
|
|
643
|
+
state: EVIDENCE_STATES.includes(String(e.state)) ? String(e.state) : 'planned',
|
|
644
|
+
sourceLocator: str(e.sourceLocator, 2000),
|
|
645
|
+
conditions: str(e.conditions, 2000),
|
|
646
|
+
uncertainty: str(e.uncertainty, 2000),
|
|
647
|
+
allowedInterpretation: str(e.allowedInterpretation, 2000),
|
|
648
|
+
prohibitedInterpretation: str(e.prohibitedInterpretation, 2000),
|
|
649
|
+
note: str(e.note, 2000),
|
|
650
|
+
createdAt: now,
|
|
651
|
+
updatedAt: now,
|
|
652
|
+
})),
|
|
653
|
+
evidenceSeq: (Array.isArray(legacy.evidence) ? legacy.evidence : []).length,
|
|
654
|
+
tasks: (Array.isArray(legacy.tasks) ? legacy.tasks : []).map(String).slice(0, 50),
|
|
655
|
+
figures: (Array.isArray(legacy.figures) ? legacy.figures : []).map(String).slice(0, 50),
|
|
656
|
+
references: (Array.isArray(legacy.references) ? legacy.references : []).filter((x) => x && typeof x === 'object').map((x) => ({
|
|
657
|
+
doi: str(x.doi, 200).toLowerCase(),
|
|
658
|
+
title: str(x.title, 300),
|
|
659
|
+
usedAs: ['method', 'concept', 'background', 'evidence'].includes(String(x.usedAs)) ? String(x.usedAs) : 'background',
|
|
660
|
+
claimIds: (Array.isArray(x.claimIds) ? x.claimIds : []).map(String),
|
|
661
|
+
relation: str(x.relation, 40),
|
|
662
|
+
sourceLocator: str(x.sourceLocator, 1000),
|
|
663
|
+
providedTitle: str(x.providedTitle, 300),
|
|
664
|
+
verified: x.verified === true,
|
|
665
|
+
verifyError: str(x.verifyError, 300),
|
|
666
|
+
checkedAt: Number(x.checkedAt) || 0,
|
|
667
|
+
addedAt: now,
|
|
668
|
+
})),
|
|
669
|
+
screening: legacy.screening && typeof legacy.screening === 'object' ? { decision: ['include', 'exclude', 'maybe'].includes(String(legacy.screening.decision)) ? String(legacy.screening.decision) : 'maybe', note: str(legacy.screening.note, 2000), decidedAt: now } : null,
|
|
670
|
+
notes: str(legacy.notes, 4000),
|
|
671
|
+
revision: numOr(legacy.revision, 1),
|
|
672
|
+
confirmed: false,
|
|
673
|
+
confirmation: null,
|
|
674
|
+
createdAt: now,
|
|
675
|
+
updatedAt: now,
|
|
676
|
+
}
|
|
677
|
+
// 旧确认凭据迁移(fail-safe:hash 不可复用旧值——记录 legacy-migration 标记并绑定 revision)
|
|
678
|
+
if (legacy.confirmed === true) {
|
|
679
|
+
result.confirmed = true
|
|
680
|
+
result.confirmation = {
|
|
681
|
+
revisionId: `${id}-r${result.revision}`,
|
|
682
|
+
objectRevision: result.revision,
|
|
683
|
+
contentHash: contentHashOf(result),
|
|
684
|
+
confirmedBy: 'user',
|
|
685
|
+
confirmedAt: now,
|
|
686
|
+
source: 'legacy-migration',
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
snapshot.paper.results.push(result)
|
|
690
|
+
return { changedKeys: ['paper.results'], objects: [{ objectId: id, objectRevision: result.revision, imported: true }] }
|
|
691
|
+
}
|
|
692
|
+
case 'paper.archive-object': {
|
|
693
|
+
const objectId = str(p.objectId, 100)
|
|
694
|
+
const obj = findObject(snapshot, objectId)
|
|
695
|
+
if (!obj) throw new StoreError('object-not-found', `对象 ${objectId} 不存在`)
|
|
696
|
+
rememberRevision(obj, 'archive', now)
|
|
697
|
+
obj.archived = true
|
|
698
|
+
obj.revision = objectRevisionOf(obj) + 1
|
|
699
|
+
obj.confirmed = false
|
|
700
|
+
obj.confirmation = null
|
|
701
|
+
obj.updatedAt = now
|
|
702
|
+
return { changedKeys: ['paper.revisions'], objects: [{ objectId, objectRevision: objectRevisionOf(obj), archived: true }] }
|
|
703
|
+
}
|
|
704
|
+
case 'paper.record-proposal': {
|
|
705
|
+
const source = str(p.source, 300).trim()
|
|
706
|
+
if (!source) throw new StoreError('invalid-command', '结构提案必须带来源;不能把聊天全文或任意 Markdown 当作业务状态')
|
|
707
|
+
if (!Array.isArray(snapshot.paper.proposals)) snapshot.paper.proposals = []
|
|
708
|
+
const proposal = {
|
|
709
|
+
id: `prop-${snapshot.paper.proposals.length + 1}`,
|
|
710
|
+
source,
|
|
711
|
+
objectIds: (Array.isArray(p.objectIds) ? p.objectIds : []).map((item) => str(item, 80)).filter(Boolean),
|
|
712
|
+
note: str(p.note, 500),
|
|
713
|
+
createdAt: now,
|
|
714
|
+
}
|
|
715
|
+
snapshot.paper.proposals.push(proposal)
|
|
716
|
+
return { changedKeys: ['paper.proposals'], objects: [{ objectId: proposal.id, proposal: true }] }
|
|
717
|
+
}
|
|
718
|
+
case 'paper.register-artifact': {
|
|
719
|
+
const out = registerArtifact(snapshot, { ...p, projectId: snapshot.projectId }, now)
|
|
720
|
+
return { changedKeys: out.created ? ['artifactIndex'] : [], objects: [{ objectId: out.id, created: out.created }] }
|
|
721
|
+
}
|
|
722
|
+
case 'paper.relink-artifact': {
|
|
723
|
+
const out = relinkArtifact(snapshot, p, now)
|
|
724
|
+
if (!out.ok) throw new StoreError('object-conflict', out.diagnostic || '历史版本引用不能被同名文件替换', out)
|
|
725
|
+
return { changedKeys: ['artifactIndex'], objects: [{ objectId: out.record.id, relocated: true }] }
|
|
726
|
+
}
|
|
727
|
+
case 'paper.dispatch-gate': {
|
|
728
|
+
const gate = assertDispatchGate(snapshot, p.resultIds)
|
|
729
|
+
return { changedKeys: [], objects: [], gate }
|
|
730
|
+
}
|
|
731
|
+
case 'project.set-metadata': {
|
|
732
|
+
// workspaceKey 是服务端授权列,不接受客户端、工具或 metadata 覆盖。
|
|
733
|
+
if (p.title !== undefined) snapshot.metadata.title = str(p.title, 300)
|
|
734
|
+
if (p.workspaceIdentity !== undefined) snapshot.metadata.workspaceIdentity = str(p.workspaceIdentity, 500)
|
|
735
|
+
if (snapshot.metadata && Object.prototype.hasOwnProperty.call(snapshot.metadata, 'workspaceKey')) {
|
|
736
|
+
delete snapshot.metadata.workspaceKey
|
|
737
|
+
}
|
|
738
|
+
return { changedKeys: ['metadata'], objects: [] }
|
|
739
|
+
}
|
|
740
|
+
default:
|
|
741
|
+
throw new StoreError('invalid-command', `未知领域命令 ${command || '(空)'}(可用:${COMMANDS.join(', ')})`)
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// ---- 批量执行(唯一写入口)---------------------------------------------------------
|
|
746
|
+
// batch: { mutationId, expectedRevision?, actor, operations: [{ operationId?, command, payload }], source? }
|
|
747
|
+
// 语义:单事务全成全败;一次 project revision;每个语义变化的对象各自 revision++。
|
|
748
|
+
// M3:角色权限在 module 内断言(不依赖调用方自觉)——paper.* 写命令需要 writePaper;
|
|
749
|
+
// 派单闸门需要 dispatch 能力;teammate/attached 直接 forbidden。
|
|
750
|
+
// M2:纯闸门批次(只含 paper.dispatch-gate)走只读校验——不推进 revision、不落回执,
|
|
751
|
+
// 每次都基于当前快照重算(幂等重放不会给出过期结论)。
|
|
752
|
+
// M4:project.attach-session 经 store.attachSessionWithAudit 统一维护表+快照+审计。
|
|
753
|
+
export function executePaperCommands(store, ref, batch) {
|
|
754
|
+
if (!ref || !ref.projectId) return { kind: 'invalid', reason: '当前会话尚未绑定项目(先经 ensureProject 建立绑定)' }
|
|
755
|
+
const ops = Array.isArray(batch.operations) ? batch.operations : []
|
|
756
|
+
if (ops.length === 0) return { kind: 'invalid', reason: 'operations 不能为空' }
|
|
757
|
+
for (const op of ops) {
|
|
758
|
+
if (!COMMANDS.includes(String(op.command))) {
|
|
759
|
+
return { kind: 'invalid', reason: `未知领域命令 ${String(op.command || '(空)')}` }
|
|
760
|
+
}
|
|
761
|
+
// attach-session 走 store.attachSessionWithAudit 单 op 特判(无 applyOperation 分支);
|
|
762
|
+
// 混入批量时给出明确原因,而不是落到「未知领域命令」。
|
|
763
|
+
if (String(op.command) === 'project.attach-session' && ops.length !== 1) {
|
|
764
|
+
return { kind: 'invalid', reason: 'project.attach-session 只能作为单条操作执行(绑定审计需独立事务)' }
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
const source = String(batch.source || 'tool')
|
|
768
|
+
const caps = ref.capabilities || {}
|
|
769
|
+
// M3:能力断言(设计 §18.5 后端重校验)
|
|
770
|
+
if (ref.relationship === 'fork') return { kind: 'forbidden', reason: 'fork 与父项目写时复制隔离,不能写入该项目' }
|
|
771
|
+
if (!caps.writePaper) return { kind: 'forbidden', reason: '当前会话没有论文语义写权限(成员只能提交提案与任务回报)' }
|
|
772
|
+
|
|
773
|
+
// M4:attach-session 统一路径(root_bindings 表为访问权真源)
|
|
774
|
+
if (ops.length === 1 && String(ops[0].command) === 'project.attach-session') {
|
|
775
|
+
const rootSessionId = String((ops[0].payload || {}).rootSessionId || '')
|
|
776
|
+
if (!rootSessionId) return { kind: 'invalid', reason: 'project.attach-session 需要 rootSessionId' }
|
|
777
|
+
try {
|
|
778
|
+
const out = store.attachSessionWithAudit({ projectId: ref.projectId, rootSessionId, actor: batch.actor || {} })
|
|
779
|
+
if (out.kind === 'applied') {
|
|
780
|
+
return { kind: 'applied', receipt: { mutationId: String(batch.mutationId || ''), projectId: ref.projectId, revision: out.revision, command: 'project.attach-session', changedKeys: ['bindings'], objects: [], appliedAt: Date.now(), source } }
|
|
781
|
+
}
|
|
782
|
+
return { kind: 'already-applied', receipt: { mutationId: String(batch.mutationId || ''), projectId: ref.projectId, command: 'project.attach-session', bound: true, source } }
|
|
783
|
+
} catch (err) {
|
|
784
|
+
if (err instanceof StoreError) {
|
|
785
|
+
return { kind: err.code === 'binding-conflict' ? 'conflict' : 'invalid', reason: err.message }
|
|
786
|
+
}
|
|
787
|
+
throw err
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
const isPureGate = ops.every((op) => String(op.command) === 'paper.dispatch-gate')
|
|
792
|
+
if (isPureGate) {
|
|
793
|
+
// M2:只读闸门——不消耗 revision,重放总是基于当前状态
|
|
794
|
+
if (!caps.dispatch) return { kind: 'forbidden', reason: '当前会话没有派单权限(只有队长可以派单)' }
|
|
795
|
+
const snap = store.snapshotOf(ref.projectId)
|
|
796
|
+
if (!snap || snap.corrupt) return { kind: 'invalid', reason: (snap && snap.error) || '项目不存在' }
|
|
797
|
+
try {
|
|
798
|
+
let gate = null
|
|
799
|
+
for (const op of ops) gate = assertDispatchGate(snap.snapshot, (op.payload || {}).resultIds)
|
|
800
|
+
return { kind: 'applied', receipt: { mutationId: String(batch.mutationId || ''), projectId: ref.projectId, gateOnly: true, command: 'paper.dispatch-gate', gate, appliedAt: Date.now(), source } }
|
|
801
|
+
} catch (err) {
|
|
802
|
+
if (err instanceof StoreError) return { kind: 'invalid', reason: err.message, ...(err.details || {}) }
|
|
803
|
+
throw err
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
if (ops.some((op) => String(op.command) === 'paper.dispatch-gate') && !caps.dispatch) {
|
|
808
|
+
return { kind: 'forbidden', reason: '当前会话没有派单权限(只有队长可以派单)' }
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// T3:legacy 导入台账由 batch.legacyImport 传给 store,在同一事务内与命令/审计/回执提交。
|
|
812
|
+
const storeHooks = batch.legacyImport
|
|
813
|
+
? { legacyImport: { ...batch.legacyImport, projectId: ref.projectId } }
|
|
814
|
+
: {}
|
|
815
|
+
const result = store.execute(ref.projectId, {
|
|
816
|
+
mutationId: String(batch.mutationId || ''),
|
|
817
|
+
expectedRevision: batch.expectedRevision,
|
|
818
|
+
command: ops.length === 1 ? String(ops[0].command) : `batch(${ops.length})`,
|
|
819
|
+
payload: { operations: ops.map((op) => ({ command: op.command, payload: op.payload })) },
|
|
820
|
+
actor: batch.actor || {},
|
|
821
|
+
source: source,
|
|
822
|
+
}, (current, now) => {
|
|
823
|
+
const changedKeys = new Set()
|
|
824
|
+
const objects = []
|
|
825
|
+
const gate = {}
|
|
826
|
+
for (const op of ops) {
|
|
827
|
+
// 确认凭据的 source 与批次来源一致(action-card / ui-action / conversation…)
|
|
828
|
+
const payload = op.command === 'paper.confirm-revision' ? { ...(op.payload || {}), source } : op.payload
|
|
829
|
+
const out = applyOperation(current, { command: op.command, payload }, now)
|
|
830
|
+
for (const k of out.changedKeys || []) changedKeys.add(k)
|
|
831
|
+
for (const o of out.objects || []) objects.push({ operationId: op.operationId || null, ...o })
|
|
832
|
+
if (out.gate) Object.assign(gate, out.gate)
|
|
833
|
+
}
|
|
834
|
+
current.metadata.updatedAt = now
|
|
835
|
+
return { snapshot: current, changedKeys: [...changedKeys], objects, ...gate }
|
|
836
|
+
}, storeHooks)
|
|
837
|
+
return result
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// 对象级确认的便捷封装(Remote act / Action Card 共用)
|
|
841
|
+
export function confirmObjectRevision(store, ref, payload, opts = {}) {
|
|
842
|
+
return executePaperCommands(store, ref, {
|
|
843
|
+
mutationId: String(opts.mutationId || ''),
|
|
844
|
+
expectedRevision: opts.expectedRevision,
|
|
845
|
+
source: opts.source || 'conversation',
|
|
846
|
+
actor: { sessionId: ref.currentSessionId, relationship: ref.relationship },
|
|
847
|
+
operations: [{ command: 'paper.confirm-revision', payload }],
|
|
848
|
+
})
|
|
849
|
+
}
|