dsh-soul 0.7.2 → 0.8.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.
@@ -26,20 +26,21 @@
26
26
  * 用法:node scripts/verify-e2e-prompt.mjs
27
27
  * 退出码:0 = 通过;1 = 存在失败项。
28
28
  */
29
- import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
29
+ import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
30
30
  import { tmpdir } from 'node:os'
31
31
  import { dirname, join, resolve } from 'node:path'
32
32
  import { fileURLToPath, pathToFileURL } from 'node:url'
33
- import { assertCount } from './lib/skip-report.mjs'
33
+ import { assertCount, skipNote } from './lib/skip-report.mjs'
34
34
  // 内置人设的期望值直接取代码里的同一份数据(它的数据契约另有 verify-config 钉住),
35
35
  // 免得 e2e 里再抄一份「极简主义者 = efficient / less」这类会悄悄漂移的常量。
36
36
  // 「关于你」的字段名单同理取自配置层唯一来源(PROFILE_FIELDS)。
37
37
  import { BUILTIN_PERSONAS } from '../lib/personas.mjs'
38
38
  import { PROFILE_FIELDS } from '../lib/config.mjs'
39
39
 
40
- // 基线运行应跑出的断言数:E 场景 24 项 + F 损坏场景 8 项 + 2 项判断力对照。
41
- // 跑完时校验,防止「脚本加/删用例」与文档口径悄悄脱节。
42
- const EXPECTED_ASSERTIONS = 38
40
+ // 基线运行应跑出的断言数:E 场景 28 项 + F 损坏场景 8 项 + G 变更记录 16 项
41
+ // + H 撤销拒绝路径 3 项 + W 工作区绑定 15 项 + 2 项判断力对照。跑完时校验,
42
+ // 防止「脚本加/删用例」与文档口径悄悄脱节。
43
+ const EXPECTED_ASSERTIONS = 90
43
44
 
44
45
  const HERE = dirname(fileURLToPath(import.meta.url))
45
46
  const PKG_DIR = resolve(HERE, '..')
