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
package/lib/figures.js
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
// dsh-science — 绘图登记模块(P3-3)
|
|
2
|
+
// 模型生成图后调用 sci_figure_register 登记;工作台图库与审查器都从这里取数据。
|
|
3
|
+
// v0.6.0:登记时可带 result_id,把图表直接挂为文章蓝图 result 的图表证据
|
|
4
|
+
// (对齐逻辑在 lib/blueprint.js linkFigureToResult,失败不阻断登记)。
|
|
5
|
+
// v0.9.0(Track 3,对齐 aipoch artifacts 不可变版本 + Claude Science 版本 stepper,机制原创):
|
|
6
|
+
// 版本链——同一 path(或同一标题)再次登记且内容变化(sha 不同)→ 新档案记
|
|
7
|
+
// prevId/prevSha/version(对比入口在客户端图表卡);内容完全相同 → 幂等返回旧档案不新建。
|
|
8
|
+
// v0.10.0(B1,v0.7 遗留①):图片格式校验——扩展名白名单 + 文件头 magic bytes 双重校验,
|
|
9
|
+
// 任意文件(如 .txt)不再能冒充图表混进图库。
|
|
10
|
+
|
|
11
|
+
import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
14
|
+
import { dataDirOf } from './store.js'
|
|
15
|
+
import { linkFigureToResult } from './blueprint.js'
|
|
16
|
+
import { inspectFigureBuffer, auditFigureRecord, JOURNAL_PROFILES } from './figureqa.js'
|
|
17
|
+
// 路线 B T1:图件/图件计划写入稳定项目归属(projectId/rootSessionId),版本链与查询
|
|
18
|
+
// 不得跨项目复用其他项目的图件档案。
|
|
19
|
+
import { readScope, sessionIdOf } from './project-adapter.js'
|
|
20
|
+
import { projectAttributionOf, createRecordScopeResolver } from './project-context.js'
|
|
21
|
+
|
|
22
|
+
// B1:图片扩展名白名单与 magic bytes 校验。错误信息统一以「文件不是有效图片」开头。
|
|
23
|
+
const IMAGE_EXT_WHITELIST = new Set(['png', 'jpg', 'jpeg', 'svg', 'gif', 'webp', 'tiff', 'pdf'])
|
|
24
|
+
const IMAGE_EXT_HINT = 'png/jpg/jpeg/svg/gif/webp/tiff/pdf'
|
|
25
|
+
|
|
26
|
+
function charOf(cp) {
|
|
27
|
+
return Number.isFinite(cp) && cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : ''
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 扫描前先解码字符引用,防 javascript: / java	script: 一类混淆绕过;
|
|
31
|
+
// 数字引用允许省略分号(HTML 解析器同样接受),否则 javascript: 会漏检。
|
|
32
|
+
function decodeCharRefs(s) {
|
|
33
|
+
return s
|
|
34
|
+
.replace(/&#x([0-9a-f]+);?/gi, (_, h) => charOf(parseInt(h, 16)))
|
|
35
|
+
.replace(/&#(\d+);?/g, (_, d) => charOf(Number(d)))
|
|
36
|
+
.replace(/	/gi, '\t')
|
|
37
|
+
.replace(/
/gi, '\n')
|
|
38
|
+
.replace(/:/gi, ':')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 去掉成对 XML 注释:注释里的 <script> 不执行,不构成风险(未闭合注释保留 → fail-closed)。
|
|
42
|
+
function stripXmlComments(text) {
|
|
43
|
+
return text.replace(/<!--[\s\S]*?-->/g, '')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 单遍标签扫描:返回每个标签的原文与位置。属性值里的 ">" 不会截断标签;
|
|
47
|
+
// 遇到没有闭合 ">" 的 "<" 直接结束(其后不可能再有完整标签),避免 /<...>*>/ 的回溯爆炸。
|
|
48
|
+
function scanTags(text) {
|
|
49
|
+
const tags = []
|
|
50
|
+
let i = 0
|
|
51
|
+
while (i < text.length) {
|
|
52
|
+
const lt = text.indexOf('<', i)
|
|
53
|
+
if (lt < 0) break
|
|
54
|
+
let j = lt + 1
|
|
55
|
+
let quote = null
|
|
56
|
+
for (; j < text.length; j++) {
|
|
57
|
+
const ch = text[j]
|
|
58
|
+
if (quote) {
|
|
59
|
+
if (ch === quote) quote = null
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
if (ch === '"' || ch === "'") quote = ch
|
|
63
|
+
else if (ch === '>') break
|
|
64
|
+
}
|
|
65
|
+
if (j >= text.length) break
|
|
66
|
+
tags.push({ start: lt, end: j + 1, raw: text.slice(lt, j + 1) })
|
|
67
|
+
i = j + 1
|
|
68
|
+
}
|
|
69
|
+
return tags
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function tagNameOf(raw) {
|
|
73
|
+
let i = 1
|
|
74
|
+
if (raw[i] === '/') i++
|
|
75
|
+
while (i < raw.length && /\s/.test(raw[i])) i++
|
|
76
|
+
let name = ''
|
|
77
|
+
while (i < raw.length && !/[\s/>]/.test(raw[i])) {
|
|
78
|
+
name += raw[i]
|
|
79
|
+
i++
|
|
80
|
+
}
|
|
81
|
+
return name.toLowerCase()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 引号感知的属性解析:`<svg a="b"onload=…>` 能被识别出 onload;
|
|
85
|
+
// `title="onload=x"`(值里出现 on* 文本)不会被误判。
|
|
86
|
+
function attrsOf(raw) {
|
|
87
|
+
const attrs = []
|
|
88
|
+
let i = 1
|
|
89
|
+
if (raw[i] === '/') i++
|
|
90
|
+
while (i < raw.length && !/[\s/>]/.test(raw[i])) i++
|
|
91
|
+
while (i < raw.length) {
|
|
92
|
+
while (i < raw.length && /\s/.test(raw[i])) i++
|
|
93
|
+
if (i >= raw.length || raw[i] === '>') break
|
|
94
|
+
if (raw[i] === '/') {
|
|
95
|
+
i++
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
let name = ''
|
|
99
|
+
while (i < raw.length && !/[\s=/>]/.test(raw[i])) {
|
|
100
|
+
name += raw[i]
|
|
101
|
+
i++
|
|
102
|
+
}
|
|
103
|
+
if (!name) {
|
|
104
|
+
i++
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
while (i < raw.length && /\s/.test(raw[i])) i++
|
|
108
|
+
let value = ''
|
|
109
|
+
if (raw[i] === '=') {
|
|
110
|
+
i++
|
|
111
|
+
while (i < raw.length && /\s/.test(raw[i])) i++
|
|
112
|
+
const q = raw[i]
|
|
113
|
+
if (q === '"' || q === "'") {
|
|
114
|
+
i++
|
|
115
|
+
while (i < raw.length && raw[i] !== q) {
|
|
116
|
+
value += raw[i]
|
|
117
|
+
i++
|
|
118
|
+
}
|
|
119
|
+
i++
|
|
120
|
+
} else {
|
|
121
|
+
while (i < raw.length && !/[\s>]/.test(raw[i])) {
|
|
122
|
+
value += raw[i]
|
|
123
|
+
i++
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
attrs.push({ name, value })
|
|
128
|
+
}
|
|
129
|
+
return attrs
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const EXEC_URL_RE = /javascript:|vbscript:|data:text\/html|data:image\/svg\+xml/
|
|
133
|
+
const CSS_EXEC_RE = /(?:javascript|vbscript):|expression\(/
|
|
134
|
+
|
|
135
|
+
// CSS 十六进制转义(\6a avascript: → javascript:)先还原再检测,防拆词绕过。
|
|
136
|
+
function decodeCssEscapes(s) {
|
|
137
|
+
return String(s).replace(/\\([0-9a-f]{1,6})[ \t\r\n\f]?/gi, (_, h) => {
|
|
138
|
+
const cp = parseInt(h, 16)
|
|
139
|
+
return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : ''
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// SVG 解码(UTF-16LE/BE:先看 BOM,再看首字节 3C 00 / 00 3C 的无 BOM 形态;
|
|
144
|
+
// 奇数尾字节先截齐,避免 swap16 抛错)。其余按 UTF-8。
|
|
145
|
+
export function decodeSvgText(buf) {
|
|
146
|
+
if (buf[0] === 0xff && buf[1] === 0xfe) return buf.subarray(2).toString('utf16le')
|
|
147
|
+
if (buf[0] === 0xfe && buf[1] === 0xff) {
|
|
148
|
+
const body = buf.subarray(2)
|
|
149
|
+
return Buffer.from(body.subarray(0, body.length - (body.length % 2))).swap16().toString('utf16le')
|
|
150
|
+
}
|
|
151
|
+
if (buf[0] === 0x3c && buf[1] === 0x00) {
|
|
152
|
+
const body = buf.subarray(0, buf.length - (buf.length % 2))
|
|
153
|
+
return body.toString('utf16le')
|
|
154
|
+
}
|
|
155
|
+
if (buf[0] === 0x00 && buf[1] === 0x3c) {
|
|
156
|
+
const body = buf.subarray(0, buf.length - (buf.length % 2))
|
|
157
|
+
return Buffer.from(body).swap16().toString('utf16le')
|
|
158
|
+
}
|
|
159
|
+
return buf.toString('utf8')
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// SVG 可执行内容检测(安全):图库与 /file 路由以 image/svg+xml 原样提供 SVG,浏览器直接
|
|
163
|
+
// 打开时脚本会执行——登记闸门拒绝 script 标签/事件属性/可执行 URL/内嵌 ENTITY 声明。
|
|
164
|
+
// 返回拒绝原因字符串;纯静态 SVG 返回 null。
|
|
165
|
+
export function svgActiveContentReason(svgText) {
|
|
166
|
+
const text = stripXmlComments(decodeCharRefs(String(svgText)))
|
|
167
|
+
// 命名空间前缀(<svg:script>/<x:script>)同样可执行,需一并拦截
|
|
168
|
+
if (/<\s*(?:[\w.-]+:)?script\b/i.test(text)) return '<script> 标签'
|
|
169
|
+
if (/<\?xml-stylesheet\b/i.test(text)) return 'xml-stylesheet 处理指令(XSLT 可输出脚本化 HTML)'
|
|
170
|
+
// HTML 嵌入标签会创建可执行上下文(iframe srcdoc 会把 <script> 解码成脚本),静态图不需要
|
|
171
|
+
if (/<\s*(?:[\w.-]+:)?(foreignObject|iframe|embed|object)\b/i.test(text)) return 'HTML 嵌入标签(foreignObject/iframe/embed/object)'
|
|
172
|
+
if (/<!ENTITY/i.test(text)) return 'DOCTYPE 内嵌 XML 实体声明'
|
|
173
|
+
const tags = scanTags(text)
|
|
174
|
+
for (const t of tags) {
|
|
175
|
+
if (tagNameOf(t.raw) === 'style') continue
|
|
176
|
+
for (const a of attrsOf(t.raw)) {
|
|
177
|
+
if (/^(?:[A-Za-z_][\w.-]*:)?on[a-z]+$/i.test(a.name)) return `事件属性 ${a.name}`
|
|
178
|
+
// 去掉属性值内全部空白/控制字符再查 URL scheme,堵 java	script 拆词混淆
|
|
179
|
+
const compact = a.value.replace(/[\s\x00-\x20]+/g, '').toLowerCase()
|
|
180
|
+
if (EXEC_URL_RE.test(compact)) return '可执行 URL(javascript:/vbscript:/data:text/html/data:image/svg+xml)'
|
|
181
|
+
if (a.name.toLowerCase() === 'style' && CSS_EXEC_RE.test(decodeCssEscapes(a.value).replace(/[\s\x00-\x20]+/g, '').toLowerCase())) return '样式表内可执行 URL(style)'
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// <style> 块内容同样可执行(CSS url(javascript:)/expression())——按标签位置配对内容,避免全文重复扫描
|
|
185
|
+
for (let k = 0; k < tags.length; k++) {
|
|
186
|
+
if (tagNameOf(tags[k].raw) !== 'style' || tags[k].raw.startsWith('</')) continue
|
|
187
|
+
for (let m = k + 1; m < tags.length; m++) {
|
|
188
|
+
if (tagNameOf(tags[m].raw) === 'style' && tags[m].raw.startsWith('</')) {
|
|
189
|
+
const body = text.slice(tags[k].end, tags[m].start)
|
|
190
|
+
if (CSS_EXEC_RE.test(decodeCssEscapes(body).replace(/[\s\x00-\x20]+/g, '').toLowerCase())) return '样式表内可执行 URL(style)'
|
|
191
|
+
k = m
|
|
192
|
+
break
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function validateImageFile(filePath, buf) {
|
|
200
|
+
const ext = (String(filePath).split('.').pop() || '').toLowerCase()
|
|
201
|
+
if (!IMAGE_EXT_WHITELIST.has(ext)) {
|
|
202
|
+
return { ok: false, error: `文件不是有效图片:扩展名 .${ext || '(无)'} 不在白名单(允许 ${IMAGE_EXT_HINT})` }
|
|
203
|
+
}
|
|
204
|
+
const head = buf.subarray(0, 12)
|
|
205
|
+
const ascii = (start, len) => head.subarray(start, start + len).toString('latin1')
|
|
206
|
+
let magicOk = false
|
|
207
|
+
switch (ext) {
|
|
208
|
+
case 'png':
|
|
209
|
+
magicOk = head[0] === 0x89 && ascii(1, 3) === 'PNG'
|
|
210
|
+
break
|
|
211
|
+
case 'jpg':
|
|
212
|
+
case 'jpeg':
|
|
213
|
+
magicOk = head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff
|
|
214
|
+
break
|
|
215
|
+
case 'gif':
|
|
216
|
+
magicOk = ascii(0, 4) === 'GIF8'
|
|
217
|
+
break
|
|
218
|
+
case 'webp':
|
|
219
|
+
magicOk = ascii(0, 4) === 'RIFF' && ascii(8, 4) === 'WEBP'
|
|
220
|
+
break
|
|
221
|
+
case 'tiff':
|
|
222
|
+
magicOk =
|
|
223
|
+
(ascii(0, 2) === 'II' && head[2] === 0x2a && head[3] === 0x00) ||
|
|
224
|
+
(ascii(0, 2) === 'MM' && head[2] === 0x00 && head[3] === 0x2a)
|
|
225
|
+
break
|
|
226
|
+
case 'svg': {
|
|
227
|
+
// SVG 是文本格式:头部(含 BOM/注释/doctype 的容差窗口)内应出现 '<svg' 根标签。
|
|
228
|
+
// UTF-16(LE/BE BOM)先解码成 UTF-8 字符串再校验,否则交错的 \0 会让 magic 误判。
|
|
229
|
+
const svgText = decodeSvgText(buf)
|
|
230
|
+
magicOk = svgText.slice(0, 2048).includes('<svg')
|
|
231
|
+
if (magicOk) {
|
|
232
|
+
const reason = svgActiveContentReason(svgText)
|
|
233
|
+
if (reason) {
|
|
234
|
+
return { ok: false, error: `SVG 含可执行内容(${reason}),拒绝登记——请移除脚本/事件属性/可执行 URL,重新导出纯静态 SVG` }
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
break
|
|
238
|
+
}
|
|
239
|
+
case 'pdf':
|
|
240
|
+
magicOk = ascii(0, 5) === '%PDF-'
|
|
241
|
+
break
|
|
242
|
+
default:
|
|
243
|
+
magicOk = false
|
|
244
|
+
}
|
|
245
|
+
if (!magicOk) {
|
|
246
|
+
return { ok: false, error: `文件不是有效图片:文件头与 .${ext} 格式不符(扩展名 ${IMAGE_EXT_HINT} 需匹配对应 magic bytes)` }
|
|
247
|
+
}
|
|
248
|
+
return { ok: true, ext }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 路径归一化(版本链同图判断用:Windows 大小写不敏感 + 统一分隔符)
|
|
252
|
+
function normPath(p) {
|
|
253
|
+
return String(p || '').replace(/\\/g, '/').toLowerCase()
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function log(msg) {
|
|
257
|
+
console.log(`[dsh-science figures] ${msg}`)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const figuresFile = () => join(dataDirOf(), 'figures.json')
|
|
261
|
+
const figurePlansFile = () => join(dataDirOf(), 'figure-plans.json')
|
|
262
|
+
|
|
263
|
+
// 图表档案损坏隔离(X3,对齐 blueprint fix4):解析失败或结构非法(应为键值对象,数组/标量
|
|
264
|
+
// 均不行)→ 坏文件改名备份为 figures.json.corrupt-<ts>(quarantine,备份保留)+ console.error
|
|
265
|
+
// 报警,返回空档案。文件不存在(首跑常态)不算损坏。
|
|
266
|
+
function quarantineFigures(reason) {
|
|
267
|
+
const backupName = `figures.json.corrupt-${Date.now()}`
|
|
268
|
+
try {
|
|
269
|
+
renameSync(figuresFile(), join(dataDirOf(), backupName))
|
|
270
|
+
console.error(`[dsh-science figures] figures.json ${reason},已隔离备份为 ${backupName}`)
|
|
271
|
+
} catch (berr) {
|
|
272
|
+
console.error(`[dsh-science figures] figures.json ${reason}且隔离备份失败(${berr && berr.message})`)
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function loadFigures() {
|
|
277
|
+
let raw = null
|
|
278
|
+
try {
|
|
279
|
+
raw = readFileSync(figuresFile(), 'utf8')
|
|
280
|
+
} catch (err) {
|
|
281
|
+
if (err && err.code !== 'ENOENT') {
|
|
282
|
+
console.error(`[dsh-science figures] figures.json read failed (treated as empty): ${err && err.message}`)
|
|
283
|
+
}
|
|
284
|
+
return {}
|
|
285
|
+
}
|
|
286
|
+
let parsed = null
|
|
287
|
+
try {
|
|
288
|
+
parsed = JSON.parse(raw)
|
|
289
|
+
} catch (err) {
|
|
290
|
+
quarantineFigures(`解析失败(${err && err.message})`)
|
|
291
|
+
return {}
|
|
292
|
+
}
|
|
293
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
294
|
+
quarantineFigures('结构非法(应为键值对象)')
|
|
295
|
+
return {}
|
|
296
|
+
}
|
|
297
|
+
return parsed
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function saveFigures(figures) {
|
|
301
|
+
// X3:原子写(先写 .tmp 再 renameSync 覆盖;rename 失败退回直接写,避免登记丢失)
|
|
302
|
+
const text = JSON.stringify(figures, null, 2)
|
|
303
|
+
const tmp = `${figuresFile()}.tmp`
|
|
304
|
+
try {
|
|
305
|
+
writeFileSync(tmp, text, 'utf8')
|
|
306
|
+
renameSync(tmp, figuresFile())
|
|
307
|
+
} catch (err) {
|
|
308
|
+
log(`atomic persist fallback: ${err && err.message}`)
|
|
309
|
+
writeFileSync(figuresFile(), text, 'utf8')
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function loadFigurePlans() {
|
|
314
|
+
let raw = null
|
|
315
|
+
try {
|
|
316
|
+
raw = readFileSync(figurePlansFile(), 'utf8')
|
|
317
|
+
} catch (err) {
|
|
318
|
+
if (err && err.code !== 'ENOENT') console.error(`[dsh-science figures] figure-plans.json 读取失败(按空计划继续): ${err && err.message}`)
|
|
319
|
+
return {}
|
|
320
|
+
}
|
|
321
|
+
let parsed = null
|
|
322
|
+
try {
|
|
323
|
+
parsed = JSON.parse(raw)
|
|
324
|
+
} catch (err) {
|
|
325
|
+
quarantineFigurePlans(`解析失败(${err && err.message})`)
|
|
326
|
+
return {}
|
|
327
|
+
}
|
|
328
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
329
|
+
quarantineFigurePlans('结构非法(应为键值对象)')
|
|
330
|
+
return {}
|
|
331
|
+
}
|
|
332
|
+
return parsed
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function quarantineFigurePlans(reason) {
|
|
336
|
+
const backupName = `figure-plans.json.corrupt-${Date.now()}`
|
|
337
|
+
try {
|
|
338
|
+
renameSync(figurePlansFile(), join(dataDirOf(), backupName))
|
|
339
|
+
console.error(`[dsh-science figures] figure-plans.json ${reason},已隔离备份为 ${backupName}`)
|
|
340
|
+
} catch (err) {
|
|
341
|
+
console.error(`[dsh-science figures] figure-plans.json ${reason}且隔离备份失败(${err && err.message})`)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function saveFigurePlans(plans) {
|
|
346
|
+
const text = JSON.stringify(plans, null, 2)
|
|
347
|
+
const tmp = `${figurePlansFile()}.tmp`
|
|
348
|
+
try {
|
|
349
|
+
writeFileSync(tmp, text, 'utf8')
|
|
350
|
+
renameSync(tmp, figurePlansFile())
|
|
351
|
+
} catch (err) {
|
|
352
|
+
log(`figure plan atomic persist fallback: ${err && err.message}`)
|
|
353
|
+
writeFileSync(figurePlansFile(), text, 'utf8')
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function textList(v, max = 40) {
|
|
358
|
+
return Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim()).slice(0, max).map((x) => x.trim().slice(0, 2000)) : []
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function targetProfileOf(raw) {
|
|
362
|
+
const value = String(raw || '').trim().toLowerCase()
|
|
363
|
+
if (value === 'nature' || value.includes('nature')) return 'nature'
|
|
364
|
+
return 'generic'
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function planFromArgs(args) {
|
|
368
|
+
const targetJournal = targetProfileOf(args.target_journal)
|
|
369
|
+
const profile = JOURNAL_PROFILES[targetJournal]
|
|
370
|
+
const targetWidth = Number(args.target_width_mm)
|
|
371
|
+
return {
|
|
372
|
+
title: String(args.figure_title || '').trim().slice(0, 300),
|
|
373
|
+
resultId: args.result_id ? String(args.result_id).trim().slice(0, 100) : null,
|
|
374
|
+
claim: String(args.figure_claim || '').trim().slice(0, 4000),
|
|
375
|
+
figureRole: String(args.figure_role || 'main').trim().slice(0, 80),
|
|
376
|
+
targetJournal,
|
|
377
|
+
targetJournalName: String(args.target_journal || profile.label).trim().slice(0, 200),
|
|
378
|
+
submissionStage: String(args.submission_stage || 'final').trim().slice(0, 40),
|
|
379
|
+
targetWidthMm: Number.isFinite(targetWidth) && targetWidth > 0 ? targetWidth : profile.widthsMm.single,
|
|
380
|
+
requiresStatistics: args.requires_statistics === true,
|
|
381
|
+
statisticsNote: String(args.statistics_note || '').trim().slice(0, 4000),
|
|
382
|
+
sourceDataPaths: textList(args.source_data_paths),
|
|
383
|
+
templateSource: String(args.template_source || '').trim().slice(0, 2000),
|
|
384
|
+
templateVersion: String(args.template_version || '').trim().slice(0, 300),
|
|
385
|
+
templateLicense: String(args.template_license || '').trim().slice(0, 300),
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export function registerFigureTools(ctx, opts = {}) {
|
|
390
|
+
const store = opts.store
|
|
391
|
+
// T1:当前执行的 ProjectRef + 新记录归属。readScope 失败(未知会话)时只保留宿主侧
|
|
392
|
+
// sessionId 作为 root 兜底——不猜测 projectId。
|
|
393
|
+
const scopeRefOf = (exec) => {
|
|
394
|
+
try {
|
|
395
|
+
const scopeRead = readScope(ctx, exec, { store })
|
|
396
|
+
if (scopeRead && scopeRead.ok) return { ref: scopeRead.ref, snapshot: scopeRead.snapshot || null }
|
|
397
|
+
} catch { /* 作用域不可用时走下面的兜底 */ }
|
|
398
|
+
// 兜底:只保留宿主侧 sessionId 作为 root 候选,不猜测 projectId;读取侧不会跨项目匹配。
|
|
399
|
+
const sid = sessionIdOf(exec)
|
|
400
|
+
return {
|
|
401
|
+
ref: sid
|
|
402
|
+
? { projectId: null, rootSessionId: String(sid), currentSessionId: String(sid), relationship: 'unknown', capabilities: { read: false, propose: false, writePaper: false, dispatch: false } }
|
|
403
|
+
: null,
|
|
404
|
+
snapshot: null,
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const attributionOf = (exec, ref) => {
|
|
408
|
+
const base = projectAttributionOf(ref)
|
|
409
|
+
return { projectId: base.projectId, rootSessionId: base.rootSessionId || sessionIdOf(exec) || null }
|
|
410
|
+
}
|
|
411
|
+
ctx.tools.register({
|
|
412
|
+
name: 'sci_figure_plan',
|
|
413
|
+
description:
|
|
414
|
+
'在绘图前建立期刊图件计划:声明所属 result、该图要表达的主张、目标期刊/最终宽度、统计说明、源数据路径和模板许可。返回 planId;随后 sci_figure_register 传 plan_id 绑定。当前内置 nature 与 generic 前检配置,其他期刊按 generic 执行并保留原名称。',
|
|
415
|
+
parameters: {
|
|
416
|
+
figure_title: { type: 'string', required: true, description: '图件标题' },
|
|
417
|
+
result_id: { type: 'string', description: '所属文章 result(res-N)' },
|
|
418
|
+
figure_claim: { type: 'string', description: '这张图支持的一句话主张' },
|
|
419
|
+
figure_role: { type: 'string', description: 'main / extended-data / supplementary / graphical-abstract' },
|
|
420
|
+
target_journal: { type: 'string', description: 'nature 或目标期刊名称;未内置者使用 generic 前检' },
|
|
421
|
+
submission_stage: { type: 'string', description: 'initial / revision / final' },
|
|
422
|
+
target_width_mm: { type: 'number', description: '最终版面宽度(mm);缺省按目标配置单栏宽' },
|
|
423
|
+
requires_statistics: { type: 'boolean', description: '图中是否包含需说明的统计结果' },
|
|
424
|
+
statistics_note: { type: 'string', description: 'n、误差线、检验、多重比较等说明' },
|
|
425
|
+
source_data_paths: { type: 'array', description: '图中数据的源文件路径列表' },
|
|
426
|
+
template_source: { type: 'string', description: '模板/素材来源(如 SFL exact selector 或仓库 URL)' },
|
|
427
|
+
template_version: { type: 'string', description: '模板精确版本、commit 或哈希' },
|
|
428
|
+
template_license: { type: 'string', description: '模板/素材许可证' },
|
|
429
|
+
},
|
|
430
|
+
output: {
|
|
431
|
+
schema: { type: 'object' },
|
|
432
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
433
|
+
},
|
|
434
|
+
async execute(args, exec) {
|
|
435
|
+
const plan = planFromArgs(args || {})
|
|
436
|
+
if (!plan.title) throw new Error('figure_title 为必填项——先说明这张图要表达什么。')
|
|
437
|
+
if (plan.requiresStatistics && !plan.statisticsNote) {
|
|
438
|
+
throw new Error('requires_statistics=true 时必须提供 statistics_note(n、误差线、检验与多重比较)。')
|
|
439
|
+
}
|
|
440
|
+
const plans = loadFigurePlans()
|
|
441
|
+
const id = `figplan-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
|
442
|
+
const { ref } = scopeRefOf(exec)
|
|
443
|
+
const attribution = attributionOf(exec, ref)
|
|
444
|
+
plans[id] = { id, ...plan, ...attribution, status: 'planned', figureId: null, createdAt: Date.now(), updatedAt: Date.now() }
|
|
445
|
+
saveFigurePlans(plans)
|
|
446
|
+
if (opts.mirror) opts.mirror('figure-plans.json', JSON.stringify(plans, null, 2), exec)
|
|
447
|
+
return {
|
|
448
|
+
ok: true,
|
|
449
|
+
planId: id,
|
|
450
|
+
plan: plans[id],
|
|
451
|
+
profile: JOURNAL_PROFILES[plan.targetJournal],
|
|
452
|
+
next: `完成绘图后调用 sci_figure_register plan_id=${id},再调用 sci_figure_audit。`,
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
})
|
|
456
|
+
|
|
457
|
+
ctx.tools.register({
|
|
458
|
+
name: 'sci_figure_register',
|
|
459
|
+
description:
|
|
460
|
+
'登记一张已生成的科研图件(绘图后必须调用)。推荐先用 sci_figure_plan 获得 plan_id;登记支持 PNG/JPEG/SVG/GIF/WebP/TIFF/PDF,校验扩展名与文件头;SVG 必须纯静态。登记只是形成档案,不等于通过投稿前检,随后必须调用 sci_figure_audit。',
|
|
461
|
+
parameters: {
|
|
462
|
+
path: { type: 'string', required: true },
|
|
463
|
+
figure_title: { type: 'string', description: '图表标题' },
|
|
464
|
+
code_path: { type: 'string', description: '生成该图的代码文件路径' },
|
|
465
|
+
dpi: { type: 'number' },
|
|
466
|
+
figure_note: { type: 'string', description: '备注' },
|
|
467
|
+
result_id: { type: 'string', description: '文章蓝图 result id(res-N);提供时图表自动挂为该 result 的证据' },
|
|
468
|
+
plan_id: { type: 'string', description: 'sci_figure_plan 返回的计划 id' },
|
|
469
|
+
source_data_paths: { type: 'array', description: '兼容无计划登记时补充源数据路径' },
|
|
470
|
+
},
|
|
471
|
+
output: {
|
|
472
|
+
schema: { type: 'object' },
|
|
473
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
474
|
+
},
|
|
475
|
+
async execute(args, exec) {
|
|
476
|
+
if (!existsSync(args.path)) throw new Error(`图片文件不存在: ${args.path}`)
|
|
477
|
+
const stat = statSync(args.path)
|
|
478
|
+
const buf = readFileSync(args.path)
|
|
479
|
+
// B1(v0.10.0):登记前校验图片格式(扩展名白名单 + magic bytes),不符即拒绝
|
|
480
|
+
const imgCheck = validateImageFile(args.path, buf)
|
|
481
|
+
if (!imgCheck.ok) throw new Error(imgCheck.error)
|
|
482
|
+
const figures = loadFigures()
|
|
483
|
+
const plans = loadFigurePlans()
|
|
484
|
+
const { ref } = scopeRefOf(exec)
|
|
485
|
+
const attribution = attributionOf(exec, ref)
|
|
486
|
+
const recordScope = createRecordScopeResolver({ store })
|
|
487
|
+
const ownedByCurrentProject = (record) => (ref ? recordScope.inScope(record, ref) : false)
|
|
488
|
+
const planId = args.plan_id ? String(args.plan_id).trim() : null
|
|
489
|
+
const planRecord = planId ? plans[planId] : null
|
|
490
|
+
if (planId && !planRecord) throw new Error(`图件计划不存在: ${planId}。先调用 sci_figure_plan,或去掉 plan_id 作为遗留图件登记。`)
|
|
491
|
+
// 归属明确的跨项目计划不得绑定(无归属的旧计划保留兼容路径,读取侧按 legacy 处理)。
|
|
492
|
+
if (planRecord && ref && (planRecord.projectId || planRecord.rootSessionId) && !ownedByCurrentProject(planRecord)) {
|
|
493
|
+
throw new Error(`图件计划 ${planId} 属于其他项目,不能跨项目绑定。先在本项目重新调用 sci_figure_plan。`)
|
|
494
|
+
}
|
|
495
|
+
const planSnapshot = planRecord ? {
|
|
496
|
+
targetJournal: planRecord.targetJournal,
|
|
497
|
+
targetJournalName: planRecord.targetJournalName,
|
|
498
|
+
submissionStage: planRecord.submissionStage,
|
|
499
|
+
targetWidthMm: planRecord.targetWidthMm,
|
|
500
|
+
figureRole: planRecord.figureRole,
|
|
501
|
+
claim: planRecord.claim,
|
|
502
|
+
requiresStatistics: planRecord.requiresStatistics,
|
|
503
|
+
statisticsNote: planRecord.statisticsNote,
|
|
504
|
+
templateSource: planRecord.templateSource,
|
|
505
|
+
templateVersion: planRecord.templateVersion,
|
|
506
|
+
templateLicense: planRecord.templateLicense,
|
|
507
|
+
} : null
|
|
508
|
+
const sourceDataPaths = planRecord ? textList(planRecord.sourceDataPaths) : textList(args.source_data_paths)
|
|
509
|
+
const id = `fig-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
|
510
|
+
const sha = createHash('sha256').update(buf).digest('hex').slice(0, 12)
|
|
511
|
+
const title = args.figure_title || args.path.split(/[\\/]/).pop()
|
|
512
|
+
// 版本链(v0.9.0):同 path 优先、同标题兜底,取最近登记的一条作前驱。
|
|
513
|
+
// T1:前驱只在当前项目拥有的图件里找——不同项目的同名文件不得互相续版本。
|
|
514
|
+
const all = Object.values(figures).filter((f) => f && typeof f === 'object' && ownedByCurrentProject(f))
|
|
515
|
+
const byPath = all.filter((f) => f && normPath(f.path) === normPath(args.path)).sort((a, b) => (b.registeredAt || 0) - (a.registeredAt || 0))
|
|
516
|
+
const byTitle = args.figure_title ? all.filter((f) => f && f.title === title).sort((a, b) => (b.registeredAt || 0) - (a.registeredAt || 0)) : []
|
|
517
|
+
const prior = byPath[0] || byTitle[0] || null
|
|
518
|
+
if (prior && prior.sha256_12 === sha) {
|
|
519
|
+
// 内容未变时不刷版本;但允许补绑定图件计划、代码/源数据和 Result。
|
|
520
|
+
// 这些元数据决定前检口径,一旦改变就清除旧审计与人工结论,强制重新审计。
|
|
521
|
+
const nextCodePath = args.code_path || prior.codePath
|
|
522
|
+
const nextSources = planRecord || args.source_data_paths ? sourceDataPaths : (prior.sourceDataPaths || [])
|
|
523
|
+
const nextResultId = args.result_id ? String(args.result_id) : prior.resultId
|
|
524
|
+
const previousPlanId = prior.planId || null
|
|
525
|
+
const auditBasisChanged = (planRecord && prior.planId !== planId) ||
|
|
526
|
+
(args.code_path && args.code_path !== prior.codePath) ||
|
|
527
|
+
((planRecord || args.source_data_paths) && JSON.stringify(nextSources) !== JSON.stringify(prior.sourceDataPaths || []))
|
|
528
|
+
const metadataChanged = auditBasisChanged || (args.result_id && nextResultId !== prior.resultId)
|
|
529
|
+
if (metadataChanged) {
|
|
530
|
+
prior.planId = planRecord ? planId : prior.planId
|
|
531
|
+
prior.plan = planRecord ? planSnapshot : prior.plan
|
|
532
|
+
prior.codePath = nextCodePath
|
|
533
|
+
prior.sourceDataPaths = nextSources
|
|
534
|
+
prior.resultId = nextResultId || null
|
|
535
|
+
if (auditBasisChanged) {
|
|
536
|
+
delete prior.audit
|
|
537
|
+
delete prior.manualReview
|
|
538
|
+
}
|
|
539
|
+
prior.updatedAt = Date.now()
|
|
540
|
+
figures[prior.id] = prior
|
|
541
|
+
saveFigures(figures)
|
|
542
|
+
if (opts.mirror) opts.mirror('figures.json', JSON.stringify(figures, null, 2), exec)
|
|
543
|
+
if (planRecord) {
|
|
544
|
+
if (previousPlanId && previousPlanId !== planId && plans[previousPlanId]) {
|
|
545
|
+
plans[previousPlanId] = {
|
|
546
|
+
...plans[previousPlanId], status: 'superseded', supersededBy: planId, updatedAt: Date.now(),
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
plans[planId] = { ...planRecord, status: 'registered', figureId: prior.id, updatedAt: Date.now() }
|
|
550
|
+
saveFigurePlans(plans)
|
|
551
|
+
if (opts.mirror) opts.mirror('figure-plans.json', JSON.stringify(plans, null, 2), exec)
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
let blueprintLink = null
|
|
555
|
+
if (args.result_id) {
|
|
556
|
+
try {
|
|
557
|
+
blueprintLink = linkFigureToResult(ctx, prior.id, args.result_id, { store, exec, mirror: opts.mirror })
|
|
558
|
+
} catch (err) {
|
|
559
|
+
blueprintLink = { error: String(err && err.message) }
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
log(`figure unchanged (sha match): ${prior.id} v${prior.version || 1}`)
|
|
563
|
+
return {
|
|
564
|
+
ok: true,
|
|
565
|
+
figureId: prior.id,
|
|
566
|
+
unchanged: true,
|
|
567
|
+
metadataUpdated: metadataChanged,
|
|
568
|
+
version: prior.version || 1,
|
|
569
|
+
sha256_12: sha,
|
|
570
|
+
planId: prior.planId || null,
|
|
571
|
+
resultId: prior.resultId || null,
|
|
572
|
+
blueprintLink,
|
|
573
|
+
note: auditBasisChanged
|
|
574
|
+
? '文件内容未变,未新建版本;计划/溯源元数据已更新,旧前检结论已清除,请重新运行 sci_figure_audit。'
|
|
575
|
+
: metadataChanged
|
|
576
|
+
? '文件内容未变,未新建版本;Result 关联已更新。'
|
|
577
|
+
: '图片内容与已登记版本完全相同(sha 一致),未新建版本。',
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
const version = prior ? (prior.version || 1) + 1 : 1
|
|
581
|
+
const inheritedAttribution = prior && (prior.projectId || prior.rootSessionId)
|
|
582
|
+
? { projectId: prior.projectId || null, rootSessionId: prior.rootSessionId || null }
|
|
583
|
+
: attribution
|
|
584
|
+
figures[id] = {
|
|
585
|
+
id,
|
|
586
|
+
path: args.path,
|
|
587
|
+
title,
|
|
588
|
+
codePath: args.code_path,
|
|
589
|
+
sourceDataPaths,
|
|
590
|
+
dpi: args.dpi,
|
|
591
|
+
note: args.figure_note,
|
|
592
|
+
planId,
|
|
593
|
+
plan: planSnapshot,
|
|
594
|
+
...inheritedAttribution,
|
|
595
|
+
bytes: stat.size,
|
|
596
|
+
sha256_12: sha,
|
|
597
|
+
// 版本链(v0.9.0):prevId/prevSha 指向同 path/标题的上一登记版本,version 从 1 起递增
|
|
598
|
+
version,
|
|
599
|
+
prevId: prior ? prior.id : null,
|
|
600
|
+
prevSha: prior ? prior.sha256_12 : null,
|
|
601
|
+
// 双向对齐回写(v0.6.0 fix5):result.figures 含 fig-* 之外,figure 对象也记录 resultId
|
|
602
|
+
//(产物 tab 图表卡据此显示 res-N 徽章;挂接失败不回滚此标记,错误经 blueprintLink 回报)
|
|
603
|
+
resultId: args.result_id ? String(args.result_id) : (prior && prior.resultId) || null,
|
|
604
|
+
registeredAt: Date.now(),
|
|
605
|
+
}
|
|
606
|
+
saveFigures(figures)
|
|
607
|
+
if (opts.mirror) opts.mirror('figures.json', JSON.stringify(figures, null, 2), exec)
|
|
608
|
+
if (planRecord) {
|
|
609
|
+
plans[planId] = { ...planRecord, status: 'registered', figureId: id, updatedAt: Date.now() }
|
|
610
|
+
saveFigurePlans(plans)
|
|
611
|
+
if (opts.mirror) opts.mirror('figure-plans.json', JSON.stringify(plans, null, 2), exec)
|
|
612
|
+
}
|
|
613
|
+
// 文章蓝图挂接(v0.6.0):带 result_id 时挂为该 result 的图表证据(失败不阻断登记)
|
|
614
|
+
let blueprintLink = null
|
|
615
|
+
if (args.result_id) {
|
|
616
|
+
try {
|
|
617
|
+
blueprintLink = linkFigureToResult(ctx, id, args.result_id, { store, exec, mirror: opts.mirror })
|
|
618
|
+
} catch (err) {
|
|
619
|
+
log(`blueprint link failed for ${id} → ${args.result_id}: ${err && err.message}`)
|
|
620
|
+
blueprintLink = { error: String(err && err.message) }
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
const out = { ok: true, figureId: id, bytes: stat.size, sha256_12: sha, version, resultId: figures[id].resultId, planId }
|
|
624
|
+
if (prior) {
|
|
625
|
+
out.prevId = prior.id
|
|
626
|
+
out.prevSha = prior.sha256_12 || null
|
|
627
|
+
out.versionNote = `同图新版(v${version}):上一版本 ${prior.id}(sha ${prior.sha256_12}),工作台图表卡可对比。`
|
|
628
|
+
}
|
|
629
|
+
if (blueprintLink) out.blueprintLink = blueprintLink
|
|
630
|
+
return out
|
|
631
|
+
},
|
|
632
|
+
})
|
|
633
|
+
|
|
634
|
+
ctx.tools.register({
|
|
635
|
+
name: 'sci_figure_audit',
|
|
636
|
+
description:
|
|
637
|
+
'对已登记图件执行投稿前检:最终尺寸有效 dpi、格式、代码与源数据、统计说明、模板许可,并列出必须人工检查的字号/拼版/科学完整性。自动状态 ready-for-manual-review 后,只有研究者按最终尺寸实际查看并明确同意,才可传 manual_decision=approved 与 review_note;该批准不代表期刊接收保证。',
|
|
638
|
+
parameters: {
|
|
639
|
+
figure_id: { type: 'string', required: true },
|
|
640
|
+
manual_decision: { type: 'string', description: '可选:approved / rejected / pending;仅记录真实人工审阅结论' },
|
|
641
|
+
review_note: { type: 'string', description: '人工审阅依据;approved/rejected 时必填' },
|
|
642
|
+
},
|
|
643
|
+
output: {
|
|
644
|
+
schema: { type: 'object' },
|
|
645
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
646
|
+
},
|
|
647
|
+
async execute(args, exec) {
|
|
648
|
+
const figures = loadFigures()
|
|
649
|
+
const id = String(args.figure_id || '').trim()
|
|
650
|
+
const record = figures[id]
|
|
651
|
+
if (!record) throw new Error(`图件不存在: ${id || '(空)'}。先用 sci_figure_list 查看。`)
|
|
652
|
+
// T1:归属明确的图件只允许本项目的执行上下文审计(legacy 无归属记录保留兼容路径)。
|
|
653
|
+
if (record.projectId || record.rootSessionId) {
|
|
654
|
+
const { ref } = scopeRefOf(exec)
|
|
655
|
+
const allowed = ref ? createRecordScopeResolver({ store }).inScope(record, ref) : false
|
|
656
|
+
if (!allowed) throw new Error(`图件 ${id} 属于其他项目,不能跨项目审计。先切换到该图件所属项目的会话。`)
|
|
657
|
+
}
|
|
658
|
+
if (!record.path || !existsSync(record.path)) throw new Error(`图件文件不存在: ${record.path || '(未登记路径)'}`)
|
|
659
|
+
const buf = readFileSync(record.path)
|
|
660
|
+
const currentSha = createHash('sha256').update(buf).digest('hex').slice(0, 12)
|
|
661
|
+
if ((record.sha256_12 && currentSha !== record.sha256_12) || (Number.isFinite(record.bytes) && buf.length !== record.bytes)) {
|
|
662
|
+
throw new Error(`图件文件在登记后已改变(登记 sha ${record.sha256_12 || '?'},当前 sha ${currentSha})。先重新调用 sci_figure_register 生成新版本,再审计;旧版本结论不能沿用。`)
|
|
663
|
+
}
|
|
664
|
+
const valid = validateImageFile(record.path, buf)
|
|
665
|
+
if (!valid.ok) throw new Error(valid.error)
|
|
666
|
+
const inspected = inspectFigureBuffer(record.path, buf)
|
|
667
|
+
let audit = auditFigureRecord(record, inspected, { pathExists: existsSync })
|
|
668
|
+
const decision = args.manual_decision ? String(args.manual_decision).trim().toLowerCase() : ''
|
|
669
|
+
if (decision) {
|
|
670
|
+
if (!['approved', 'rejected', 'pending'].includes(decision)) throw new Error('manual_decision 仅允许 approved / rejected / pending。')
|
|
671
|
+
const note = String(args.review_note || '').trim()
|
|
672
|
+
if ((decision === 'approved' || decision === 'rejected') && note.length < 10) {
|
|
673
|
+
throw new Error('人工批准/拒绝必须提供至少 10 个字符的 review_note,记录最终尺寸与主要检查依据。')
|
|
674
|
+
}
|
|
675
|
+
if (decision === 'approved' && audit.automaticStatus !== 'ready-for-manual-review') {
|
|
676
|
+
throw new Error(`自动前检状态为 ${audit.automaticStatus},不能批准。先处理 fail/warn 并重新审计。`)
|
|
677
|
+
}
|
|
678
|
+
record.manualReview = { decision, note, reviewedAt: Date.now() }
|
|
679
|
+
audit = auditFigureRecord(record, inspected, { pathExists: existsSync })
|
|
680
|
+
}
|
|
681
|
+
record.audit = audit
|
|
682
|
+
record.updatedAt = Date.now()
|
|
683
|
+
figures[id] = record
|
|
684
|
+
saveFigures(figures)
|
|
685
|
+
if (opts.mirror) opts.mirror('figures.json', JSON.stringify(figures, null, 2), exec)
|
|
686
|
+
const plans = loadFigurePlans()
|
|
687
|
+
if (record.planId && plans[record.planId]) {
|
|
688
|
+
plans[record.planId] = { ...plans[record.planId], status: audit.overallStatus, updatedAt: Date.now() }
|
|
689
|
+
saveFigurePlans(plans)
|
|
690
|
+
if (opts.mirror) opts.mirror('figure-plans.json', JSON.stringify(plans, null, 2), exec)
|
|
691
|
+
}
|
|
692
|
+
return { ok: true, figureId: id, audit }
|
|
693
|
+
},
|
|
694
|
+
})
|
|
695
|
+
|
|
696
|
+
ctx.tools.register({
|
|
697
|
+
name: 'sci_figure_list',
|
|
698
|
+
description: '列出已登记的科研图表(最新的在前)。参数:limit?(默认 20)。',
|
|
699
|
+
parameters: { limit: { type: 'number' } },
|
|
700
|
+
output: {
|
|
701
|
+
schema: { type: 'object' },
|
|
702
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
|
|
703
|
+
},
|
|
704
|
+
async execute(args, exec) {
|
|
705
|
+
const { ref, snapshot } = scopeRefOf(exec)
|
|
706
|
+
const figures = Object.values(loadFigures()).filter((f) => f && typeof f === 'object')
|
|
707
|
+
// T1:图件列表是项目视图——只返回本项目拥有的图件;历史无归属条目只有能被当前
|
|
708
|
+
// 项目快照的稳定链接(result.figures / links.artifactRefs)唯一确定时才显示。
|
|
709
|
+
let visible = figures
|
|
710
|
+
if (ref) {
|
|
711
|
+
const recordScope = createRecordScopeResolver({ store })
|
|
712
|
+
const linkedIds = new Set()
|
|
713
|
+
const results = snapshot && snapshot.paper && Array.isArray(snapshot.paper.results) ? snapshot.paper.results : []
|
|
714
|
+
for (const result of results) {
|
|
715
|
+
for (const fid of Array.isArray(result && result.figures) ? result.figures : []) linkedIds.add(String(fid))
|
|
716
|
+
}
|
|
717
|
+
const links = snapshot && snapshot.links && Array.isArray(snapshot.links.artifactRefs) ? snapshot.links.artifactRefs : []
|
|
718
|
+
for (const link of links) if (link && link.artifactId) linkedIds.add(String(link.artifactId))
|
|
719
|
+
visible = figures.filter((f) => recordScope.inScope(f, ref) || (f.id && linkedIds.has(String(f.id))))
|
|
720
|
+
} else {
|
|
721
|
+
visible = []
|
|
722
|
+
}
|
|
723
|
+
visible.sort((a, b) => (b.registeredAt || 0) - (a.registeredAt || 0))
|
|
724
|
+
return {
|
|
725
|
+
figures: visible.slice(0, Math.min(args.limit || 20, 100)),
|
|
726
|
+
total: visible.length,
|
|
727
|
+
}
|
|
728
|
+
},
|
|
729
|
+
})
|
|
730
|
+
|
|
731
|
+
log('figure tools registered (sci_figure_plan / sci_figure_register / sci_figure_audit / sci_figure_list)')
|
|
732
|
+
}
|