dsh-science-plugin 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -2
  3. package/agents/_README.md +5 -0
  4. package/agents/analyst.md +27 -0
  5. package/agents/figure-expert.md +35 -0
  6. package/agents/literature-scout.md +32 -0
  7. package/agents/presentation.md +78 -0
  8. package/agents/reviewer.md +32 -0
  9. package/agents/simulator.md +30 -0
  10. package/agents/topic-designer.md +26 -0
  11. package/agents/trainer.md +36 -0
  12. package/agents/writer.md +44 -0
  13. package/assets/mascots/analyst.svg +33 -0
  14. package/assets/mascots/designer.svg +33 -0
  15. package/assets/mascots/figure.svg +35 -0
  16. package/assets/mascots/idle.svg +9 -0
  17. package/assets/mascots/lead.svg +33 -0
  18. package/assets/mascots/presentation.svg +40 -0
  19. package/assets/mascots/reviewer.svg +31 -0
  20. package/assets/mascots/scout.svg +31 -0
  21. package/assets/mascots/simulator.svg +33 -0
  22. package/assets/mascots/thinking.svg +23 -0
  23. package/assets/mascots/trainer.svg +32 -0
  24. package/assets/mascots/working.svg +9 -0
  25. package/assets/mascots/writer.svg +33 -0
  26. package/client/client.js +3425 -0
  27. package/client/client.js.map +7 -0
  28. package/cordis.patch.yml +12 -0
  29. package/docs/DEVLOG.md +864 -0
  30. package/docs/SPEC.md +452 -0
  31. package/docs/recipes/agent-teams-science.md +46 -0
  32. package/docs/research/2026-11-12-academic-figure-skill-/350/257/204/344/274/260.md +33 -0
  33. package/docs/research/2026-11-12-/347/224/237/347/211/251/347/247/221/347/240/224/350/203/275/345/212/233/344/270/216/345/267/245/344/275/234/345/217/260/351/233/206/346/210/220/350/260/203/347/240/224.md +169 -0
  34. package/docs/research/2026-11-12-/347/247/221/347/240/224/347/273/230/345/233/276/345/274/200/346/272/220/346/226/271/346/241/210/350/260/203/347/240/224.md +52 -0
  35. package/docs/research/2026-11-13-/345/257/271/350/257/235/351/251/261/345/212/250/347/247/221/347/240/224/345/267/245/344/275/234/345/217/260/344/272/247/345/223/201/347/255/226/347/225/245/350/260/203/347/240/224.md +319 -0
  36. package/docs/research/2026-11-13-/350/267/257/347/272/277B/346/212/200/346/234/257/345/217/257/350/241/214/346/200/247/344/270/216/344/275/216/347/274/272/351/231/267/350/256/276/350/256/241/350/260/203/347/240/224.md +65 -0
  37. package/docs/superpowers/specs/2026-11-12-/347/247/221/347/240/224/345/267/245/344/275/234/345/217/260/351/207/215/346/236/204/350/256/276/350/256/241.md +364 -0
  38. package/docs/superpowers/specs/2026-11-13-/345/257/271/350/257/235/344/274/230/345/205/210/347/247/221/347/240/224/345/215/241/347/211/207/345/267/245/344/275/234/345/217/260/351/207/215/346/236/204/350/256/276/350/256/241.md +607 -0
  39. package/icon.svg +6 -0
  40. package/lib/action-cards.js +194 -0
  41. package/lib/artifact-index.js +131 -0
  42. package/lib/blueprint.js +1487 -0
  43. package/lib/dag.js +69 -0
  44. package/lib/db.js +386 -0
  45. package/lib/figureqa.js +290 -0
  46. package/lib/figures.js +732 -0
  47. package/lib/httpdata-auth.js +91 -0
  48. package/lib/httpdata.js +862 -0
  49. package/lib/index.js +329 -0
  50. package/lib/lit.js +100 -0
  51. package/lib/paperspine.js +287 -0
  52. package/lib/project-adapter.js +259 -0
  53. package/lib/project-catalog.js +227 -0
  54. package/lib/project-context.js +282 -0
  55. package/lib/project-domain.js +849 -0
  56. package/lib/project-remote.js +348 -0
  57. package/lib/project-store.js +653 -0
  58. package/lib/rail-team.js +47 -0
  59. package/lib/resources.js +94 -0
  60. package/lib/reviewcov.js +238 -0
  61. package/lib/reviewer.js +638 -0
  62. package/lib/reviewruns.js +95 -0
  63. package/lib/roles.js +41 -0
  64. package/lib/router.js +133 -0
  65. package/lib/skeleton-context.js +181 -0
  66. package/lib/skillmenu.js +993 -0
  67. package/lib/ssh.js +637 -0
  68. package/lib/status.js +138 -0
  69. package/lib/store.js +50 -0
  70. package/lib/team.js +945 -0
  71. package/lib/vendor/ssh2.bundle.cjs +20124 -0
  72. package/lib/workspace-key.js +64 -0
  73. package/locale/en.json +7 -0
  74. package/locale/zh.json +7 -0
  75. package/package.json +71 -6
  76. package/skills/sci-autoresearch/SKILL.md +41 -0
  77. package/skills/sci-figures/SKILL.md +91 -0
  78. package/skills/sci-figures/references/journal-requirements.md +22 -0
  79. package/skills/sci-figures/references/r-figures.md +106 -0
  80. package/skills/sci-figures/scripts/figure_export.py +45 -0
  81. package/skills/sci-figures/scripts/style_presets.py +82 -0
  82. package/skills/sci-hypothesis/SKILL.md +37 -0
  83. package/skills/sci-polish/SKILL.md +28 -0
  84. package/skills/sci-remote-jobs/SKILL.md +48 -0
  85. package/skills/sci-simulation/SKILL.md +70 -0
  86. package/skills/sci-simulation/references/tool-dossiers/_TEMPLATE.md +25 -0
  87. package/skills/sci-simulation/references/tool-dossiers/ase.md +42 -0
  88. package/skills/sci-simulation/references/tool-dossiers/gaussian.md +42 -0
  89. package/skills/sci-simulation/references/tool-dossiers/gromacs.md +37 -0
  90. package/skills/sci-simulation/references/tool-dossiers/lammps.md +34 -0
  91. package/skills/sci-simulation/references/tool-dossiers/quantum-espresso.md +34 -0
  92. package/skills/sci-simulation/references/universal-tool-onboarding.md +117 -0
  93. package/skills/sci-slides/SKILL.md +73 -0
  94. package/skills/sci-slides/scripts/make_deck.py +332 -0
  95. package/skills/sci-writing/SKILL.md +33 -0
