dsh-ta 0.1.0 → 0.3.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.
@@ -0,0 +1,387 @@
1
+ /**
2
+ * TA 生命周期:初始化、转生。
3
+ *
4
+ * 两个入口都从 host 读取运行时依赖,并统一放进同一个串行队列里执行:
5
+ * host = { ctx, config, runtime, lifecycle, queue, logger, configEditor }
6
+ *
7
+ * lifecycle 是可变对象 { operation: null | 'reincarnating' },
8
+ * 供状态接口展示“正在转生”。所有写操作串行,失败不能把后续操作卡死。
9
+ */
10
+
11
+ import { AsyncLocalStorage } from 'node:async_hooks'
12
+ import { readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { SettingsError, badRequest, conflict } from './errors.js'
15
+ import {
16
+ assertDestroyableHome, ensureHome, isTaHome, physicalPath, validateHomePath,
17
+ validateNewHome,
18
+ } from './home.js'
19
+ import { reconcileReviewSchedule, removeReviewSchedule } from './schedule.js'
20
+
21
+ const PERSONA_FILES = ['SOUL.md', 'USER.md']
22
+ const QUIESCE_TIMEOUT_MS = 10_000
23
+
24
+ /**
25
+ * 创建串行队列。fn 抛错只影响本次调用,后续任务照常执行。
26
+ * 用 AsyncLocalStorage 识别“已在队列任务内部”的调用:直接执行而不是排到队尾,
27
+ * 避免路由层和生命周期层同时套队列时死锁。
28
+ */
29
+ export function createLifecycleQueue() {
30
+ const inside = new AsyncLocalStorage()
31
+ let tail = Promise.resolve()
32
+
33
+ const enqueue = fn => {
34
+ if (typeof fn !== 'function') return Promise.reject(new TypeError('queue 需要一个函数'))
35
+ if (inside.getStore() === enqueue) return Promise.resolve().then(fn)
36
+ const run = tail.then(() => inside.run(enqueue, fn))
37
+ tail = run.then(() => undefined, () => undefined)
38
+ return run
39
+ }
40
+ return enqueue
41
+ }
42
+
43
+ /** host 没有显式 queue 时,按 host 维度兜底一个,保证同一 host 的写操作仍串行。 */
44
+ const fallbackQueues = new WeakMap()
45
+
46
+ function queueFor(host) {
47
+ if (typeof host?.queue === 'function') return host.queue
48
+ if (host && (typeof host === 'object' || typeof host === 'function')) {
49
+ let queue = fallbackQueues.get(host)
50
+ if (!queue) {
51
+ queue = createLifecycleQueue()
52
+ fallbackQueues.set(host, queue)
53
+ }
54
+ return queue
55
+ }
56
+ return createLifecycleQueue()
57
+ }
58
+
59
+ function runQueued(host, fn) {
60
+ return queueFor(host)(fn)
61
+ }
62
+
63
+ function lifecycleOf(host) {
64
+ if (host?.lifecycle && typeof host.lifecycle === 'object') return host.lifecycle
65
+ const created = { operation: null }
66
+ if (host && typeof host === 'object') host.lifecycle = created
67
+ return created
68
+ }
69
+
70
+ function loggerOf(host) {
71
+ return host?.logger
72
+ }
73
+
74
+ function describe(cause) {
75
+ return cause instanceof Error ? cause.message : String(cause ?? '未知错误')
76
+ }
77
+
78
+ function warn(host, message) {
79
+ try {
80
+ loggerOf(host)?.warn?.(`[dsh-ta] ${message}`)
81
+ } catch {
82
+ /* 日志失败不能影响生命周期 */
83
+ }
84
+ }
85
+
86
+ function info(host, message) {
87
+ try {
88
+ loggerOf(host)?.info?.(`[dsh-ta] ${message}`)
89
+ } catch {
90
+ /* 日志失败不能影响生命周期 */
91
+ }
92
+ }
93
+
94
+ /** 路径比较以 realpath 后结果为准;用于判断“是不是同一个家”。 */
95
+ function samePath(left, right) {
96
+ if (typeof left !== 'string' || typeof right !== 'string') return false
97
+ if (!left || !right) return false
98
+ return physicalPath(left) === physicalPath(right)
99
+ }
100
+
101
+ /** 老家的判定:SOUL.md、USER.md 去空白后都非空。 */
102
+ function hasPersona(home) {
103
+ for (const name of PERSONA_FILES) {
104
+ try {
105
+ const file = join(home, name)
106
+ if (!statSync(file).isFile()) return false
107
+ if (readFileSync(file, 'utf8').trim() === '') return false
108
+ } catch {
109
+ return false
110
+ }
111
+ }
112
+ return true
113
+ }
114
+
115
+ /**
116
+ * 已初始化 = 目录存在,并且带有有效 .ta-home 标记,或者已经有人设文件。
117
+ * 后者用于 0.3.0 之前创建、缺少标记的老家:必须被认成“已有 TA”,不能被当成空目录。
118
+ */
119
+ function isInitializedHome(home) {
120
+ if (typeof home !== 'string' || !home) return false
121
+ try {
122
+ if (!statSync(home).isDirectory()) return false
123
+ } catch {
124
+ return false
125
+ }
126
+ return isTaHome(home) || hasPersona(home)
127
+ }
128
+
129
+ function configEditorOf(host) {
130
+ if (typeof host?.configEditor?.edit === 'function') return host.configEditor
131
+ const editor = host?.ctx?.get?.('configEditor')
132
+ return typeof editor?.edit === 'function' ? editor : undefined
133
+ }
134
+
135
+ function requireConfigEditor(host) {
136
+ const editor = configEditorOf(host)
137
+ if (!editor) {
138
+ throw new SettingsError(500, 'CONFIG_EDITOR_UNAVAILABLE', '无法写入配置:配置编辑器不可用')
139
+ }
140
+ return editor
141
+ }
142
+
143
+ /** 把 taHome 写进 profile 配置;写入完成后 volatile getter 会看到新值。 */
144
+ async function editTaHome(host, home) {
145
+ const editor = requireConfigEditor(host)
146
+ const entry = host?.ctx?.fiber?.entry
147
+ if (!entry) {
148
+ throw new SettingsError(500, 'CONFIG_EDITOR_UNAVAILABLE', '无法写入配置:找不到插件配置项')
149
+ }
150
+ await editor.edit(entry, current => ({ ...current, taHome: home }))
151
+ }
152
+
153
+ function stopRuntime(host) {
154
+ const runtime = host?.runtime
155
+ if (runtime && typeof runtime.stop === 'function') runtime.stop()
156
+ }
157
+
158
+ function startRuntime(host) {
159
+ const runtime = host?.runtime
160
+ if (runtime && typeof runtime.start === 'function') return runtime.start()
161
+ return undefined
162
+ }
163
+
164
+ function rebindRuntime(host) {
165
+ const runtime = host?.runtime
166
+ if (runtime && typeof runtime.rebind === 'function') return runtime.rebind()
167
+ stopRuntime(host)
168
+ return startRuntime(host)
169
+ }
170
+
171
+ /** 删除旧家前尽力停止/等待运行中的 TA 会话;超时只记录 warning。 */
172
+ async function quiesceHomeSessions(host, home) {
173
+ let agents
174
+ try {
175
+ agents = host?.ctx?.agents?.list?.()
176
+ } catch {
177
+ agents = undefined
178
+ }
179
+ if (!Array.isArray(agents) || agents.length === 0) return
180
+ const waits = []
181
+ for (const agent of agents) {
182
+ const cwd = agent?.session?.header?.cwd
183
+ if (typeof cwd !== 'string' || !samePath(cwd, home)) continue
184
+ try {
185
+ agent.cancel?.({ kind: 'hook', reason: 'ta-reincarnate-cleanup' })
186
+ } catch {
187
+ /* 取消失败仍尽量等待 */
188
+ }
189
+ try {
190
+ const idle = agent.whenIdle?.()
191
+ if (idle && typeof idle.then === 'function') waits.push(Promise.resolve(idle).catch(() => {}))
192
+ } catch {
193
+ /* whenIdle 不可用时继续 */
194
+ }
195
+ }
196
+ if (waits.length === 0) return
197
+ await Promise.race([
198
+ Promise.all(waits),
199
+ new Promise(resolvePromise => setTimeout(resolvePromise, QUIESCE_TIMEOUT_MS)),
200
+ ])
201
+ }
202
+
203
+ function busyError() {
204
+ return conflict('LIFECYCLE_BUSY', 'TA 正在转生中,请稍候再试')
205
+ }
206
+
207
+ function assertLifecycleIdle(host) {
208
+ if (lifecycleOf(host).operation) throw busyError()
209
+ }
210
+
211
+ /**
212
+ * 回顾任务同步:用户关掉 reviewScheduleEnabled 时不创建新任务;
213
+ * 换家时旧家的回顾任务仍然要清掉。
214
+ */
215
+ async function syncReviewSchedule(host, previousHome) {
216
+ const { ctx, config } = host
217
+ if (config?.reviewScheduleEnabled === false) {
218
+ const warnings = []
219
+ if (previousHome && !samePath(previousHome, config.taHome)) {
220
+ const removed = await removeReviewSchedule(ctx, previousHome, loggerOf(host))
221
+ warnings.push(...(removed.warnings ?? []))
222
+ }
223
+ return { created: false, existing: false, disabled: true, warnings }
224
+ }
225
+ return reconcileReviewSchedule(ctx, config, previousHome, loggerOf(host))
226
+ }
227
+
228
+ function ensureResult(path, ensured) {
229
+ return {
230
+ initialized: true,
231
+ home: path,
232
+ created: ensured.created,
233
+ adopted: ensured.adopted,
234
+ marked: ensured.marked,
235
+ repairedMarker: ensured.repairedMarker === true,
236
+ createdDirs: ensured.createdDirs,
237
+ createdFiles: ensured.createdFiles,
238
+ }
239
+ }
240
+
241
+ /**
242
+ * 初始化 TA 的家。
243
+ *
244
+ * - 未初始化:校验路径 → 建家 → (路径和配置不同时)写 taHome → rebind → 同步回顾任务。
245
+ * - 已初始化且路径就是当前家:只补缺失的标记/模板,已有文件不覆盖;runtime 没跑就启动。
246
+ * - 已初始化但换了路径:拒绝,换家必须走转生。
247
+ */
248
+ export async function initializeHome(host, input) {
249
+ assertLifecycleIdle(host)
250
+ return runQueued(host, async () => {
251
+ const config = host?.config ?? {}
252
+ const currentHome = config.taHome
253
+ const initialized = isInitializedHome(currentHome)
254
+ const requested = validateHomePath(input?.path)
255
+
256
+ if (initialized) {
257
+ if (!samePath(requested.path, currentHome)) {
258
+ throw badRequest('ALREADY_INITIALIZED', 'TA 已经有了家,改变家请使用转生')
259
+ }
260
+ // 老用户补标记、补目录;ensureHome 只创建缺失项,绝不覆盖 SOUL.md / USER.md。
261
+ const ensured = ensureHome(currentHome)
262
+ const runtime = host?.runtime
263
+ if (runtime && typeof runtime.start === 'function' && runtime.running !== true) runtime.start()
264
+ info(host, `TA 的家已存在,补齐标记/模板:${ensured.path}`)
265
+ return {
266
+ ...ensureResult(ensured.path, ensured),
267
+ configChanged: false,
268
+ warnings: [],
269
+ }
270
+ }
271
+
272
+ let existingEntries = []
273
+ try {
274
+ existingEntries = readdirSync(requested.path)
275
+ } catch {
276
+ existingEntries = []
277
+ }
278
+ if (existingEntries.length > 0
279
+ && !isInitializedHome(requested.path)
280
+ && input?.confirmAdopt !== true) {
281
+ throw badRequest(
282
+ 'ADOPT_CONFIRM_REQUIRED',
283
+ '这个目录已有内容。确认接管后只会补写 .ta-home 和缺失的模板/目录,不会覆盖已有文件。',
284
+ )
285
+ }
286
+ const ensured = ensureHome(requested.path)
287
+ const configChanged = !samePath(ensured.path, currentHome)
288
+ const warnings = []
289
+ if (configChanged) {
290
+ await editTaHome(host, ensured.path)
291
+ }
292
+ rebindRuntime(host)
293
+ const schedule = await syncReviewSchedule(host, configChanged ? currentHome : undefined)
294
+ warnings.push(...(schedule.warnings ?? []))
295
+ info(host, `TA 的家已初始化:${ensured.path}`)
296
+ return {
297
+ ...ensureResult(ensured.path, ensured),
298
+ configChanged,
299
+ warnings,
300
+ }
301
+ })
302
+ }
303
+
304
+ /**
305
+ * 转生:保留 ReMe 记忆,换一个全新的空家。
306
+ * 默认保留旧家;用户显式勾选并确认时,切换成功后删除旧家。
307
+ * 失败时尽量恢复旧 runtime(配置尚未改)或对新家 rebind;已创建的新家不删除。
308
+ */
309
+ export async function reincarnate(host, input) {
310
+ assertLifecycleIdle(host)
311
+ if (input?.confirm !== '转生') {
312
+ throw badRequest('CONFIRM_REQUIRED', '请输入“转生”以确认转生')
313
+ }
314
+ const config = host?.config ?? {}
315
+ const oldHome = config.taHome
316
+ if (!isInitializedHome(oldHome)) {
317
+ throw badRequest('NOT_INITIALIZED', 'TA 还没有家,请先初始化 TA 的家')
318
+ }
319
+ const deleteOldHome = input?.deleteOldHome === true
320
+ if (deleteOldHome) {
321
+ if (input?.deleteConfirm !== '删除旧家') {
322
+ throw badRequest('DELETE_CONFIRM_REQUIRED', '要删除旧家,请输入“删除旧家”确认')
323
+ }
324
+ // 在动任何东西之前先验证旧家可以安全删除。
325
+ assertDestroyableHome(oldHome, { ctx: host?.ctx })
326
+ }
327
+ const target = validateNewHome(oldHome, input?.newHome)
328
+ const lifecycle = lifecycleOf(host)
329
+ lifecycle.operation = 'reincarnating'
330
+
331
+ return runQueued(host, async () => {
332
+ let configChanged = false
333
+ let oldHomeDeleted = false
334
+ let ensured
335
+ const warnings = []
336
+ try {
337
+ stopRuntime(host)
338
+ ensured = ensureHome(target.path)
339
+ await editTaHome(host, target.path)
340
+ configChanged = true
341
+ rebindRuntime(host)
342
+ const schedule = await syncReviewSchedule(host, oldHome)
343
+ warnings.push(...(schedule.warnings ?? []))
344
+ if (deleteOldHome) {
345
+ try {
346
+ await quiesceHomeSessions(host, oldHome)
347
+ rmSync(physicalPath(oldHome), { recursive: true, force: true })
348
+ oldHomeDeleted = true
349
+ info(host, `旧家已删除:${oldHome}`)
350
+ } catch (cleanupCause) {
351
+ warnings.push(`旧家删除失败,旧家仍保留:${describe(cleanupCause)}`)
352
+ warn(host, warnings[warnings.length - 1])
353
+ }
354
+ }
355
+ info(host, `TA 已转生:${oldHome} -> ${target.path}${oldHomeDeleted ? '(旧家已删除)' : '(旧家保留)'}`)
356
+ return { previousHome: oldHome, home: target.path, oldHomeDeleted, warnings }
357
+ } catch (cause) {
358
+ // 恢复:配置没改成 → 旧家继续可用;配置已指到新家 → 对新家 rebind。
359
+ if (!configChanged) {
360
+ try {
361
+ startRuntime(host)
362
+ } catch (recoverCause) {
363
+ warnings.push(`恢复旧 runtime 失败:${describe(recoverCause)}`)
364
+ }
365
+ // 只清理本次刚创建的新家;用户原有空目录不能删。
366
+ if (ensured?.created) {
367
+ try {
368
+ rmSync(target.path, { recursive: true, force: true })
369
+ } catch (cleanupCause) {
370
+ warnings.push(`清理未使用的新家失败:${describe(cleanupCause)}`)
371
+ }
372
+ }
373
+ } else {
374
+ try {
375
+ rebindRuntime(host)
376
+ } catch (recoverCause) {
377
+ warnings.push(`新家 runtime 启动失败:${describe(recoverCause)}`)
378
+ }
379
+ }
380
+ for (const message of warnings) warn(host, message)
381
+ if (cause instanceof SettingsError && cause.status === 400) throw cause
382
+ throw new SettingsError(500, 'REINCARNATE_FAILED', `转生失败:${describe(cause)}`)
383
+ } finally {
384
+ lifecycle.operation = null
385
+ }
386
+ })
387
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * 人设读写:只允许 SOUL.md / USER.md,全部经 withinHome。
3
+ *
4
+ * 设计要点:
5
+ * - revision = sha256:<hex>,对 UTF-8 内容计算;文件不存在按空串。
6
+ * - 写入前校验 revision,防止两个设置页互相覆盖(409 PERSONA_CONFLICT)。
7
+ * - 超过建议预算只返回 warnings,不截断;超过硬上限(PERSONA_MAX_CHARS)返回 400。
8
+ * - 写入串行化,单个文件写入使用 storage.writeAtomic。
9
+ */
10
+
11
+ import { statSync } from 'node:fs'
12
+ import { readTextIfExists, sha256Revision, withinHome, writeAtomic } from '../storage.js'
13
+ import { PERSONA_BUDGETS, PERSONA_MAX_CHARS } from './defaults.js'
14
+ import { badRequest, conflict } from './errors.js'
15
+
16
+ /** 字段名与 identity.js 注入时使用的标题保持一致,预览才能反映真实注入内容。 */
17
+ const PERSONA_FILES = {
18
+ soul: { file: 'SOUL.md', title: '# 你是谁' },
19
+ user: { file: 'USER.md', title: '# 关于Ta' },
20
+ }
21
+
22
+ /** 模块内写入队列:同一进程内的多次保存按调用顺序执行。 */
23
+ let writeTail = Promise.resolve()
24
+
25
+ function enqueueWrite(task) {
26
+ const run = writeTail.then(task)
27
+ // 队列自身永远保持 resolved,某次保存失败不会卡死后续保存。
28
+ writeTail = run.catch(() => undefined)
29
+ return run
30
+ }
31
+
32
+ function requireHome(config) {
33
+ const home = config?.taHome
34
+ if (typeof home !== 'string' || home.length === 0) {
35
+ throw badRequest('HOME_INVALID', 'TA 的家尚未配置')
36
+ }
37
+ }
38
+
39
+ /** 先有家,再有人设;否则 writeAtomic 会隐式创建目录。 */
40
+ function requireExistingHome(config) {
41
+ requireHome(config)
42
+ try {
43
+ if (statSync(config.taHome).isDirectory()) return
44
+ } catch {
45
+ /* fall through */
46
+ }
47
+ throw badRequest('HOME_NOT_INITIALIZED', '先创建 TA 的家,再保存人设')
48
+ }
49
+
50
+ /** withinHome 的路径越界错误统一转成可读的 400 文案。 */
51
+ function personaPath(config, key) {
52
+ try {
53
+ return withinHome(PERSONA_FILES[key].file, config)
54
+ } catch {
55
+ throw badRequest('PERSONA_PATH_INVALID', '人设文件不在 TA 的家内,已拒绝访问')
56
+ }
57
+ }
58
+
59
+ function readPersonaText(config, key) {
60
+ const text = readTextIfExists(personaPath(config, key))
61
+ return typeof text === 'string' ? text : ''
62
+ }
63
+
64
+ /** 超出建议预算的提示;只提示,不修改、不截断内容。 */
65
+ function budgetWarnings(soul, user) {
66
+ const warnings = []
67
+ if (soul.length > PERSONA_BUDGETS.soul) {
68
+ warnings.push(`SOUL.md 已有 ${soul.length} 字,超过建议预算 ${PERSONA_BUDGETS.soul} 字,超出部分不会注入`)
69
+ }
70
+ if (user.length > PERSONA_BUDGETS.user) {
71
+ warnings.push(`USER.md 已有 ${user.length} 字,超过建议预算 ${PERSONA_BUDGETS.user} 字,超出部分不会注入`)
72
+ }
73
+ return warnings
74
+ }
75
+
76
+ function personaRecord(soul, user) {
77
+ return {
78
+ soul,
79
+ user,
80
+ soulRevision: sha256Revision(soul),
81
+ userRevision: sha256Revision(user),
82
+ budgets: { soul: PERSONA_BUDGETS.soul, user: PERSONA_BUDGETS.user },
83
+ warnings: budgetWarnings(soul, user),
84
+ }
85
+ }
86
+
87
+ function requireInputText(value, label) {
88
+ if (typeof value !== 'string') {
89
+ throw badRequest('PERSONA_INVALID', `${label} 内容必须是文本`)
90
+ }
91
+ return value
92
+ }
93
+
94
+ function requireRevision(value, label) {
95
+ if (typeof value !== 'string' || value.length === 0) {
96
+ throw badRequest('PERSONA_INVALID', `缺少 ${label} 的版本号,请刷新后重试`)
97
+ }
98
+ return value
99
+ }
100
+
101
+ function assertWithinMaxChars(label, text, max) {
102
+ if (text.length > max) {
103
+ throw badRequest('PERSONA_TOO_LARGE', `${label} 最多 ${max} 字,请压缩后再保存`)
104
+ }
105
+ }
106
+
107
+ function personaConflict() {
108
+ return conflict('PERSONA_CONFLICT', '文件已被其他会话修改,请刷新后重试')
109
+ }
110
+
111
+ /** 预览注入文本时的截断规则,与 identity.js 的 truncate 完全一致。 */
112
+ function truncateForInjection(text, cap) {
113
+ const trimmed = text.trim()
114
+ if (trimmed.length <= cap) return { text: trimmed, truncated: false }
115
+ return { text: `${trimmed.slice(0, cap)}\n…(已截断)`, truncated: true }
116
+ }
117
+
118
+ /** 读取两个当前人设文件,返回内容、revision、预算与超预算警告。 */
119
+ export function readPersona(config) {
120
+ requireHome(config)
121
+ const soul = readPersonaText(config, 'soul')
122
+ const user = readPersonaText(config, 'user')
123
+ return personaRecord(soul, user)
124
+ }
125
+
126
+ /**
127
+ * 保存人设。
128
+ * input: { soul, user, soulRevision, userRevision }
129
+ * revision 与磁盘当前内容不一致时抛 409 PERSONA_CONFLICT。
130
+ */
131
+ export function writePersona(config, input) {
132
+ return enqueueWrite(async () => {
133
+ requireExistingHome(config)
134
+ const soul = requireInputText(input?.soul, 'SOUL.md')
135
+ const user = requireInputText(input?.user, 'USER.md')
136
+ const soulRevision = requireRevision(input?.soulRevision, 'SOUL.md')
137
+ const userRevision = requireRevision(input?.userRevision, 'USER.md')
138
+ assertWithinMaxChars('SOUL.md', soul, PERSONA_MAX_CHARS.soul)
139
+ assertWithinMaxChars('USER.md', user, PERSONA_MAX_CHARS.user)
140
+
141
+ const currentSoul = readPersonaText(config, 'soul')
142
+ const currentUser = readPersonaText(config, 'user')
143
+ if (soulRevision !== sha256Revision(currentSoul)) throw personaConflict()
144
+ if (userRevision !== sha256Revision(currentUser)) throw personaConflict()
145
+
146
+ writeAtomic(personaPath(config, 'soul'), soul)
147
+ writeAtomic(personaPath(config, 'user'), user)
148
+ return personaRecord(soul, user)
149
+ })
150
+ }
151
+
152
+ /**
153
+ * 单字段保存:input { field: 'soul'|'user', content, revision }。
154
+ * 两个编辑器独立保存时,只更新对应文件和 revision。
155
+ */
156
+ export function writePersonaField(config, input) {
157
+ return enqueueWrite(async () => {
158
+ requireExistingHome(config)
159
+ const field = input?.field
160
+ if (field !== 'soul' && field !== 'user') {
161
+ throw badRequest('PERSONA_INVALID', 'field 必须是 soul 或 user')
162
+ }
163
+ const label = field === 'soul' ? 'SOUL.md' : 'USER.md'
164
+ const content = requireInputText(input?.content, label)
165
+ const revision = requireRevision(input?.revision, label)
166
+ assertWithinMaxChars(label, content, PERSONA_MAX_CHARS[field])
167
+
168
+ const current = readPersonaText(config, field)
169
+ if (revision !== sha256Revision(current)) throw personaConflict()
170
+
171
+ writeAtomic(personaPath(config, field), content)
172
+ return {
173
+ field,
174
+ content,
175
+ revision: sha256Revision(content),
176
+ budgets: { soul: PERSONA_BUDGETS.soul, user: PERSONA_BUDGETS.user },
177
+ warnings: budgetWarnings(field === 'soul' ? content : '', field === 'user' ? content : ''),
178
+ }
179
+ })
180
+ }
181
+
182
+ /**
183
+ * 保存前预览实际会注入的内容。
184
+ * input 为编辑中的草稿 { soul, user };缺省字段回退到磁盘当前内容。
185
+ * 返回 { text, truncated: { soul, user } };超硬上限同样抛 400。
186
+ */
187
+ export function personaPreview(config, input) {
188
+ requireHome(config)
189
+ const soul = typeof input?.soul === 'string' ? input.soul : readPersonaText(config, 'soul')
190
+ const user = typeof input?.user === 'string' ? input.user : readPersonaText(config, 'user')
191
+ assertWithinMaxChars('SOUL.md', soul, PERSONA_MAX_CHARS.soul)
192
+ assertWithinMaxChars('USER.md', user, PERSONA_MAX_CHARS.user)
193
+
194
+ const soulPart = truncateForInjection(soul, PERSONA_BUDGETS.soul)
195
+ const userPart = truncateForInjection(user, PERSONA_BUDGETS.user)
196
+ const parts = []
197
+ if (soulPart.text) parts.push(`${PERSONA_FILES.soul.title}\n${soulPart.text}`)
198
+ if (userPart.text) parts.push(`${PERSONA_FILES.user.title}\n${userPart.text}`)
199
+ return {
200
+ text: parts.join('\n\n'),
201
+ truncated: { soul: soulPart.truncated, user: userPart.truncated },
202
+ }
203
+ }