@@ -59,20 +60,43 @@ function record(name, ok, detail) {
59
60
  // ==================== 假宿主 ====================
60
61
 
61
62
  /** 记录一切被访问的服务名与每次会话注入,供 E13 / E16 断言两条通道都健在。 */
62
- function makeCtx() {
63
+ function makeCtx(agentSpecs) {
63
64
  const state = {
64
- sections: [], // 每次 systemPrompt.section() 的注册
65
+ sections: [], // 每次 systemPrompt.section() 的注册
65
66
  disposals: 0,
66
- routes: new Map(), // path -> handler
67
- services: [], // ctx.get / ctx.inject 索要过的服务名
68
- providers: [], // 已注册的服务(ctx.provide)
69
- injected: [] // 每个活动 agent 收到的注入消息
67
+ routes: new Map(), // path -> handler
68
+ routeKeys: [], // "kind path" 注册序列(重复注册在 register 里直接抛)
69
+ services: [], // ctx.get / ctx.inject 索要过的服务名
70
+ providers: [], // 已注册的服务(ctx.provide)
71
+ injected: [], // 每个活动 agent 收到的注入消息(汇总,E13 用)
72
+ agents: [], // 活动 agent 桩(工作区绑定场景按 id 取)
73
+ injections: new Map() // agent id -> 该会话收到的注入消息
70
74
  }
71
75
 
72
- // 活动 agent 桩:宿主通过 agents.list() 暴露,注入走 agent.inject()
76
+ // 活动 agent 桩:宿主通过 agents.list() 暴露,注入走 agent.inject()。
77
+ //
78
+ // 默认单个**不带 cwd** 的会话(E/F/G/H 场景只需要「有会话可注入」)。工作区绑定场景
79
+ // 传 specs 造多 cwd 的多会话:`cwd` 是字符串时挂上 session.header.cwd,省略则**根本不
80
+ // 挂 session** —— 那正是宿主在诊断装配下的形态,cwdOfAgent 必须容忍它而不是抛错。
81
+ const specs = Array.isArray(agentSpecs) && agentSpecs.length > 0 ? agentSpecs : [{ id: 'fake-agent' }]
82
+ const list = specs.map((spec) => {
83
+ const bucket = []
84
+ state.injections.set(spec.id, bucket)
85
+ const stub = {
86
+ id: spec.id,
87
+ inject(message) {
88
+ bucket.push(message)
89
+ state.injected.push(message)
90
+ }
91
+ }
92
+ if (typeof spec.cwd === 'string') stub.session = { header: { cwd: spec.cwd } }
93
+ return stub
94
+ })
95
+ state.agents = list
96
+
73
97
  const agents = {
74
98
  list() {
75
- return [{ id: 'fake-agent', inject(message) { state.injected.push(message) } }]
99
+ return list
76
100
  }
77
101
  }
78
102
 
@@ -88,8 +112,20 @@ function makeCtx() {
88
112
  }
89
113
 
90
114
  const webServer = {
91
- register({ path, handler }) {
92
- state.routes.set(path, handler)
115
+ // ★ 必须与宿主 dsh-host-webserver 的 register() **同等严格**:宿主对重复的
116
+ // (kind, path) 直接 `throw new Error('webserver: duplicate exact route "' + path + '"')`,
117
+ // 而抛点在 ctx.inject 回调里 ⇒ 一次重复注册会让整个插件装配失败。
118
+ //
119
+ // 桩若用 Map.set 静默覆盖,这条最致命的错误就永远测不出来:后注册的 handler
120
+ // 顶掉前一个,测试里表现成「GET 也会按 POST 处理」之类的怪现象,甚至完全正常。
121
+ // 这里如实抛错,让重复注册在断言里显形。
122
+ register(route) {
123
+ const key = `${route.kind} ${route.path}`
124
+ if (state.routeKeys.includes(key)) {
125
+ throw new Error(`webserver: duplicate ${route.kind} route "${route.path}"`)
126
+ }
127
+ state.routeKeys.push(key)
128
+ state.routes.set(route.path, route.handler)
93
129
  }
94
130
  }
95
131
 
@@ -133,12 +169,14 @@ function makeCtx() {
133
169
  }
134
170
 
135
171
  /** 直接调用捕获到的 HTTP 处理器,避免起真实服务器。 */
136
- async function callRoute(ctx, path, body, method = 'POST') {
172
+ async function callRoute(ctx, path, body, method = 'POST', url = null) {
137
173
  const handler = ctx.state.routes.get(path)
138
174
  if (!handler) throw new Error(`未注册路由 ${path}`)
139
175
  const payload = Buffer.from(JSON.stringify(body ?? {}))
140
176
  const req = {
141
177
  method,
178
+ // url 单独可传:?limit= 这类查询串住在 url 上,与路由 path 无关
179
+ url: url === null ? path : url,
142
180
  async *[Symbol.asyncIterator]() {
143
181
  yield payload
144
182
  }
@@ -160,11 +198,23 @@ async function callRoute(ctx, path, body, method = 'POST') {
160
198
  return captured
161
199
  }
162
200
 
163
- /** 当前生效的 section 文本:始终读**最后一次**注册的 provider(模拟宿主每步求值)。 */
164
- function currentPrompt(ctx) {
201
+ /** 装配上下文的桩:宿主在 diagnostics 装配时不传 agent,`agentWithCwd(null)` 就是那种形态。 */
202
+ function agentWithCwd(cwd) {
203
+ if (typeof cwd !== 'string') return undefined
204
+ return { session: { header: { cwd } } }
205
+ }
206
+
207
+ /**
208
+ * 当前生效的 section 文本:始终读**最后一次**注册的 provider(模拟宿主每步求值)。
209
+ *
210
+ * 必须传装配上下文:0.8.1-b 之后 text provider 会按 `assembly.agent` 的 cwd 解析绑定,
211
+ * 零参调用得到的是「没有会话信息」这条分支(也就是全局配置),那是另一个被测语义 ——
212
+ * 想测「某个会话会拿到什么」就必须把那个会话传进来。
213
+ */
214
+ function currentPrompt(ctx, cwd) {
165
215
  const last = ctx.state.sections[ctx.state.sections.length - 1]
166
216
  if (!last) return '<未注册>'
167
- return last.text()
217
+ return last.text({ agent: agentWithCwd(cwd) })
168
218
  }
169
219
 
170
220
  // ==================== 场景 ====================
@@ -246,6 +296,30 @@ async function scenario(entry) {
246
296
  `${injectedBefore} → ${ctx.state.injected.length}`
247
297
  )
248
298
 
299
+ // 非提示词字段必须是「推导出来的集合」而不是手写清单。
300
+ // 手工白名单已经漏过两次(requireToolConfirmation、historyMaxEntries),
301
+ // 后果是改一次容量参数就向所有活动会话多注入一条「配置已更新」。
302
+ // 这里逐个走真实 HTTP 写路径,断言 section 与注入都不增加。
303
+ for (const [key, value] of [
304
+ ['historyMaxEntries', 500],
305
+ ['requireToolConfirmation', true],
306
+ ['trailEnabled', false],
307
+ ['trailSpeed', 'fast'],
308
+ ['trailWidth', 'thick']
309
+ ]) {
310
+ const sBefore = ctx.state.sections.length
311
+ const iBefore = ctx.state.injected.length
312
+ const saved = await callRoute(ctx, '/api/soul/config', { [key]: value })
313
+ push(
314
+ `E10c 非提示词字段 ${key} 保存后不刷新提示词、不注入会话`,
315
+ saved.status === 200 &&
316
+ (saved.body?.changed || []).includes(key) &&
317
+ ctx.state.sections.length === sBefore &&
318
+ ctx.state.injected.length === iBefore,
319
+ `status=${saved.status} changed=${JSON.stringify(saved.body?.changed)} section ${sBefore}→${ctx.state.sections.length} 注入 ${iBefore}→${ctx.state.injected.length}`
320
+ )
321
+ }
322
+
249
323
  // 校验失败不得改动生效提示词
250
324
  const bad = await callRoute(ctx, '/api/soul/config', { style: '不存在的风格' })
251
325
  push('E11 非法枚举被拒绝(400)', bad.status === 400, JSON.stringify(bad.body))
@@ -505,6 +579,785 @@ async function corruptConfigScenario(entry) {
505
579
  return results
506
580
  }
507
581
 
582
+ // ==================== 变更记录与回滚场景(0.8.0)====================
583
+
584
+ /**
585
+ * 真实挂载 + 真实文件系统跑一遍变更记录:每次提交留痕、撤销、恢复被删预设、清空。
586
+ *
587
+ * 为什么非要在这一层测:路由里的 400 / 405 / 409 是**判定逻辑**,源码文本断言只能证明
588
+ * 「写了这行代码」,证明不了「这条分支真的会触发」。而撤销的核心风险恰恰是分支走错 ——
589
+ * 比如把 diverged 也当成可撤销,用户就会拿到一份从未存在过的混合配置。
590
+ */
591
+ async function historyScenario(entry) {
592
+ const dshHome = mkdtempSync(join(tmpdir(), 'dsh-soul-e2e-history-'))
593
+ const previous = process.env.DSH_HOME
594
+ process.env.DSH_HOME = dshHome
595
+
596
+ const results = []
597
+ const push = (name, ok, detail) => results.push({ name, ok, detail })
598
+ const configFile = join(dshHome, 'soul-config.json')
599
+ const historyFile = join(dshHome, 'soul-config.history.jsonl')
600
+ const mount = async () => {
601
+ const mod = await import(pathToFileURL(entry).href + `?t=${Date.now()}-${Math.random()}`)
602
+ const ctx = makeCtx()
603
+ await mod.apply(ctx)
604
+ return ctx
605
+ }
606
+ const listHistory = async (ctx, limit = null) => {
607
+ const raw = await callRoute(ctx, '/api/soul/history', null, 'GET', limit === null ? null : `/api/soul/history?limit=${limit}`)
608
+ return raw
609
+ }
610
+
611
+ try {
612
+ const ctx = await mount()
613
+
614
+ // ── 留痕:每一次提交都要留下一条,且记清来源 ────────────────────────────────
615
+ await callRoute(ctx, '/api/soul/config', { customInstructions: 'G-甲' })
616
+ await callRoute(ctx, '/api/soul/config', { customInstructions: 'G-乙' })
617
+ await callRoute(ctx, '/api/soul/personas/save', { name: 'G自建' })
618
+ const deleted = await callRoute(ctx, '/api/soul/personas/delete', { name: 'G自建' })
619
+ push('G1 删除预设返回 200', deleted.status === 200 && deleted.body?.ok === true, JSON.stringify(deleted.body).slice(0, 120))
620
+
621
+ push('G2 变更记录文件真的落在配置的兄弟路径上', existsSync(historyFile), historyFile)
622
+
623
+ const all = await listHistory(ctx)
624
+ const entries = all.body?.entries || []
625
+ push(
626
+ 'G3 列表返回 200 且最新在前(时间线顺序由物理顺序决定,不靠时间戳排序)',
627
+ all.status === 200 &&
628
+ all.body?.ok === true &&
629
+ entries.length >= 4 &&
630
+ entries[0].personas.removed.length === 1 &&
631
+ entries[0].personas.removed[0].name === 'G自建',
632
+ JSON.stringify({ 条数: entries.length, 最新来源: entries[0]?.source, 最新动作: entries[0]?.action })
633
+ )
634
+ push(
635
+ 'G4 每条记录都带来源与动作(事后从配置差异里推不出「是谁改的」)',
636
+ entries.every((item) => typeof item.source === 'string' && typeof item.action === 'string') &&
637
+ entries.some((item) => item.source === 'web' && item.action === 'deletePreset'),
638
+ JSON.stringify(entries.map((item) => `${item.source}/${item.action}`))
639
+ )
640
+ push(
641
+ 'G5 记录带链式指纹(配置哈希),否则撤销无法判断「当前状态是否还是当初那条链」',
642
+ entries.every((item) => /^[0-9a-f]{64}$/.test(item.configHash)),
643
+ JSON.stringify(entries[0]?.configHash)
644
+ )
645
+
646
+ const limited = await listHistory(ctx, 1)
647
+ push(
648
+ 'G6 ?limit= 只削本次返回的条数,max 仍是容量上限(两种含义不能混)',
649
+ limited.body?.entries?.length === 1 && limited.body.entries[0].id === entries[0].id && limited.body.max === 200,
650
+ JSON.stringify({ 返回: limited.body?.entries?.length, max: limited.body?.max })
651
+ )
652
+
653
+ // ── 方法校验:写路由不能接受 GET ───────────────────────────────────────────
654
+ const listWrongMethod = await callRoute(ctx, '/api/soul/history', null, 'POST')
655
+ const rollbackWrongMethod = await callRoute(ctx, '/api/soul/history/rollback', null, 'GET')
656
+ push(
657
+ 'G7 四条路由的 method 判定真的生效(POST 列表 / GET 撤销都必须 405,而不是执行写入)',
658
+ listWrongMethod.status === 405 && rollbackWrongMethod.status === 405,
659
+ `列表 POST=${listWrongMethod.status} 撤销 GET=${rollbackWrongMethod.status}`
660
+ )
661
+
662
+ // ── 撤销:回到目标条目**发生之前** ──────────────────────────────────────────
663
+ const oldest = entries[entries.length - 1]
664
+ const rolled = await callRoute(ctx, '/api/soul/history/rollback', { id: oldest.id })
665
+ push(
666
+ 'G8 撤销到最早一条:配置回到那次改动之前(customInstructions 复原为默认空串)',
667
+ rolled.status === 200 && rolled.body?.config?.customInstructions === '',
668
+ JSON.stringify({ status: rolled.status, customInstructions: rolled.body?.config?.customInstructions })
669
+ )
670
+ push(
671
+ 'G9 撤销如实回报撤销了哪些条目(reversed 含目标条目自身)',
672
+ Array.isArray(rolled.body?.reversed) && rolled.body.reversed.includes(oldest.id),
673
+ JSON.stringify(rolled.body?.reversed)
674
+ )
675
+ const afterRollback = await listHistory(ctx)
676
+ const newest = (afterRollback.body?.entries || [])[0]
677
+ push(
678
+ 'G10 撤销动作自己也会留一条记录(时间线成链,撤销可被再撤销)',
679
+ newest?.source === 'rollback' && newest?.action === 'rollback' && newest?.id !== oldest.id,
680
+ JSON.stringify({ source: newest?.source, action: newest?.action })
681
+ )
682
+
683
+ const missing = await callRoute(ctx, '/api/soul/history/rollback', { id: 'zzzzzzzz-abcdef' })
684
+ push(
685
+ 'G11 找不到的 id 回 400(而不是静默成功让用户以为撤销生效了)',
686
+ missing.status === 400 && missing.body?.ok === false,
687
+ JSON.stringify({ status: missing.status, error: missing.body?.error })
688
+ )
689
+
690
+ // ── 恢复预设:绝不静默覆盖同名 ─────────────────────────────────────────────
691
+ const restore = await callRoute(ctx, '/api/soul/history/restore-persona', { id: entries[0].id })
692
+ const personasAfter = await callRoute(ctx, '/api/soul/personas', null, 'GET')
693
+ push(
694
+ 'G12 从「删除预设」的记录里恢复预设,条目内容逐字段还原',
695
+ restore.status === 200 &&
696
+ Array.isArray(restore.body?.restored) &&
697
+ restore.body.restored.includes('G自建') &&
698
+ Object.prototype.hasOwnProperty.call(personasAfter.body?.personas, 'G自建'),
699
+ JSON.stringify({ status: restore.status, restored: restore.body?.restored, skipped: restore.body?.skipped })
700
+ )
701
+
702
+ const restoreAgain = await callRoute(ctx, '/api/soul/history/restore-persona', { id: entries[0].id })
703
+ push(
704
+ 'G13 同名预设已存在时拒绝恢复(400)—— 删掉后又新建同名条目,恢复不能把它悄悄覆盖掉',
705
+ restoreAgain.status === 400 &&
706
+ (restoreAgain.body?.error || '').includes('G自建'),
707
+ JSON.stringify({ status: restoreAgain.status, error: restoreAgain.body?.error })
708
+ )
709
+
710
+ const noRemoved = await callRoute(ctx, '/api/soul/history/restore-persona', { id: oldest.id })
711
+ push(
712
+ 'G14 对「没有删除预设」的记录恢复预设回 400(不返回空成功)',
713
+ noRemoved.status === 400,
714
+ JSON.stringify({ status: noRemoved.status, error: noRemoved.body?.error })
715
+ )
716
+
717
+ // ── 记录文件是不可信输入:手改出来的怪条目不能崩,也不能静默吞掉 ────────────
718
+ // 追加一条**手工伪造**的记录:里面有个只有空白的预设名。它骗得过
719
+ // normalizePersonaEvents(只看「非空且不超长」),但过不了 sanitizePersonaName ——
720
+ // 这正是「读侧再校验一遍」存在的理由。要求:既不崩,也要如实报进 skipped。
721
+ {
722
+ const forged = {
723
+ v: 1,
724
+ id: 'forged0001-abcdef',
725
+ at: new Date().toISOString(),
726
+ source: 'web',
727
+ action: 'deletePreset',
728
+ configHash: 'a'.repeat(64),
729
+ before: { nickname: '' },
730
+ after: { nickname: 'x' },
731
+ personas: { added: [], updated: [], removed: [{ name: ' ', entry: { style: 'roasted' } }, { name: 'G伪造', entry: { style: 'casual' } }] }
732
+ }
733
+ appendFileSync(historyFile, `${JSON.stringify(forged)}\n`, 'utf8')
734
+
735
+ const forgedResult = await callRoute(ctx, '/api/soul/history/restore-persona', { id: 'forged0001-abcdef' })
736
+ push(
737
+ 'G16 手改出来的记录:空白名报进 skipped,合法名照常恢复(读侧二次校验,既不崩也不吞)',
738
+ forgedResult.status === 200 &&
739
+ forgedResult.body?.restored?.includes('G伪造') &&
740
+ (forgedResult.body?.skipped || []).some((item) => item.reason === 'invalid-name'),
741
+ JSON.stringify({ status: forgedResult.status, restored: forgedResult.body?.restored, skipped: forgedResult.body?.skipped })
742
+ )
743
+ }
744
+
745
+ // ── 清空:隐私出口 ────────────────────────────────────────────────────────
746
+ const cleared = await callRoute(ctx, '/api/soul/history/clear')
747
+ const afterClear = await listHistory(ctx)
748
+ push(
749
+ 'G15 清空回报删掉的条数,并且真的清干净(记录里有昵称 / 介绍原文,这是隐私出口)',
750
+ cleared.status === 200 && cleared.body?.removed > 0 && afterClear.body?.entries?.length === 0,
751
+ JSON.stringify({ removed: cleared.body?.removed, 剩余: afterClear.body?.entries?.length })
752
+ )
753
+ } finally {
754
+ if (previous === undefined) delete process.env.DSH_HOME
755
+ else process.env.DSH_HOME = previous
756
+ rmSync(dshHome, { recursive: true, force: true })
757
+ }
758
+
759
+ return results
760
+ }
761
+
762
+ /**
763
+ * 手改配置后撤销必须被拒(409 diverged)。
764
+ *
765
+ * 单独一个场景的原因:diverged 的前提是「进程外的改动」,只能靠**重新挂载**来复现 ——
766
+ * 进程内所有写路径都走同一漏斗、都会留痕,链永远不会断。这也正是它的现实来源:
767
+ * 用户手改了 soul-config.json 之后重启 DSH。
768
+ */
769
+ async function historyDivergedScenario(entry) {
770
+ const dshHome = mkdtempSync(join(tmpdir(), 'dsh-soul-e2e-diverged-'))
771
+ const previous = process.env.DSH_HOME
772
+ process.env.DSH_HOME = dshHome
773
+ const configFile = join(dshHome, 'soul-config.json')
774
+
775
+ const results = []
776
+ const push = (name, ok, detail) => results.push({ name, ok, detail })
777
+ const mount = async () => {
778
+ const mod = await import(pathToFileURL(entry).href + `?t=${Date.now()}-${Math.random()}`)
779
+ const ctx = makeCtx()
780
+ await mod.apply(ctx)
781
+ return ctx
782
+ }
783
+
784
+ try {
785
+ const first = await mount()
786
+ await callRoute(first, '/api/soul/config', { customInstructions: '原始值' })
787
+ const record = (await callRoute(first, '/api/soul/history', null, 'GET')).body?.entries?.[0]
788
+ push('H1 预置一条可撤销的记录', typeof record?.id === 'string', JSON.stringify(record?.id))
789
+
790
+ // 进程外改坏链条:直接改磁盘上的配置(模拟用户手工编辑 / 别的工具写入)
791
+ const onDisk = JSON.parse(readFileSync(configFile, 'utf8'))
792
+ writeFileSync(configFile, JSON.stringify({ ...onDisk, customInstructions: '手工改的' }, null, 2), 'utf8')
793
+
794
+ const second = await mount()
795
+ const diverged = await callRoute(second, '/api/soul/history/rollback', { id: record.id })
796
+ push(
797
+ 'H2 配置被进程外改动后撤销回 409,而不是算出一份从未存在过的混合配置',
798
+ diverged.status === 409 && diverged.body?.ok === false,
799
+ JSON.stringify({ status: diverged.status, error: diverged.body?.error })
800
+ )
801
+ push(
802
+ 'H3 被拒的撤销没有改动配置(拒绝就是拒绝,不留半截写入)',
803
+ JSON.parse(readFileSync(configFile, 'utf8')).customInstructions === '手工改的',
804
+ readFileSync(configFile, 'utf8').slice(0, 80)
805
+ )
806
+ } finally {
807
+ if (previous === undefined) delete process.env.DSH_HOME
808
+ else process.env.DSH_HOME = previous
809
+ rmSync(dshHome, { recursive: true, force: true })
810
+ }
811
+
812
+ return results
813
+ }
814
+
815
+ // ==================== 工作区绑定场景(0.8.1-b)====================
816
+
817
+ /**
818
+ * 同一进程里多个不同 cwd 的会话:目录绑定必须**各自解析**,且两条通道口径一致。
819
+ *
820
+ * 为什么非要端到端测:绑定层的纯函数(前缀匹配、最长前缀、边界判定)已由
821
+ * verify-bindings 单独钉住,但「解析结果真的到达了会话」是另一回事 —— 中间还隔着
822
+ * configForCwd 的合成语义、text provider 的**同步**约束、以及注入通道的逐 agent 编译。
823
+ * 这三处任何一处接错,症状都是「绑定看起来生效了、其实全都在用全局配置」,或者更糟:
824
+ * A 项目的人设进了 B 项目的会话。纯函数层的断言对这两件事一无所知。
825
+ *
826
+ * 绑定表必须在挂载**之前**落盘:loadBindings() 只在 apply() 启动时读一次
827
+ * (读盘不能放在装配路径上 —— text provider 必须是同步的)。
828
+ */
829
+ async function workspaceBindingScenario(entry) {
830
+ const dshHome = mkdtempSync(join(tmpdir(), 'dsh-soul-e2e-workspace-'))
831
+ const previous = process.env.DSH_HOME
832
+ process.env.DSH_HOME = dshHome
833
+
834
+ const results = []
835
+ const push = (name, ok, detail) => results.push({ name, ok, detail })
836
+
837
+ // 目录键用**真实存在**的目录。loadBindings() 会对每条键算一次 realpath 身份键;
838
+ // 路径不存在时它刻意回落到规范化形态而不报错,但那样身份键恒等于展示键,
839
+ // 「两个键集合」这条设计就一点都没被覆盖到。
840
+ const dirA = mkdtempSync(join(tmpdir(), 'dsh-soul-ws-A-'))
841
+ const dirB = mkdtempSync(join(tmpdir(), 'dsh-soul-ws-B-'))
842
+ const subDir = join(dirA, '子模块')
843
+ // 前缀边界:与 dirA 同级、名字以 dirA 结尾的兄弟目录(`D:\项目A` vs `D:\项目AB`)
844
+ const siblingDir = `${dirA}回响`
845
+ const bindingsFile = join(dshHome, 'soul-bindings.json')
846
+
847
+ // 判别字符串取自两个内置人设自己的指令文本 —— 它们彼此完全不同,可当指纹用。
848
+ const ARCH = '以系统设计视角回答'
849
+ const MINIMAL = '只给结论和必要依据'
850
+ const ROAST = '吐槽达人'
851
+
852
+ const injectedText = (id) =>
853
+ (ctxRef.state.injections.get(id) || []).map((m) => m?.content?.[0]?.text || '').join('\n')
854
+
855
+ let ctxRef = null
856
+
857
+ try {
858
+ mkdirSync(subDir, { recursive: true })
859
+ writeFileSync(
860
+ bindingsFile,
861
+ JSON.stringify(
862
+ {
863
+ version: 1,
864
+ bindings: {
865
+ [dirA]: '资深架构师',
866
+ [subDir]: '极简主义者',
867
+ [dirB]: 'W-不存在的人设'
868
+ }
869
+ },
870
+ null,
871
+ 2
872
+ )
873
+ )
874
+
875
+ const mod = await import(pathToFileURL(entry).href + `?t=${Date.now()}`)
876
+ const ctx = makeCtx([
877
+ { id: 'agent-global' }, // 会话头没有 cwd
878
+ { id: 'agent-a', cwd: dirA },
879
+ { id: 'agent-b', cwd: dirB },
880
+ { id: 'agent-sub', cwd: subDir },
881
+ { id: 'agent-sibling', cwd: siblingDir }
882
+ ])
883
+ ctxRef = ctx
884
+ await mod.apply(ctx)
885
+
886
+ // 全局基线:先写入「关于你」与被绑定覆盖的维度。
887
+ // style=roast 是刻意选的 —— 它让「覆盖真的替换了字段」与「只是又追加了一段文本」
888
+ // 产生可观测差别(后者会同时出现吐槽文案与架构师文案,而两者互斥)。
889
+ await callRoute(ctx, '/api/soul/config', { nickname: 'W-昵称', occupation: 'W-职业', style: 'roast' })
890
+
891
+ // 诊断装配形态:宿主在 diagnostics 下可能**整个装配上下文都不传**
892
+ // (runtime-types.d.ts 的注释写明 agent `absent on diagnostics`)。
893
+ const lastSection = ctx.state.sections[ctx.state.sections.length - 1]
894
+ const textNoAssembly = lastSection.text()
895
+
896
+ const globalText = currentPrompt(ctx)
897
+ const textA = currentPrompt(ctx, dirA)
898
+ const textSub = currentPrompt(ctx, subDir)
899
+ const textB = currentPrompt(ctx, dirB)
900
+ const textSibling = currentPrompt(ctx, siblingDir)
901
+
902
+ push(
903
+ 'W1 没有 cwd 的会话(含整个装配上下文缺席)回落全局配置,不抛错也不命中绑定',
904
+ globalText.includes(ROAST) &&
905
+ !globalText.includes(ARCH) &&
906
+ textNoAssembly === globalText,
907
+ JSON.stringify({ 全局含吐槽: globalText.includes(ROAST), 无上下文一致: textNoAssembly === globalText })
908
+ )
909
+ push(
910
+ 'W2 同一进程内不同 cwd 的会话拿到不同的 section 文本(配置不再全局唯一)',
911
+ textA.includes(ARCH) && textSub.includes(MINIMAL) && textA !== textSub,
912
+ JSON.stringify({ a: textA.includes(ARCH), sub: textSub.includes(MINIMAL) })
913
+ )
914
+ push(
915
+ 'W3 最长前缀优先:子目录自己的绑定压过父目录的绑定(不是两条叠加)',
916
+ textSub.includes(MINIMAL) && !textSub.includes(ARCH),
917
+ JSON.stringify(textSub.slice(0, 70))
918
+ )
919
+ push(
920
+ 'W4 前缀匹配落在**路径边界**上:以 dirA 为前缀的兄弟目录不得命中 dirA',
921
+ textSibling === globalText && !textSibling.includes(ARCH),
922
+ JSON.stringify({ 兄弟目录: siblingDir, 命中: textSibling.includes(ARCH) })
923
+ )
924
+ push(
925
+ 'W5 绑定指向已不存在的人设时不生效、回落全局(不自动删除,也不假装命中)',
926
+ textB === globalText && textB.includes(ROAST),
927
+ JSON.stringify({ 等于全局: textB === globalText })
928
+ )
929
+ push(
930
+ 'W6 目录绑定走预设的「部分覆盖」语义:不动「关于你」,且是替换而非追加',
931
+ textA.includes('W-昵称') && textA.includes(ARCH) && !textA.includes(ROAST) && !textA.includes(MINIMAL),
932
+ JSON.stringify({ 昵称在: textA.includes('W-昵称'), 吐槽被替换: !textA.includes(ROAST) })
933
+ )
934
+
935
+ // ── 注入通道:同样的逐会话解析,但走的是另一条路 ──────────────────────────
936
+ const injectedA = injectedText('agent-a')
937
+ const injectedSub = injectedText('agent-sub')
938
+ const injectedB = injectedText('agent-b')
939
+ const injectedGlobal = injectedText('agent-global')
940
+ push(
941
+ 'W7 注入通道也逐会话编译:绑定目录的会话收到该人设,未绑定的收到全局配置',
942
+ injectedA.includes(ARCH) &&
943
+ injectedSub.includes(MINIMAL) &&
944
+ !injectedB.includes(ARCH) &&
945
+ injectedGlobal.includes(ROAST),
946
+ JSON.stringify({
947
+ a: injectedA.includes(ARCH),
948
+ sub: injectedSub.includes(MINIMAL),
949
+ b: injectedB.includes(ARCH)
950
+ })
951
+ )
952
+ push(
953
+ 'W8 两条通道对同一会话给出**逐字节相同**的文本(section 与注入不会各说各话)',
954
+ injectedA.endsWith(textA) && injectedGlobal.endsWith(globalText),
955
+ JSON.stringify({ a: injectedA.endsWith(textA), 全局: injectedGlobal.endsWith(globalText) })
956
+ )
957
+
958
+ const status = await callRoute(ctx, '/api/soul/status', null, 'GET')
959
+ push(
960
+ 'W9 诊断端点如实计数:五个会话各自送达,没有把「算不出来」算成失败',
961
+ status.body?.channels?.injection?.agents === 5 &&
962
+ status.body?.channels?.injection?.delivered === 5 &&
963
+ status.body?.channels?.injection?.failed === 0,
964
+ JSON.stringify(status.body?.channels?.injection)
965
+ )
966
+
967
+ // 全局总开关不属于 PERSONA_FIELDS,任何绑定都覆盖不了它。
968
+ await callRoute(ctx, '/api/soul/config', { enabled: false })
969
+ const offA = currentPrompt(ctx, dirA)
970
+ const offGlobal = currentPrompt(ctx)
971
+ push(
972
+ 'W10 全局总开关仍然说话:enabled=false 时绑定的目录也不会拿到人设',
973
+ offA === '' && offGlobal === '',
974
+ JSON.stringify({ 绑定目录: offA.slice(0, 30), 全局: offGlobal.slice(0, 30) })
975
+ )
976
+ await callRoute(ctx, '/api/soul/config', { enabled: true })
977
+ } finally {
978
+ if (previous === undefined) delete process.env.DSH_HOME
979
+ else process.env.DSH_HOME = previous
980
+ rmSync(dshHome, { recursive: true, force: true })
981
+ rmSync(dirA, { recursive: true, force: true })
982
+ rmSync(dirB, { recursive: true, force: true })
983
+ }
984
+
985
+ return results
986
+ }
987
+
988
+ // ==================== 绑定身份键与降级场景(0.8.1-b)====================
989
+
990
+ /**
991
+ * 绑定表的「两个键集合」与读取失败时的降级,各自需要**不同的磁盘前置状态**:
992
+ * 身份键(realpath)要真有 Junction 才与展示键不同,降级要真有损坏/异常版本的文件。
993
+ * 而绑定表在 apply() 里只读一次,所以每一种前置状态都得重新挂载一次。
994
+ *
995
+ * 为什么不能只靠 lib/bindings.mjs 的纯函数断言:那里实时注入 realpathFn,证明的是
996
+ * 「匹配函数怎么想」;这里证明的是「整条装配链真的把 Junction 认成了同一个目录」——
997
+ * 中间还隔着 normalizeDirPath 的大小写折算、compareTable 的键优先级、以及
998
+ * resolvePersonaForCwd 的失效回落。任何一处接错,两个路径会变成两条互不相干的绑定。
999
+ */
1000
+ async function bindingIdentityScenario(entry) {
1001
+ const dshHome = mkdtempSync(join(tmpdir(), 'dsh-soul-e2e-identity-'))
1002
+ const previous = process.env.DSH_HOME
1003
+ process.env.DSH_HOME = dshHome
1004
+
1005
+ const results = []
1006
+ const push = (name, ok, detail) => results.push({ name, ok, detail })
1007
+ const bindingsFile = join(dshHome, 'soul-bindings.json')
1008
+
1009
+ // 每组前置状态都真的在磁盘上造出来,用**真实存在的目录**:loadBindings() 会对每条键
1010
+ // 算一次 realpath,路径不存在时它刻意回落到规范化形态 —— 那样身份键恒等于展示键,
1011
+ // 「两个键集合」这条设计一点都没被覆盖到。
1012
+ const rootReal = mkdtempSync(join(tmpdir(), 'dsh-soul-id-real-'))
1013
+ const rootLink = mkdtempSync(join(tmpdir(), 'dsh-soul-id-link-'))
1014
+ const realDir = join(rootReal, '真实目录')
1015
+ const linkDir = join(rootLink, '入口目录')
1016
+ mkdirSync(realDir, { recursive: true })
1017
+
1018
+ // 前置条件:Junction 必须真的指向另一个路径。造不出来(权限 / 平台限制)时本条
1019
+ // 就失去了判别力 —— 那必须**如实报出来**,而不是让断言「因为两边本来就是同一个
1020
+ // 目录」而空过。Windows 上 junction 不需要管理员权限,POSIX 上传 'junction' 会
1021
+ // 退化成普通 symlink,两者都能解析。
1022
+ let linkReady = false
1023
+ try {
1024
+ symlinkSync(realDir, linkDir, 'junction')
1025
+ linkReady = realpathSync(linkDir) === realpathSync(realDir)
1026
+ } catch {
1027
+ linkReady = false
1028
+ }
1029
+
1030
+ const ARCH = '以系统设计视角回答'
1031
+ const MINIMAL = '只给结论和必要依据'
1032
+
1033
+ const mount = async (agents) => {
1034
+ const mod = await import(pathToFileURL(entry).href + `?t=${Date.now()}-${Math.random()}`)
1035
+ const ctx = makeCtx(agents)
1036
+ await mod.apply(ctx)
1037
+ return ctx
1038
+ }
1039
+
1040
+ try {
1041
+ if (!linkReady) {
1042
+ // 这是**环境前置**,不是产品断言:受限沙箱 / 系统限制下造不出 junction,
1043
+ // W11–W13 那条断言根本没机会执行。按 skipNote 如实申报「未执行」,
1044
+ // 而不是塞一条永远红的失败项 —— 那会让整链常年红灯,真失败的项反而被淹没。
1045
+ if (!skipNote('verify-e2e-prompt', 1, '无法创建 junction / symlink,W11–W13(链接身份键)未执行', '在可建链接的环境(或非沙箱终端)重跑')) {
1046
+ push('W11 前置条件:Junction 可用(造不出来则 W11–W13 无判别力)', false, '无法创建 junction / symlink')
1047
+ }
1048
+ } else {
1049
+ // ── 展示键优先:身份键不得改写另一条已存在的绑定 ────────────────────────
1050
+ // 两个键各自绑不同人设:入口目录那条(展示键)与真实目录那条。realpath 会把
1051
+ // 入口目录解析成真实目录 —— 若身份键直接覆盖,真实目录的会话就会**静默拿到
1052
+ // 入口目录的人设**,而用户从设置页完全看不出来。
1053
+ writeFileSync(bindingsFile, JSON.stringify({
1054
+ version: 1,
1055
+ bindings: { [linkDir]: '极简主义者', [realDir]: '资深架构师' }
1056
+ }, null, 2))
1057
+ const ctx = await mount([{ id: 'via-link', cwd: linkDir }, { id: 'via-real', cwd: realDir }])
1058
+ const atLink = currentPrompt(ctx, linkDir)
1059
+ const atReal = currentPrompt(ctx, realDir)
1060
+ push(
1061
+ 'W11 会话 cwd 是 Junction 入口时按用户写的那个键命中(展示键优先于身份键)',
1062
+ atLink.includes(MINIMAL) && !atLink.includes(ARCH),
1063
+ JSON.stringify(atLink.slice(0, 60))
1064
+ )
1065
+ push(
1066
+ 'W12 真实路径的会话仍拿到真实路径那条绑定 —— 身份键不得改写已存在的展示键',
1067
+ atReal.includes(ARCH) && !atReal.includes(MINIMAL),
1068
+ JSON.stringify(atReal.slice(0, 60))
1069
+ )
1070
+
1071
+ // ── 身份键的用途:绑定只写在入口、会话从真实路径进来 ─────────────────────
1072
+ // 这是设计里点名的典型失配:cwd 由 Node 的 process.cwd() 给出(规范路径),
1073
+ // 而绑定目录是用户在选择器里点出来的(很可能是 Junction 路径)。
1074
+ writeFileSync(bindingsFile, JSON.stringify({
1075
+ version: 1,
1076
+ bindings: { [linkDir]: '极简主义者' }
1077
+ }, null, 2))
1078
+ const ctx2 = await mount([{ id: 'real-only', cwd: realDir }])
1079
+ const atReal2 = currentPrompt(ctx2, realDir)
1080
+ push(
1081
+ 'W13 绑定只写在 Junction 入口时,从真实路径进来的会话同样命中(身份键存在的理由)',
1082
+ atReal2.includes(MINIMAL),
1083
+ JSON.stringify(atReal2.slice(0, 60))
1084
+ )
1085
+ }
1086
+
1087
+ // ── 降级:绑定文件损坏 / 版本不认识 ───────────────────────────────────────
1088
+ // 绑定是环境事实、不是用户唯一的数据副本,所以读取失败时**以空表继续**而不是
1089
+ // 拒绝启动(与配置损坏时的策略刻意不同)。用户此时看到的是「绑定都没了」,
1090
+ // 但他至少能打开设置页把它们重新绑上 —— 而不是整个插件不激活。
1091
+ writeFileSync(bindingsFile, '{"version": 1, "bindings": {"D:\\\\半截', 'utf8')
1092
+ const ctx3 = await mount([{ id: 'corrupt', cwd: realDir }])
1093
+ const atCorrupt = currentPrompt(ctx3, realDir)
1094
+ push(
1095
+ 'W14 绑定文件损坏时插件照常启动、所有会话回落全局(不抛错),且损坏文件被移开备份',
1096
+ ctx3.state.sections.length === 1 && atCorrupt.length > 0 && !atCorrupt.includes(MINIMAL) &&
1097
+ existsSync(`${bindingsFile}.corrupt`),
1098
+ JSON.stringify({ section: ctx3.state.sections.length, 备份: existsSync(`${bindingsFile}.corrupt`) })
1099
+ )
1100
+
1101
+ writeFileSync(bindingsFile, JSON.stringify({
1102
+ version: 99,
1103
+ bindings: { [realDir]: '极简主义者' }
1104
+ }, null, 2))
1105
+ const ctx4 = await mount([{ id: 'future', cwd: realDir }])
1106
+ const atFuture = currentPrompt(ctx4, realDir)
1107
+ push(
1108
+ 'W15 绑定文件的版本号不认识时整表忽略、回落全局(不按当前语义猜着解析)',
1109
+ atFuture.length > 0 && !atFuture.includes(MINIMAL),
1110
+ JSON.stringify(atFuture.slice(0, 60))
1111
+ )
1112
+ } finally {
1113
+ if (previous === undefined) delete process.env.DSH_HOME
1114
+ else process.env.DSH_HOME = previous
1115
+ rmSync(dshHome, { recursive: true, force: true })
1116
+ rmSync(rootReal, { recursive: true, force: true })
1117
+ rmSync(rootLink, { recursive: true, force: true })
1118
+ }
1119
+
1120
+ return results
1121
+ }
1122
+
1123
+ // ==================== 绑定路由场景(0.8.1-c)====================
1124
+
1125
+ /**
1126
+ * 绑定写路由:方法分派、准入拒绝、**写入即生效**。
1127
+ *
1128
+ * 为什么必须端到端:绑定层的纯函数已由 verify-bindings 钉住、路由的源文本契约
1129
+ * 由 verify-config 钉住,但「写完真的改变了会话里拿到的人设」是第三件事 —— 中间
1130
+ * 隔着独立写队列、缓存重载、以及**必须由路由自己触发的刷新**。绑定不改
1131
+ * soul-config.json,commitConfig 的 promptChanged 门控看不见它(设计 §6.4)。
1132
+ * 接错的症状是「设置页显示绑定成功,会话里却还是全局人设,要重启才生效」,
1133
+ * 而纯函数层与源文本契约对这件事一无所知。
1134
+ *
1135
+ * 另一个只有端到端能覆盖的点:GET 与 POST 共用**一次** register(宿主
1136
+ * dsh-host-webserver 对重复的 (kind, path) 直接抛错,装配会整个失败)。假宿主
1137
+ * 的 register 已与宿主同等严格,故本场景一挂载就会暴露任何重复注册。
1138
+ */
1139
+ async function bindingRoutesScenario(entry) {
1140
+ const dshHome = mkdtempSync(join(tmpdir(), 'dsh-soul-e2e-broutes-'))
1141
+ const previous = process.env.DSH_HOME
1142
+ process.env.DSH_HOME = dshHome
1143
+
1144
+ const results = []
1145
+ const push = (name, ok, detail) => results.push({ name, ok, detail })
1146
+
1147
+ const dirProject = mkdtempSync(join(tmpdir(), 'dsh-soul-br-proj-'))
1148
+ const dirOther = mkdtempSync(join(tmpdir(), 'dsh-soul-br-other-'))
1149
+ const dirThird = mkdtempSync(join(tmpdir(), 'dsh-soul-br-third-'))
1150
+ const subDir = join(dirProject, '子模块')
1151
+ const bindingsFile = join(dshHome, 'soul-bindings.json')
1152
+
1153
+ const ARCH = '以系统设计视角回答'
1154
+ const MINIMAL = '只给结论和必要依据'
1155
+
1156
+ // 刷新是「不 await 的浮动 Promise」(globalUpdatePrompt 里有一次 await loadConfig)。
1157
+ // 注入本体在 refreshPromptAndInject 里是同步跑完的,但 section 重注册要过一次
1158
+ // 微任务,所以断言前统一排空一次。
1159
+ const drain = async (rounds = 8) => {
1160
+ for (let i = 0; i < rounds; i += 1) await new Promise((resolve) => setImmediate(resolve))
1161
+ }
1162
+ const injectedText = (ctx, id) =>
1163
+ (ctx.state.injections.get(id) || []).map((m) => m?.content?.[0]?.text || '').join('\n')
1164
+ const readBindings = () => JSON.parse(readFileSync(bindingsFile, 'utf8')).bindings
1165
+
1166
+ try {
1167
+ mkdirSync(subDir, { recursive: true })
1168
+ // 先落一条绑定:拒绝路径要证明「配置没被写坏」,比较基准得真实存在。
1169
+ writeFileSync(bindingsFile, JSON.stringify({ version: 1, bindings: { [dirOther]: '极简主义者' } }, null, 2))
1170
+ const beforeText = readFileSync(bindingsFile, 'utf8')
1171
+
1172
+ const mod = await import(pathToFileURL(entry).href + `?t=${Date.now()}-${Math.random()}`)
1173
+ const ctx = makeCtx([
1174
+ { id: 'br-proj', cwd: dirProject },
1175
+ { id: 'br-sub', cwd: subDir },
1176
+ { id: 'br-other', cwd: dirOther },
1177
+ { id: 'br-nocwd' }
1178
+ ])
1179
+ await mod.apply(ctx)
1180
+
1181
+ // ── 读 ──────────────────────────────────────────────────────────────
1182
+ const list = await callRoute(ctx, '/api/soul/bindings', null, 'GET')
1183
+ push(
1184
+ 'R1 GET 返回绑定表与活动会话(sessions 由宿主遍历 agents.list() 得出 —— 设置页槽位拿不到 sessionId)',
1185
+ list.status === 200 &&
1186
+ list.body?.ok === true &&
1187
+ Array.isArray(list.body?.sessions) &&
1188
+ list.body.sessions.length === 4 &&
1189
+ typeof list.body?.max === 'number' &&
1190
+ list.body?.bindings?.[dirOther] === '极简主义者',
1191
+ JSON.stringify({ status: list.status, sessions: list.body?.sessions?.length, max: list.body?.max })
1192
+ )
1193
+
1194
+ // ── 方法分派:同一路径注册一次,handler 内按 method 走 ──────────────────
1195
+ const putList = await callRoute(ctx, '/api/soul/bindings', {}, 'PUT')
1196
+ const getDelete = await callRoute(ctx, '/api/soul/bindings/delete', null, 'GET')
1197
+ push(
1198
+ 'R2 两条路由都显式校验方法(PUT 列表 / GET 解绑都回 405,而不是被执行或落到 GET 分支)',
1199
+ putList.status === 405 && getDelete.status === 405,
1200
+ `列表 PUT=${putList.status} 解绑 GET=${getDelete.status}`
1201
+ )
1202
+
1203
+ // ── 准入拒绝:三类理由原样回传,且磁盘一个字节都没动 ────────────────────
1204
+ const relative = await callRoute(ctx, '/api/soul/bindings', { dir: '相对/路径', persona: '极简主义者' })
1205
+ const unknown = await callRoute(ctx, '/api/soul/bindings', { dir: dirProject, persona: '不存在的人设' })
1206
+ push(
1207
+ 'R3 非绝对路径被拒绝(400),理由可直接展示,且绑定文件未被改动',
1208
+ relative.status === 400 &&
1209
+ relative.body?.ok === false &&
1210
+ (relative.body?.error || '').includes('绝对路径') &&
1211
+ readFileSync(bindingsFile, 'utf8') === beforeText,
1212
+ JSON.stringify({ status: relative.status, error: relative.body?.error })
1213
+ )
1214
+ push(
1215
+ 'R4 写入不存在的人设被拒绝(400)—— 允许写入等于让用户对着一个 typo 等永远不来的生效',
1216
+ unknown.status === 400 && (unknown.body?.error || '').includes('不存在的人设'),
1217
+ JSON.stringify({ status: unknown.status, error: unknown.body?.error })
1218
+ )
1219
+
1220
+ // ── 写入即生效 ──────────────────────────────────────────────────────
1221
+ const sectionsBefore = ctx.state.sections.length
1222
+ const created = await callRoute(ctx, '/api/soul/bindings', { dir: dirProject, persona: '资深架构师' })
1223
+ await drain()
1224
+ push(
1225
+ 'R5 合法绑定写入成功,规范化后的键真的落盘',
1226
+ created.status === 200 && readBindings()[dirProject] === '资深架构师',
1227
+ JSON.stringify({ status: created.status, 落盘: readBindings() })
1228
+ )
1229
+ push(
1230
+ 'R6 写入后 section 被重新注册(绑定不改 soul-config.json,promptChanged 门控看不见它)',
1231
+ ctx.state.sections.length > sectionsBefore,
1232
+ `${sectionsBefore} → ${ctx.state.sections.length}`
1233
+ )
1234
+ // ★ 本场景的核心:不重新挂载,活动会话立刻拿到新解析结果。
1235
+ // br-sub 一条绑定都没写,它拿到 ARCH 是因为**父目录绑定被继承** ——
1236
+ // 若注入通道没有逐 agent 编译(而是共用一份全局文本),br-sub 拿不到。
1237
+ const afterProj = injectedText(ctx, 'br-proj')
1238
+ const afterSub = injectedText(ctx, 'br-sub')
1239
+ const afterOther = injectedText(ctx, 'br-other')
1240
+ push(
1241
+ 'R7 绑定写完立即对活动会话生效:本目录与子目录都拿到新的人设,子目录靠继承',
1242
+ afterProj.includes(ARCH) && afterSub.includes(ARCH) && !afterOther.includes(ARCH),
1243
+ JSON.stringify({
1244
+ 本目录: afterProj.includes(ARCH),
1245
+ 子目录: afterSub.includes(ARCH),
1246
+ 其它目录被误伤: afterOther.includes(ARCH)
1247
+ })
1248
+ )
1249
+
1250
+ // ── 改绑同一目录:覆盖而不是新增 ─────────────────────────────────────
1251
+ const rebound = await callRoute(ctx, '/api/soul/bindings', { dir: dirProject, persona: '极简主义者' })
1252
+ const tableAfterRebind = readBindings()
1253
+ push(
1254
+ 'R8 同一目录改绑是覆盖:条数不变,人设换新(否则改绑会把表越写越长)',
1255
+ rebound.status === 200 &&
1256
+ Object.keys(tableAfterRebind).length === 2 &&
1257
+ tableAfterRebind[dirProject] === '极简主义者',
1258
+ JSON.stringify(tableAfterRebind)
1259
+ )
1260
+
1261
+ // ── 解绑:按比较键命中,删空不刷新 ───────────────────────────────────
1262
+ // 用「另一种写法」解绑:Windows 上折大小写 + 尾分隔符(两者都指向同一目录)。
1263
+ // 拿原串直接 delete 的话这一步会「点了没反应」—— 用户看着列表里那一行,
1264
+ // 点下去什么都没发生。
1265
+ const altSpelling = process.platform === 'win32' ? `${dirProject}\\`.toUpperCase() : `${dirProject}/`
1266
+ const removedOne = await callRoute(ctx, '/api/soul/bindings/delete', { dir: altSpelling })
1267
+ push(
1268
+ 'R9 用另一种写法(大小写 / 尾分隔符)解绑仍能命中,并按比较键删掉原键',
1269
+ removedOne.status === 200 &&
1270
+ removedOne.body?.removed === true &&
1271
+ !Object.prototype.hasOwnProperty.call(readBindings(), dirProject),
1272
+ JSON.stringify({ removed: removedOne.body?.removed, 剩余: Object.keys(readBindings()) })
1273
+ )
1274
+
1275
+ await drain()
1276
+ const injectedBeforeEmpty = ctx.state.injected.length
1277
+ const sectionsBeforeEmpty = ctx.state.sections.length
1278
+ const removedNone = await callRoute(ctx, '/api/soul/bindings/delete', { dir: dirThird })
1279
+ await drain()
1280
+ push(
1281
+ 'R10 解绑一个本来就没绑的目录:如实回 removed=false,且**不触发刷新**(空解绑会向所有会话注入一条假更新)',
1282
+ removedNone.status === 200 &&
1283
+ removedNone.body?.removed === false &&
1284
+ ctx.state.injected.length === injectedBeforeEmpty &&
1285
+ ctx.state.sections.length === sectionsBeforeEmpty,
1286
+ JSON.stringify({
1287
+ 注入: `${injectedBeforeEmpty} → ${ctx.state.injected.length}`,
1288
+ section: `${sectionsBeforeEmpty} → ${ctx.state.sections.length}`
1289
+ })
1290
+ )
1291
+
1292
+ // ── 失效引用:如实标注,但不自动删除 ─────────────────────────────────
1293
+ await callRoute(ctx, '/api/soul/personas/save', { name: 'R自建' })
1294
+ await callRoute(ctx, '/api/soul/bindings', { dir: dirThird, persona: 'R自建' })
1295
+ await callRoute(ctx, '/api/soul/personas/delete', { name: 'R自建' })
1296
+ const afterDelete = await callRoute(ctx, '/api/soul/bindings', null, 'GET')
1297
+ const invalid = afterDelete.body?.invalid || []
1298
+ push(
1299
+ 'R11 绑定指向的人设被删掉后如实列进 invalid,且条目仍在表里(不自动删除 —— 用户可能只是改个名字)',
1300
+ invalid.length === 1 &&
1301
+ invalid[0].dir === dirThird &&
1302
+ invalid[0].persona === 'R自建' &&
1303
+ Object.prototype.hasOwnProperty.call(afterDelete.body?.bindings || {}, dirThird),
1304
+ JSON.stringify({ invalid, 表: afterDelete.body?.bindings })
1305
+ )
1306
+
1307
+ // ── inherited 判别:必须在宿主做 ─────────────────────────────────────
1308
+ // 绑定 dirProject,会话 cwd 是它自己 vs 它的子目录:前者「就是本目录」、
1309
+ // 后者「继承自上级」。客户端拿原始串比较在 Windows 上会被盘符大小写骗过。
1310
+ await callRoute(ctx, '/api/soul/bindings', { dir: dirProject, persona: '资深架构师' })
1311
+ const view = await callRoute(ctx, '/api/soul/bindings', null, 'GET')
1312
+ const byId = Object.fromEntries((view.body?.sessions || []).map((s) => [s.id, s]))
1313
+ push(
1314
+ 'R12 sessions 如实区分「就是本目录」与「继承自上级」,没有 cwd 的会话显式回报 cwd:null',
1315
+ byId['br-proj']?.binding?.inherited === false &&
1316
+ byId['br-sub']?.binding?.inherited === true &&
1317
+ byId['br-other']?.binding?.persona === '极简主义者' &&
1318
+ byId['br-other']?.binding?.inherited === false &&
1319
+ byId['br-nocwd']?.cwd === null &&
1320
+ byId['br-nocwd']?.binding === null,
1321
+ JSON.stringify({
1322
+ proj: byId['br-proj']?.binding,
1323
+ sub: byId['br-sub']?.binding,
1324
+ other: byId['br-other']?.binding,
1325
+ nocwd: byId['br-nocwd']?.cwd
1326
+ })
1327
+ )
1328
+
1329
+ // ★ 生效人设(sessions[].persona)必须与**绑定结果**一致,而不是全局配置那一个。
1330
+ //
1331
+ // 这是设置页要回答的那个问题:「我这个项目现在到底是谁」。只回报 binding 名是不够的 ——
1332
+ // 绑定可能指向一个已删除的人设(那时生效的其实是全局配置),两者必须分别可见。
1333
+ // 同理,若这里错用了全局配置算生效人设,带绑定的会话会显示成全局的那个名字,
1334
+ // 而会话里注入的却是绑定的人设 —— 界面与事实相反,正是最难查的一类 bug。
1335
+ const globalPersona = (await callRoute(ctx, '/api/soul/status', null, 'GET')).body?.persona
1336
+ push(
1337
+ 'R13 sessions 的生效人设跟随绑定解析结果(不是全局那一个),且与状态端点对全局的描述不矛盾',
1338
+ byId['br-proj']?.persona === '资深架构师' &&
1339
+ byId['br-other']?.persona === '极简主义者' &&
1340
+ byId['br-sub']?.persona === '资深架构师' &&
1341
+ globalPersona !== '资深架构师',
1342
+ JSON.stringify({
1343
+ proj: byId['br-proj']?.persona,
1344
+ sub: byId['br-sub']?.persona,
1345
+ other: byId['br-other']?.persona,
1346
+ 全局: globalPersona
1347
+ })
1348
+ )
1349
+ } finally {
1350
+ if (previous === undefined) delete process.env.DSH_HOME
1351
+ else process.env.DSH_HOME = previous
1352
+ rmSync(dshHome, { recursive: true, force: true })
1353
+ rmSync(dirProject, { recursive: true, force: true })
1354
+ rmSync(dirOther, { recursive: true, force: true })
1355
+ rmSync(dirThird, { recursive: true, force: true })
1356
+ }
1357
+
1358
+ return results
1359
+ }
1360
+
508
1361
  // ==================== 挂载沙箱 ====================
509
1362
  /**
510
1363
  * 把插件复制到临时目录,并生成静态依赖 `@deepseek-ai/dsh-llm` 的形状兼容桩。
@@ -569,6 +1422,60 @@ async function main() {
569
1422
  rmSync(corruptSandbox.dir, { recursive: true, force: true })
570
1423
  }
571
1424
 
1425
+ // 变更记录与撤销(0.8.0):另起沙箱,因为它的前置状态是「已经攒下一串记录」,
1426
+ // 与上面那条从空配置起步的场景互相污染。
1427
+ console.log('')
1428
+ console.log('G 变更记录:提交即留痕、撤销、恢复预设、清空')
1429
+ const historySandbox = prepareSandbox(PKG_DIR, 'history')
1430
+ try {
1431
+ for (const r of await historyScenario(historySandbox.entry)) record(r.name, r.ok, r.detail)
1432
+ } finally {
1433
+ rmSync(historySandbox.dir, { recursive: true, force: true })
1434
+ }
1435
+
1436
+ // 手改配置后撤销必须被拒(409):需要一次「进程外的改动」,只能靠重新挂载复现
1437
+ console.log('')
1438
+ console.log('H 撤销的拒绝路径:配置被进程外改动')
1439
+ const divergedSandbox = prepareSandbox(PKG_DIR, 'diverged')
1440
+ try {
1441
+ for (const r of await historyDivergedScenario(divergedSandbox.entry)) record(r.name, r.ok, r.detail)
1442
+ } finally {
1443
+ rmSync(divergedSandbox.dir, { recursive: true, force: true })
1444
+ }
1445
+
1446
+ // 工作区绑定(0.8.1-b):另起沙箱,因为它的前置状态是「绑定表已经在磁盘上」,
1447
+ // 而绑定表只在 apply() 读取一次。混进前面那些场景会互相污染。
1448
+ console.log('')
1449
+ console.log('W 工作区绑定:不同 cwd 的会话各自解析人设')
1450
+ const workspaceSandbox = prepareSandbox(PKG_DIR, 'workspace')
1451
+ try {
1452
+ for (const r of await workspaceBindingScenario(workspaceSandbox.entry)) record(r.name, r.ok, r.detail)
1453
+ } finally {
1454
+ rmSync(workspaceSandbox.dir, { recursive: true, force: true })
1455
+ }
1456
+
1457
+ // 身份键(Junction)与读取失败的降级:每种前置状态都要重新挂载一次,
1458
+ // 因为绑定表只在 apply() 里读一次。
1459
+ console.log('')
1460
+ console.log('W2 绑定身份键与降级:Junction 入口 / 真实路径 / 损坏 / 版本不认识')
1461
+ const identitySandbox = prepareSandbox(PKG_DIR, 'identity')
1462
+ try {
1463
+ for (const r of await bindingIdentityScenario(identitySandbox.entry)) record(r.name, r.ok, r.detail)
1464
+ } finally {
1465
+ rmSync(identitySandbox.dir, { recursive: true, force: true })
1466
+ }
1467
+
1468
+ // 绑定写路由(0.8.1-c):另起沙箱,因为它的前置状态是「绑定表里已经有一条」,
1469
+ // 且它要观察**写入后活动会话立刻被刷新** —— 与前面那些只读装配的场景互相污染。
1470
+ console.log('')
1471
+ console.log('R 工作区绑定路由:方法分派、准入拒绝、写入即生效、解绑')
1472
+ const bindingRoutesSandbox = prepareSandbox(PKG_DIR, 'broutes')
1473
+ try {
1474
+ for (const r of await bindingRoutesScenario(bindingRoutesSandbox.entry)) record(r.name, r.ok, r.detail)
1475
+ } finally {
1476
+ rmSync(bindingRoutesSandbox.dir, { recursive: true, force: true })
1477
+ }
1478
+
572
1479
  // 判断力对照:把 provider 读的配置源换成 DEFAULT_CONFIG(模拟「配置改了但读不到」),
573
1480
  // E4 / E8 必须失败 —— 否则这些断言证明不了「新配置真的到了 provider」。
574
1481
  const sandbox = mkdtempSync(join(tmpdir(), 'dsh-soul-sabotage-'))
@@ -582,12 +1489,13 @@ async function main() {
582
1489
  const target = join(patched, 'index.mjs')
583
1490
  const source = readFileSync(target, 'utf8')
584
1491
  // marker 取「provider 读的那个配置源」这一表达式本身,而不是它所在的整行语句 ——
585
- // 后者会随 section 注册处的写法调整而失效(曾经就这样报废过一次对照)。
586
- const marker = 'compilePrompt(configCache || DEFAULT_CONFIG)'
587
- if (!source.includes(marker)) {
588
- record('E 判断力对照:可在副本中改坏 provider 的配置源', false, '找不到 marker')
1492
+ // 后者会随 section 注册处的写法调整而失效(曾经就这样报废过一次对照;
1493
+ // 0.8.1-b 把 text 回调改成按 cwd 解析后又失效了一次,这次仍只钉表达式)。
1494
+ const marker = 'configCache || DEFAULT_CONFIG'
1495
+ if (!source.includes(marker) || source.split(marker).length !== 2) {
1496
+ record('E 判断力对照:可在副本中改坏 provider 的配置源', false, '找不到 marker 或 marker 不唯一')
589
1497
  } else {
590
- writeFileSync(target, source.replace(marker, 'compilePrompt(DEFAULT_CONFIG)'))
1498
+ writeFileSync(target, source.replace(marker, 'DEFAULT_CONFIG'))
591
1499
  const sabotageSandbox = prepareSandbox(patched, 'sabotage')
592
1500
  try {
593
1501
  sabotage = await scenario(sabotageSandbox.entry)