@@ -0,0 +1,653 @@
1
+ // dsh-science — 项目状态存储(Project Store,T0.3 spike → 阶段 1 正式 module)
2
+ //
3
+ // 设计真源 §8.4:Node 内置 node:sqlite;库文件 $DSH_HOME/dsh-science/science-state.sqlite;
4
+ // WAL + foreign keys + busy timeout;全部 SQL 预编译参数。
5
+ // 首版表结构按"事件表 + 最新 JSON snapshot"最小集:projects / snapshots / audit_events /
6
+ // idempotency_receipts / outbox / schema_migrations。对象(core/results/claims/evidence)
7
+ // 与确认凭据保存在 snapshot JSON 内,由领域层维护对象 revision——避免过早拆关系表。
8
+ //
9
+ // 唯一写 seam:execute(projectId, command) 在同一个事务里推进 revision、写 snapshot、
10
+ // 审计事件、幂等回执和 outbox;提交后由 outbox 发布(失败不回滚业务事实,重试补发)。
11
+
12
+ import { DatabaseSync } from 'node:sqlite'
13
+ import { mkdirSync } from 'node:fs'
14
+ import { join } from 'node:path'
15
+ import { randomBytes, randomUUID } from 'node:crypto'
16
+ import { dataDirOf } from './store.js'
17
+
18
+ const SCHEMA_VERSION = 1
19
+
20
+ function log(msg) {
21
+ console.log(`[dsh-science project-store] ${msg}`)
22
+ }
23
+
24
+ const WORKSPACE_KEY_RE = /^[a-f0-9]{64}$/
25
+
26
+ export function assertWorkspaceKey(value) {
27
+ const key = String(value || '')
28
+ if (!WORKSPACE_KEY_RE.test(key)) {
29
+ throw new StoreError('invalid-workspace-key', 'workspaceKey 只能由服务端生成,不能由客户端提交')
30
+ }
31
+ return key
32
+ }
33
+
34
+ const MIGRATIONS = [
35
+ {
36
+ version: 1,
37
+ up: `
38
+ CREATE TABLE IF NOT EXISTS projects (
39
+ id TEXT PRIMARY KEY,
40
+ schema_version INTEGER NOT NULL DEFAULT 1,
41
+ title TEXT NOT NULL DEFAULT '',
42
+ primary_root_session_id TEXT NOT NULL,
43
+ bindings TEXT NOT NULL DEFAULT '{}',
44
+ created_at INTEGER NOT NULL,
45
+ updated_at INTEGER NOT NULL
46
+ );
47
+ CREATE TABLE IF NOT EXISTS snapshots (
48
+ project_id TEXT PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE,
49
+ revision INTEGER NOT NULL,
50
+ snapshot TEXT NOT NULL,
51
+ updated_at INTEGER NOT NULL
52
+ );
53
+ CREATE TABLE IF NOT EXISTS audit_events (
54
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
55
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
56
+ revision INTEGER NOT NULL,
57
+ mutation_id TEXT NOT NULL,
58
+ command TEXT NOT NULL,
59
+ payload TEXT NOT NULL,
60
+ actor TEXT NOT NULL,
61
+ created_at INTEGER NOT NULL
62
+ );
63
+ CREATE INDEX IF NOT EXISTS idx_audit_project ON audit_events(project_id, seq);
64
+ CREATE TABLE IF NOT EXISTS idempotency_receipts (
65
+ mutation_id TEXT PRIMARY KEY,
66
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
67
+ receipt TEXT NOT NULL,
68
+ created_at INTEGER NOT NULL
69
+ );
70
+ CREATE TABLE IF NOT EXISTS outbox (
71
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
72
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
73
+ revision INTEGER NOT NULL,
74
+ frame TEXT NOT NULL,
75
+ published_at INTEGER,
76
+ created_at INTEGER NOT NULL
77
+ );
78
+ CREATE INDEX IF NOT EXISTS idx_outbox_pending ON outbox(published_at, id);
79
+ CREATE TABLE IF NOT EXISTS root_bindings (
80
+ root_session_id TEXT PRIMARY KEY,
81
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
82
+ role TEXT NOT NULL DEFAULT 'primary',
83
+ bound_at INTEGER NOT NULL
84
+ );
85
+ CREATE INDEX IF NOT EXISTS idx_bindings_project ON root_bindings(project_id);
86
+ `,
87
+ },
88
+ {
89
+ version: 2,
90
+ up: `
91
+ CREATE TABLE IF NOT EXISTS legacy_imports (
92
+ migration_id TEXT PRIMARY KEY,
93
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
94
+ source TEXT NOT NULL,
95
+ source_hash TEXT NOT NULL,
96
+ backup_path TEXT NOT NULL,
97
+ imported_at INTEGER NOT NULL
98
+ );
99
+ `,
100
+ },
101
+ {
102
+ // H2 修复:幂等回执按 (project_id, mutation_id) 作用域——跨项目同 mutationId 不得串号。
103
+ version: 3,
104
+ up: `
105
+ CREATE TABLE IF NOT EXISTS idempotency_receipts_v3 (
106
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
107
+ mutation_id TEXT NOT NULL,
108
+ receipt TEXT NOT NULL,
109
+ created_at INTEGER NOT NULL,
110
+ PRIMARY KEY (project_id, mutation_id)
111
+ );
112
+ INSERT OR IGNORE INTO idempotency_receipts_v3 (project_id, mutation_id, receipt, created_at)
113
+ SELECT project_id, mutation_id, receipt, created_at FROM idempotency_receipts;
114
+ DROP TABLE idempotency_receipts;
115
+ ALTER TABLE idempotency_receipts_v3 RENAME TO idempotency_receipts;
116
+ `,
117
+ },
118
+ {
119
+ // T7:工作区目录授权键。workspace_key 只由服务端写入;客户端 metadata 不能改它。
120
+ // 无法唯一回填的既有项目保持 legacy-unassigned,不进入任何工作区目录。
121
+ version: 4,
122
+ up: `
123
+ ALTER TABLE projects ADD COLUMN workspace_key TEXT DEFAULT '';
124
+ ALTER TABLE projects ADD COLUMN workspace_status TEXT NOT NULL DEFAULT 'legacy-unassigned';
125
+ CREATE INDEX IF NOT EXISTS idx_projects_workspace ON projects(workspace_status, workspace_key);
126
+ CREATE TABLE IF NOT EXISTS catalog_secret (
127
+ id INTEGER PRIMARY KEY CHECK (id = 1),
128
+ secret TEXT NOT NULL
129
+ );
130
+ `,
131
+ },
132
+ ]
133
+
134
+ export class ProjectStore {
135
+ constructor(db) {
136
+ this.db = db
137
+ this.listeners = new Set() // (frame) => void;outbox 发布时通知
138
+ this.publishing = false // M6 重入守卫
139
+ this.publishCount = 0 // L4 清理计数
140
+ this._inTx = false // L4 嵌套事务防护
141
+ this.faultInjector = null // T3 测试 seam:fn(stage) 可抛错,用于事务故障注入
142
+ this.migrate()
143
+ this.prepareStatements()
144
+ }
145
+
146
+ static open(dshHome = null) {
147
+ const dir = dshHome ? join(dshHome, 'dsh-science') : dataDirOf()
148
+ mkdirSync(dir, { recursive: true })
149
+ const db = new DatabaseSync(join(dir, 'science-state.sqlite'))
150
+ try {
151
+ db.exec('PRAGMA journal_mode = WAL')
152
+ db.exec('PRAGMA foreign_keys = ON')
153
+ db.exec('PRAGMA busy_timeout = 5000')
154
+ return new ProjectStore(db)
155
+ } catch (err) {
156
+ // 打开失败(损坏 DB 等)必须释放文件句柄,否则 Windows 上删除目录会 EPERM
157
+ try { db.close() } catch { /* ignore */ }
158
+ throw err
159
+ }
160
+ }
161
+
162
+ prepareStatements() {
163
+ this.st = {
164
+ getMigration: this.db.prepare('SELECT version FROM schema_migrations'),
165
+ addMigration: null,
166
+ getProject: this.db.prepare('SELECT * FROM projects WHERE id = ?'),
167
+ getProjectByRoot: this.db.prepare(
168
+ `SELECT p.* FROM projects p JOIN root_bindings b ON b.project_id = p.id WHERE b.root_session_id = ?`,
169
+ ),
170
+ getBinding: this.db.prepare('SELECT * FROM root_bindings WHERE root_session_id = ?'),
171
+ insertProject: this.db.prepare(
172
+ 'INSERT INTO projects (id, schema_version, title, primary_root_session_id, bindings, created_at, updated_at, workspace_key, workspace_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
173
+ ),
174
+ assignWorkspace: this.db.prepare(
175
+ `UPDATE projects SET workspace_key = ?, workspace_status = 'assigned', updated_at = ? WHERE id = ? AND workspace_status <> 'assigned'`,
176
+ ),
177
+ listCatalog: this.db.prepare(
178
+ `SELECT id, title, primary_root_session_id, updated_at FROM projects WHERE workspace_status = 'assigned' AND workspace_key = ? ORDER BY updated_at DESC, id ASC`,
179
+ ),
180
+ insertBinding: this.db.prepare(
181
+ 'INSERT OR REPLACE INTO root_bindings (root_session_id, project_id, role, bound_at) VALUES (?, ?, ?, ?)',
182
+ ),
183
+ getSnapshot: this.db.prepare('SELECT * FROM snapshots WHERE project_id = ?'),
184
+ insertSnapshot: this.db.prepare(
185
+ 'INSERT OR REPLACE INTO snapshots (project_id, revision, snapshot, updated_at) VALUES (?, ?, ?, ?)',
186
+ ),
187
+ insertAudit: this.db.prepare(
188
+ 'INSERT INTO audit_events (project_id, revision, mutation_id, command, payload, actor, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
189
+ ),
190
+ getReceipt: this.db.prepare('SELECT * FROM idempotency_receipts WHERE project_id = ? AND mutation_id = ?'),
191
+ insertReceipt: this.db.prepare(
192
+ 'INSERT INTO idempotency_receipts (project_id, mutation_id, receipt, created_at) VALUES (?, ?, ?, ?)',
193
+ ),
194
+ insertOutbox: this.db.prepare(
195
+ 'INSERT INTO outbox (project_id, revision, frame, created_at) VALUES (?, ?, ?, ?)',
196
+ ),
197
+ pendingOutbox: this.db.prepare('SELECT * FROM outbox WHERE published_at IS NULL ORDER BY id ASC LIMIT 100'),
198
+ markPublished: this.db.prepare('UPDATE outbox SET published_at = ? WHERE id = ?'),
199
+ maxOutboxId: this.db.prepare('SELECT MAX(id) AS maxId FROM outbox'),
200
+ insertLegacyImport: this.db.prepare(
201
+ // T3:审计事实用普通 INSERT——同一 migrationId 不得被 REPLACE 覆盖。
202
+ 'INSERT INTO legacy_imports (migration_id, project_id, source, source_hash, backup_path, imported_at) VALUES (?, ?, ?, ?, ?, ?)',
203
+ ),
204
+ getLegacyImport: this.db.prepare('SELECT * FROM legacy_imports WHERE migration_id = ?'),
205
+ updateProjectTitle: this.db.prepare('UPDATE projects SET title = ?, updated_at = ? WHERE id = ?'),
206
+ getBindingAny: this.db.prepare('SELECT * FROM root_bindings WHERE root_session_id = ?'),
207
+ revisionOf: this.db.prepare('SELECT revision FROM snapshots WHERE project_id = ?'),
208
+ }
209
+ this.migrate()
210
+ }
211
+
212
+ // node:sqlite 无 .transaction()(better-sqlite3 API):手动 BEGIN IMMEDIATE/COMMIT/ROLLBACK。
213
+ // IMMEDIATE 取写锁,避免并发写升级死锁;busy_timeout 由 PRAGMA 兜底。
214
+ // L4:嵌套调用显式报错(调用方不得在事务回调里再走 runInTransaction)。
215
+ runInTransaction(fn) {
216
+ if (this._inTx) throw new StoreError('tx-nested', 'runInTransaction 不允许嵌套调用')
217
+ this.db.exec('BEGIN IMMEDIATE')
218
+ this._inTx = true
219
+ try {
220
+ const out = fn()
221
+ this.db.exec('COMMIT')
222
+ return out
223
+ } catch (err) {
224
+ try { this.db.exec('ROLLBACK') } catch (rbErr) {
225
+ log(`ROLLBACK failed: ${rbErr && rbErr.message}`) // 回滚失败记录;连接交由上层 close 重建
226
+ }
227
+ throw err
228
+ } finally {
229
+ this._inTx = false
230
+ }
231
+ }
232
+
233
+ // T3:故障注入 seam(仅测试/诊断使用)。injector(stage) 抛错即模拟对应阶段失败。
234
+ // stage: 'before-command' | 'after-snapshot' | 'at-ledger' | 'after-commit'
235
+ setFaultInjector(injector) {
236
+ this.faultInjector = typeof injector === 'function' ? injector : null
237
+ }
238
+
239
+ injectFault(stage) {
240
+ if (!this.faultInjector) return
241
+ this.faultInjector(stage)
242
+ }
243
+
244
+ migrate() {
245
+ // 迁移先于 prepareStatements:语句全部针对迁移后的表结构。
246
+ this.db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at INTEGER NOT NULL)')
247
+ const applied = new Set(
248
+ this.db.prepare('SELECT version FROM schema_migrations').all().map((r) => Number(r.version)),
249
+ )
250
+ for (const m of MIGRATIONS) {
251
+ if (applied.has(m.version)) continue
252
+ this.runInTransaction(() => {
253
+ this.db.exec(m.up)
254
+ this.db.prepare('INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)').run(m.version, Date.now())
255
+ })
256
+ log(`migration applied: v${m.version}`)
257
+ }
258
+ }
259
+
260
+ // ---- 绑定 ------------------------------------------------------------------
261
+ bindingOfRootSession(rootSessionId) {
262
+ const row = this.st.getProjectByRoot.get(String(rootSessionId))
263
+ if (!row) return null
264
+ return {
265
+ projectId: row.id,
266
+ primaryRootSessionId: row.primary_root_session_id,
267
+ title: row.title,
268
+ role: String(rootSessionId) === row.primary_root_session_id ? 'primary' : 'attached',
269
+ }
270
+ }
271
+
272
+ // 只读项目清单(升级迁移用:判断旧全局台账能否唯一归属到单个 root)。
273
+ listProjects() {
274
+ return this.db.prepare('SELECT id, primary_root_session_id FROM projects ORDER BY created_at ASC').all()
275
+ .map((row) => ({ projectId: row.id, rootSessionId: row.primary_root_session_id }))
276
+ }
277
+
278
+ // T7:授权用 workspaceKey 只存在于 projects 列。set-metadata 与 snapshot JSON 都不能改它。
279
+ projectAuthOf(projectId) {
280
+ const row = this.st.getProject.get(String(projectId))
281
+ if (!row) return null
282
+ return {
283
+ projectId: row.id,
284
+ rootSessionId: row.primary_root_session_id,
285
+ title: row.title,
286
+ workspaceKey: String(row.workspace_key || ''),
287
+ workspaceStatus: String(row.workspace_status || 'legacy-unassigned'),
288
+ updatedAt: Number(row.updated_at) || 0,
289
+ }
290
+ }
291
+
292
+ listProjectAuthRows() {
293
+ return this.db.prepare(
294
+ 'SELECT id, title, primary_root_session_id, workspace_key, workspace_status, updated_at FROM projects ORDER BY created_at ASC',
295
+ ).all().map((row) => ({
296
+ projectId: row.id,
297
+ title: row.title,
298
+ rootSessionId: row.primary_root_session_id,
299
+ workspaceKey: String(row.workspace_key || ''),
300
+ workspaceStatus: String(row.workspace_status || 'legacy-unassigned'),
301
+ updatedAt: Number(row.updated_at) || 0,
302
+ }))
303
+ }
304
+
305
+ catalogSecret() {
306
+ const row = this.db.prepare('SELECT secret FROM catalog_secret WHERE id = 1').get()
307
+ if (row && row.secret) return String(row.secret)
308
+ const secret = randomBytes(32).toString('base64url')
309
+ this.db.prepare('INSERT INTO catalog_secret (id, secret) VALUES (1, ?)').run(secret)
310
+ return secret
311
+ }
312
+
313
+ // 只回填尚未归属的项目。已 assigned 的键不可被覆盖,避免客户端或二次迁移改授权。
314
+ assignWorkspaceKey(projectId, workspaceKey, { now = Date.now() } = {}) {
315
+ const key = assertWorkspaceKey(workspaceKey)
316
+ const row = this.st.getProject.get(String(projectId))
317
+ if (!row) throw new StoreError('project-not-found', `项目 ${projectId} 不存在`)
318
+ if (String(row.workspace_status || '') === 'assigned' && String(row.workspace_key || '')) {
319
+ return { changed: false, workspaceKey: String(row.workspace_key) }
320
+ }
321
+ const result = this.st.assignWorkspace.run(key, now, String(projectId))
322
+ return { changed: Number(result.changes) > 0, workspaceKey: key }
323
+ }
324
+
325
+ listCatalogProjects(workspaceKey) {
326
+ const key = assertWorkspaceKey(workspaceKey)
327
+ return this.st.listCatalog.all(key).map((row) => ({
328
+ projectId: row.id,
329
+ title: row.title,
330
+ rootSessionId: row.primary_root_session_id,
331
+ updatedAt: Number(row.updated_at) || 0,
332
+ }))
333
+ }
334
+
335
+ createProject({ rootSessionId, title = '', workspaceKey = '', now = Date.now() }) {
336
+ const id = `proj-${now.toString(36)}-${randomUUID().slice(0, 8)}`
337
+ const key = workspaceKey ? assertWorkspaceKey(workspaceKey) : ''
338
+ const status = key ? 'assigned' : 'legacy-unassigned'
339
+ this.runInTransaction(() => {
340
+ this.st.insertProject.run(id, SCHEMA_VERSION, String(title), String(rootSessionId), '{}', now, now, key, status)
341
+ this.st.insertBinding.run(String(rootSessionId), id, 'primary', now)
342
+ const snap = emptySnapshot(id, rootSessionId, now)
343
+ if (title) snap.metadata.title = String(title) // 低-1:建项目标题同步进快照(避免首次 execute 空标题回抹)
344
+ this.st.insertSnapshot.run(id, 0, JSON.stringify(snap), now)
345
+ })
346
+ log(`project created: ${id} (root ${rootSessionId})`)
347
+ return id
348
+ }
349
+
350
+ attachRoot(projectId, rootSessionId, { now = Date.now() } = {}) {
351
+ const project = this.st.getProject.get(String(projectId))
352
+ if (!project) throw new StoreError('project-not-found', `项目 ${projectId} 不存在`)
353
+ // M4:禁止静默改绑——已绑定到其他项目的 root 必须显式解绑,不能被 attach 覆盖
354
+ const existing = this.st.getBindingAny.get(String(rootSessionId))
355
+ if (existing && existing.project_id !== String(projectId)) {
356
+ throw new StoreError('binding-conflict', `会话 ${rootSessionId} 已绑定项目 ${existing.project_id},不能改绑到 ${projectId}`)
357
+ }
358
+ this.st.insertBinding.run(String(rootSessionId), String(projectId), 'attached', now)
359
+ }
360
+
361
+ // 轻量 revision 读取(observe 兜底轮询用,避免整包 JSON.parse)
362
+ revisionOf(projectId) {
363
+ const row = this.st.revisionOf.get(String(projectId))
364
+ return row ? Number(row.revision) : null
365
+ }
366
+
367
+ // M4 统一 attach 入口:表 + 审计 + outbox 同事务维护(命令/HTTP 共用)
368
+ attachSessionWithAudit({ projectId, rootSessionId, actor = {}, now = Date.now() }) {
369
+ const pid = String(projectId)
370
+ let out = null
371
+ this.runInTransaction(() => {
372
+ const snapRow = this.st.getSnapshot.get(pid)
373
+ if (!snapRow) throw new StoreError('project-not-found', `项目 ${pid} 不存在`)
374
+ const current = JSON.parse(snapRow.snapshot)
375
+ const existing = this.st.getBindingAny.get(String(rootSessionId))
376
+ if (existing && existing.project_id !== pid) {
377
+ throw new StoreError('binding-conflict', `会话 ${rootSessionId} 已绑定项目 ${existing.project_id},不能改绑`)
378
+ }
379
+ if (existing) {
380
+ out = { kind: 'already-applied', bound: true, projectId: pid }
381
+ return
382
+ }
383
+ this.st.insertBinding.run(String(rootSessionId), pid, 'attached', now)
384
+ if (!current.bindings.attachedRootSessionIds.includes(String(rootSessionId))) {
385
+ current.bindings.attachedRootSessionIds.push(String(rootSessionId))
386
+ }
387
+ const nextRevision = Number(snapRow.revision) + 1
388
+ current.revision = nextRevision
389
+ current.metadata.updatedAt = now
390
+ this.st.insertSnapshot.run(pid, nextRevision, JSON.stringify(current), now)
391
+ this.st.updateProjectTitle.run(String(current.metadata && current.metadata.title || ''), now, pid)
392
+ this.st.insertAudit.run(pid, nextRevision, `attach-${String(rootSessionId).slice(0, 40)}-${now}`, 'project.attach-session', JSON.stringify({ rootSessionId }), JSON.stringify(actor), now)
393
+ this.st.insertOutbox.run(pid, nextRevision, JSON.stringify({ projectId: pid, projectRevision: nextRevision, changedKeys: ['bindings'], operationId: `attach-${now}`, updatedAt: now }), now)
394
+ out = { kind: 'applied', bound: true, projectId: pid, revision: nextRevision }
395
+ })
396
+ this.publishPending()
397
+ return out
398
+ }
399
+
400
+ // ---- 旧数据导入台账(T3:只允许事务内写入)------------------------------------
401
+ // 正式路径由 execute(..., { legacyImport }) 同事务写入;本方法保留给事务内调用/诊断,
402
+ // 普通 INSERT 保证同一 migrationId 不会被覆盖(重复写入会抛 SQLITE 约束错误)。
403
+ recordLegacyImport({ migrationId, projectId, source, sourceHash, backupPath, now = Date.now() }) {
404
+ this.st.insertLegacyImport.run(
405
+ String(migrationId), String(projectId), String(source), String(sourceHash), String(backupPath), now,
406
+ )
407
+ }
408
+
409
+ // ---- 读取 ------------------------------------------------------------------
410
+ snapshotOf(projectId) {
411
+ const row = this.st.getSnapshot.get(String(projectId))
412
+ if (!row) return null
413
+ // M8:行级损坏不静默重建——返回 corrupt 标记,读取方降级为只读恢复提示
414
+ try {
415
+ return { revision: Number(row.revision), snapshot: JSON.parse(row.snapshot), updatedAt: Number(row.updated_at) }
416
+ } catch (err) {
417
+ return { corrupt: true, revision: Number(row.revision), error: `snapshot parse failed: ${err && err.message}` }
418
+ }
419
+ }
420
+
421
+ // ---- 唯一写 seam -------------------------------------------------------------
422
+ // command: { mutationId, expectedRevision, command, payload, actor, source }
423
+ // handler(currentSnapshot) -> { snapshot, changedKeys, objects };抛错则整批回滚。
424
+ // 幂等键按 (projectId, mutationId) 作用域;回执检查在 BEGIN IMMEDIATE 之后(事务内复检),
425
+ // INSERT(非 REPLACE)保证并发同键只有一份回执。
426
+ execute(projectId, command, handler, options = {}) {
427
+ const pid = String(projectId)
428
+ const mutationId = String(command.mutationId || '')
429
+ if (!mutationId) return { kind: 'invalid', reason: 'mutationId 必填(幂等键)' }
430
+ const now = Date.now()
431
+ const ledger = options.legacyImport || null
432
+ if (ledger && String(ledger.projectId) !== pid) {
433
+ return { kind: 'invalid', reason: `迁移台账目标项目不一致(${ledger.projectId} ≠ ${pid})` }
434
+ }
435
+ let result = null
436
+ try {
437
+ this.runInTransaction(() => {
438
+ // H2:幂等检查在事务内(写锁之后),并断言回执属于本项目
439
+ const existing = this.st.getReceipt.get(pid, mutationId)
440
+ if (existing) {
441
+ const receipt = JSON.parse(existing.receipt)
442
+ if (receipt.projectId !== pid) {
443
+ throw new StoreError('mutation-id-scope', `幂等键 ${mutationId} 已被其他项目占用`)
444
+ }
445
+ // T3:旧版本在 commit 之后才写台账,可能留下“有回执、无台账”的异常状态。
446
+ // 同事务一次性 reconcile:补台账,不重放命令、不推进 revision。
447
+ let reconciled = false
448
+ if (ledger) {
449
+ const row = this.st.getLegacyImport.get(String(ledger.migrationId))
450
+ if (!row) {
451
+ this.injectFault('at-ledger')
452
+ this.insertLedgerRow(ledger, now)
453
+ reconciled = true
454
+ } else if (String(row.project_id) !== pid) {
455
+ throw new StoreError('legacy-import-conflict', `该旧数据已导入过其他项目(${row.project_id})`)
456
+ }
457
+ }
458
+ result = { kind: 'already-applied', receipt, ...(reconciled ? { reconciled: true } : {}) }
459
+ return
460
+ }
461
+ // T3:仅有台账、没有回执(部分恢复的异常状态)→ 视为已导入,绝不重复应用。
462
+ if (ledger) {
463
+ const row = this.st.getLegacyImport.get(String(ledger.migrationId))
464
+ if (row) {
465
+ if (String(row.project_id) !== pid) {
466
+ throw new StoreError('legacy-import-conflict', `该旧数据已导入过其他项目(${row.project_id})`)
467
+ }
468
+ result = { kind: 'already-applied', receipt: null, ledgerOnly: true }
469
+ return
470
+ }
471
+ }
472
+ const snapRow = this.st.getSnapshot.get(pid)
473
+ if (!snapRow) throw new StoreError('project-not-found', `项目 ${pid} 不存在`)
474
+ const currentRevision = Number(snapRow.revision)
475
+ if (command.expectedRevision != null && Number(command.expectedRevision) !== currentRevision) {
476
+ throw new StoreError('conflict', `项目 revision 过期(当前 ${currentRevision},请求基于 ${command.expectedRevision})`, { currentRevision })
477
+ }
478
+ let current
479
+ try {
480
+ current = JSON.parse(snapRow.snapshot)
481
+ } catch (err) {
482
+ // M8:行级损坏 → 结构化错误(项目进入只读恢复,绝不静默重建)
483
+ throw new StoreError('snapshot-corrupt', `项目 ${pid} 快照损坏,无法读取(${err && err.message})`)
484
+ }
485
+ this.injectFault('before-command')
486
+ const applied = handler(current, now)
487
+ const nextRevision = currentRevision + 1
488
+ // 快照内嵌 revision 与 updatedAt 由存储层统一维护(领域层只改业务字段)
489
+ applied.snapshot.revision = nextRevision
490
+ if (applied.snapshot.metadata) applied.snapshot.metadata.updatedAt = now
491
+ const snapshotText = JSON.stringify(applied.snapshot)
492
+ this.st.insertSnapshot.run(pid, nextRevision, snapshotText, now)
493
+ // M4:projects 行与 snapshot.metadata.title 保持同步(bindingOfRootSession 不返回 stale title)
494
+ this.st.updateProjectTitle.run(String(applied.snapshot.metadata && applied.snapshot.metadata.title || ''), now, pid)
495
+ this.injectFault('after-snapshot')
496
+ this.st.insertAudit.run(pid, nextRevision, mutationId, String(command.command || ''), JSON.stringify(command.payload ?? {}), JSON.stringify(command.actor ?? {}), now)
497
+ const receipt = {
498
+ mutationId,
499
+ projectId: pid,
500
+ revision: nextRevision,
501
+ command: String(command.command || ''),
502
+ changedKeys: applied.changedKeys || [],
503
+ objects: applied.objects || [],
504
+ appliedAt: now,
505
+ source: String(command.source || 'tool'),
506
+ }
507
+ this.st.insertReceipt.run(pid, mutationId, JSON.stringify(receipt), now)
508
+ const frame = {
509
+ projectId: pid,
510
+ projectRevision: nextRevision,
511
+ changedKeys: applied.changedKeys || [],
512
+ operationId: mutationId,
513
+ updatedAt: now,
514
+ }
515
+ this.st.insertOutbox.run(pid, nextRevision, JSON.stringify(frame), now)
516
+ // T3:legacy 导入台账与命令/审计/回执/outbox 同事务提交。
517
+ if (ledger) {
518
+ this.injectFault('at-ledger')
519
+ this.insertLedgerRow(ledger, now)
520
+ }
521
+ result = { kind: 'applied', receipt, frame }
522
+ })
523
+ } catch (err) {
524
+ if (err instanceof StoreError) {
525
+ const conflictCodes = new Set(['conflict', 'object-conflict'])
526
+ return { kind: conflictCodes.has(err.code) ? 'conflict' : 'invalid', reason: err.message, code: err.code, ...(err.details || {}) }
527
+ }
528
+ throw err
529
+ }
530
+ // 提交后通知:T3 故障注入模拟 outbox 发布失败。业务事实已提交,重试按幂等回执/台账
531
+ // 返回 duplicate,不会重复导入;错误带 committed=true 供调用方区分 partial-success。
532
+ if (result && result.kind === 'applied') {
533
+ try {
534
+ this.injectFault('after-commit')
535
+ } catch (err) {
536
+ err.committed = true
537
+ throw err
538
+ }
539
+ }
540
+ this.publishPending()
541
+ return result
542
+ }
543
+
544
+ insertLedgerRow(ledger, now) {
545
+ this.st.insertLegacyImport.run(
546
+ String(ledger.migrationId),
547
+ String(ledger.projectId),
548
+ String(ledger.source || ''),
549
+ String(ledger.sourceHash || ''),
550
+ String(ledger.backupPath || ''),
551
+ now,
552
+ )
553
+ }
554
+
555
+ // ---- outbox ------------------------------------------------------------------
556
+ // M6:重入守卫——listener 内再次 execute 时,嵌套 publishPending 直接返回,
557
+ // 由外层循环收尾,避免同帧重复投递与无界递归。
558
+ publishPending() {
559
+ if (this.publishing) return
560
+ this.publishing = true
561
+ try {
562
+ const rows = this.st.pendingOutbox.all()
563
+ for (const row of rows) {
564
+ const frame = JSON.parse(row.frame)
565
+ let delivered = 0
566
+ for (const listener of this.listeners) {
567
+ try {
568
+ listener(frame)
569
+ delivered++
570
+ } catch (err) {
571
+ log(`outbox listener failed: ${err && err.message}`) // 单个订阅者失败不影响其余
572
+ }
573
+ }
574
+ // 本地直接投递(同进程订阅者)成功即标记发布;无订阅者时同样标记(跨进程
575
+ // 拉取方以 revision gap 补读 baseline 为准,无需重试);仅投递失败保持待发。
576
+ if (delivered > 0 || this.listeners.size === 0) {
577
+ this.st.markPublished.run(Date.now(), row.id)
578
+ this.publishCount++
579
+ }
580
+ }
581
+ } finally {
582
+ this.publishing = false
583
+ }
584
+ // L3/L4:顺手有界清理(每 64 次发布一次;0 次发布时不触发;失败不影响主流程)
585
+ if (this.publishCount > 0 && this.publishCount % 64 === 0) {
586
+ try { this.pruneOutbox() } catch (err) { log(`outbox prune failed: ${err && err.message}`) }
587
+ }
588
+ }
589
+
590
+ subscribe(listener) {
591
+ this.listeners.add(listener)
592
+ return () => this.listeners.delete(listener)
593
+ }
594
+
595
+ // 有界清理:已发布的 outbox 保留最近 keep 条(L1:整数断言 + 预编译参数化)
596
+ pruneOutbox(keep = 1000) {
597
+ const n = Math.floor(Number(keep))
598
+ const limit = Number.isSafeInteger(n) && n > 0 ? n : 1000
599
+ if (!this.st.pruneOutbox) {
600
+ this.st.pruneOutbox = this.db.prepare('DELETE FROM outbox WHERE published_at IS NOT NULL AND id NOT IN (SELECT id FROM outbox WHERE published_at IS NOT NULL ORDER BY id DESC LIMIT ?)')
601
+ }
602
+ this.st.pruneOutbox.run(limit)
603
+ }
604
+
605
+ close() {
606
+ try { this.db.close() } catch { /* ignore */ }
607
+ }
608
+ }
609
+
610
+ export class StoreError extends Error {
611
+ constructor(code, message, details = null) {
612
+ super(message)
613
+ this.code = code
614
+ this.details = details
615
+ }
616
+ }
617
+
618
+ export function emptyPaperState(now) {
619
+ return {
620
+ question: '',
621
+ scope: '',
622
+ sourceSummary: '',
623
+ questionUpdatedAt: 0,
624
+ stage: 'explore',
625
+ stageNote: '',
626
+ stageUpdatedAt: now,
627
+ core: null,
628
+ results: [],
629
+ narrative: '',
630
+ resultSeq: 0,
631
+ submission: {
632
+ dataCode: { status: 'pending', note: '', updatedAt: 0 },
633
+ ethics: { status: 'pending', note: '', updatedAt: 0 },
634
+ reporting: { status: 'pending', note: '', updatedAt: 0 },
635
+ limitations: { status: 'pending', note: '', updatedAt: 0 },
636
+ },
637
+ }
638
+ }
639
+
640
+ export function emptySnapshot(projectId, rootSessionId, now) {
641
+ return {
642
+ schemaVersion: 2,
643
+ projectId,
644
+ revision: 0,
645
+ metadata: { title: '', workspaceIdentity: '', createdAt: now, updatedAt: now },
646
+ bindings: { primaryRootSessionId: String(rootSessionId), attachedRootSessionIds: [], branch: 'main' },
647
+ paper: emptyPaperState(now),
648
+ focus: { activeResultId: null, nextDecisions: [], blockers: [] },
649
+ links: { taskRefs: [], artifactRefs: [], reviewRefs: [] },
650
+ decisions: { pending: [], confirmedReceipts: [] },
651
+ migration: { sourceHashes: [], migrationIds: [] },
652
+ }
653
+ }