sage-mem 2.16.0 → 2.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/settings.js CHANGED
@@ -4,15 +4,33 @@
4
4
  * 这里的每一项都与 `memory/config.js` 的 `SAGE_MEM_*` 一一对应;边界值照抄那边的
5
5
  * envInt 调用(lo/hi 不许在这里另立一套)。
6
6
  */
7
- import { readFile } from 'node:fs/promises'
7
+ import { mkdir, readFile } from 'node:fs/promises'
8
8
  import { join } from 'node:path'
9
- import { LIMIT_SPECS, STATE_ROOT, resolveLimits } from './memory/config.js'
10
- import { EXPERIMENTAL_SPECS, resolveExperimental } from './memory/experimental.js'
9
+ import {
10
+ LIMIT_SPECS,
11
+ MAX_BASELINE,
12
+ MAX_CHARS_PER_FILE,
13
+ MAX_RESULTS,
14
+ MAX_SESSION_BYTES,
15
+ RESERVED_FILES,
16
+ STALE_DAYS,
17
+ STARTUP_LIMIT_DIAGNOSTICS,
18
+ STATE_ROOT,
19
+ resolveLimits,
20
+ } from './memory/config.js'
21
+ import {
22
+ EXPERIMENTAL_SPECS,
23
+ STARTUP_EXPERIMENTAL_DIAGNOSTICS,
24
+ applyRuntimeExperimental,
25
+ liveExperimental,
26
+ resolveExperimental,
27
+ } from './memory/experimental.js'
11
28
  import { MAX_RAW_BYTES } from './shared/limits.js'
12
- import { isPlainMdName } from './shared/md-name.js'
29
+ import { INDEX_FILE_KEY, SESSION_LOG_KEY, isPlainMdName } from './shared/md-name.js'
13
30
  export { LIMIT_SPECS, MAX_RAW_BYTES }
14
31
  import { DEFAULT_CONFIG } from './autodream/config.js'
15
32
  import { readJson } from './autodream/util.js'
33
+ import { warnLog, writeFileAtomic } from './memory/util.js'
16
34
 
17
35
  /** 面板设置的落点:状态根下(与 autodream 的配置、台账同级)。 */
18
36
  export const SETTINGS_FILE = join(STATE_ROOT, 'settings.json')
@@ -198,3 +216,156 @@ export async function autodreamConfigSnapshot() {
198
216
  const parsed = await readJson(join(STATE_ROOT, 'autodream.json'))
199
217
  return { ...DEFAULT_CONFIG, ...(parsed?.config ?? {}) }
200
218
  }
219
+
220
+ /**
221
+ * 面板上的注入设置(5 项上限 + 保护名 + 实验性开关 + 界面入口)。
222
+ *
223
+ * ⚠️ **那 5 个上限常量是模块加载时读的**:面板改完要**重启 DSH** 才生效。所以这里同时给出
224
+ * 「当前生效值」`limits`、「待生效值」`pendingLimits` 与 `restartRequired` —— 界面才能诚实地说
225
+ * 「改好了,重启后生效」,而不是让用户以为立刻生效。带 `live: true` 的实验性开关是例外:
226
+ * 它们不进 `restartRequired`(说「要重启」而实际已经生效,比不说更糟)。
227
+ *
228
+ * 2.17.1 从 `lib/index.js` 搬来(组合根撞 1000 行上限)。搬的理由不只是行数:设置的读与写、
229
+ * 合并与校验本来就该住在一个文件里,原先读在组合根、写也在组合根,而 `parseUiPatch` /
230
+ * `pendingExperimental` 这些判据却住在这里 —— 一处概念散在两个文件。
231
+ *
232
+ * @param {object} ctx — 宿主上下文(`warnLog` 用)
233
+ */
234
+ export async function readSettingsSnapshot(ctx) {
235
+ const fileRead = await readSettingsFileDetailed()
236
+ const limits = {
237
+ maxResults: MAX_RESULTS,
238
+ maxChars: MAX_CHARS_PER_FILE,
239
+ maxBaseline: MAX_BASELINE,
240
+ maxSessionBytes: MAX_SESSION_BYTES,
241
+ staleDays: STALE_DAYS,
242
+ }
243
+ // Q04:pending 与**启动解析**共用 `resolveLimits` 这一份判据(持久设置 > 环境变量 > 默认)。
244
+ const pending = resolveLimits(fileRead.data?.limits)
245
+ // 2.17.0:从 `EXPERIMENTAL_SPECS` 派生(原先手写 mmr/todoBoard 两份,加开关就得来改第三次)。
246
+ const experimental = Object.fromEntries(Object.keys(EXPERIMENTAL_SPECS).map((k) => [k, liveExperimental(k)]))
247
+ const pendingLab = pendingExperimental(fileRead.data)
248
+ // 坏设置给明确诊断、不静默回默认:启动期那份 + 这次读文件的问题 + 逐项非法/越界说明,去重后一起给。
249
+ const limitDiagnostics = [...new Set([
250
+ ...STARTUP_LIMIT_DIAGNOSTICS,
251
+ ...STARTUP_EXPERIMENTAL_DIAGNOSTICS,
252
+ ...(fileRead.error ? [fileRead.error] : []),
253
+ ...pending.diagnostics,
254
+ ])]
255
+ if (limitDiagnostics.length > 0) {
256
+ warnLog(ctx, `上限设置有问题(本次仍按环境变量/默认值生效):${limitDiagnostics.join(';')}`)
257
+ }
258
+ const reservedExtra = await readReservedFile()
259
+ // 模块加载时那份「用户声明的保护名」(RESERVED_FILES 里抠掉两个内置名)
260
+ const activeExtra = [...RESERVED_FILES].filter((n) => n !== INDEX_FILE_KEY && n !== SESSION_LOG_KEY)
261
+ const norm = (list) => JSON.stringify([...list].map((s) => String(s).toLowerCase()).sort())
262
+ const restartRequired =
263
+ JSON.stringify(limits) !== JSON.stringify(pending.limits) ||
264
+ // 2.11.0:实验性开关里带 `live: true` 的(如 todoBoard)由 client 半当场应用,
265
+ // 不参与 restartRequired。
266
+ Object.keys(pendingLab).some((k) => !EXPERIMENTAL_SPECS[k]?.live && experimental[k] !== pendingLab[k]) ||
267
+ norm(activeExtra) !== norm(reservedExtra)
268
+ // 2.7.0:entry 是 canonical;sidebarEntry 只为 2.6.0 的客户端保留(派生值,不落盘)。
269
+ const ui = pendingUi(fileRead.data)
270
+ return {
271
+ limits,
272
+ pendingLimits: pending.limits,
273
+ // 2.9.0 实验性:`experimental` = 已生效值,`pendingExperimental` = 待生效值。
274
+ experimental,
275
+ pendingExperimental: pendingLab,
276
+ restartRequired,
277
+ // Q04 的诊断出口:面板据此说明「你保存的值没生效,原因是 X」;宿主侧先如实给出。
278
+ limitDiagnostics,
279
+ // 1.8.0 / 2.7.0:客户端行为(界面入口三选一)。**不参与** restartRequired —— 改完立刻生效。
280
+ ui: { ...ui, sidebarEntry: ui.entry !== 'settings' },
281
+ // 生效的保护名单(含两个内置名)+ 用户声明的那部分原文(面板编辑的是后者)
282
+ reserved: [...new Set([INDEX_FILE_KEY, SESSION_LOG_KEY, ...reservedExtra.map((s) => s.toLowerCase())])],
283
+ reservedExtra,
284
+ }
285
+ }
286
+
287
+ /**
288
+ * 改设置:5 项上限落 `<状态根>/settings.json`,保护名单落 `<状态根>/reserved.json`。
289
+ *
290
+ * 校验**先全部过一遍再写盘**:任何一个值非法就整体 `{ ok:false }`,绝不写半份。
291
+ * 越界不是「夹到边界」(那是环境变量的宽容语义)—— 面板上手输的数字越界是笔误,
292
+ * 静默改成别的值比报错更让人困惑。
293
+ *
294
+ * @param {object} ctx — 宿主上下文(`warnLog` 用)
295
+ * @param {object} patch
296
+ */
297
+ export async function applySettingsPatch(ctx, patch) {
298
+ const p = patch && typeof patch === 'object' && !Array.isArray(patch) ? patch : {}
299
+ const limitsPatch = p.limits && typeof p.limits === 'object' && !Array.isArray(p.limits) ? p.limits : null
300
+ const nextLimits = {}
301
+ if (limitsPatch) {
302
+ for (const [key, value] of Object.entries(limitsPatch)) {
303
+ const spec = LIMIT_SPECS[key]
304
+ if (!spec) return { ok: false, error: `sage-mem: unknown setting: ${key}` }
305
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
306
+ return { ok: false, error: `sage-mem: ${key} must be a number, got ${typeof value}` }
307
+ }
308
+ const rounded = Math.round(value)
309
+ if (rounded < spec.lo || rounded > spec.hi) {
310
+ return { ok: false, error: `sage-mem: ${key} must be an integer in [${spec.lo}, ${spec.hi}], got ${value}` }
311
+ }
312
+ nextLimits[key] = rounded
313
+ }
314
+ }
315
+ let nextReserved = null
316
+ if (p.reserved !== undefined) {
317
+ if (!Array.isArray(p.reserved)) return { ok: false, error: 'sage-mem: reserved must be an array of file names' }
318
+ const cleaned = []
319
+ for (const item of p.reserved) {
320
+ const s = String(item ?? '').trim()
321
+ if (!isPlainMdName(s) || s.startsWith('..')) {
322
+ return { ok: false, error: `sage-mem: invalid reserved file name: ${String(item)}` }
323
+ }
324
+ if (!cleaned.includes(s)) cleaned.push(s)
325
+ }
326
+ nextReserved = cleaned
327
+ }
328
+ // 1.8.0:ui 与 limits / reserved 同一套「先全验、后一起写」—— 任何一个非法,整份 patch 不落盘。
329
+ const uiCheck = parseUiPatch(p.ui)
330
+ if (!uiCheck.ok) return { ok: false, error: uiCheck.error }
331
+ const uiPatch = uiCheck.patch
332
+ // 2.9.0:实验性开关与 limits / ui 同一套「先全验、后一起写」。
333
+ const labCheck = parseExperimentalPatch(p.experimental)
334
+ if (!labCheck.ok) return { ok: false, error: labCheck.error }
335
+ const labPatch = labCheck.patch
336
+ if (!limitsPatch && nextReserved === null && uiPatch === null && labPatch === null) return { ok: false, error: 'sage-mem: empty patch' }
337
+
338
+ await mkdir(STATE_ROOT, { recursive: true })
339
+ if (limitsPatch || uiPatch !== null || labPatch !== null) {
340
+ const currentRead = await readSettingsFileDetailed()
341
+ // 坏文件上不写:没有可合并的旧值,整份重写会把用户手改的内容静默吞掉。
342
+ // 明确拒绝、让用户先修文件,比「保存成功但别的设置都没了」诚实。
343
+ if (currentRead.error) {
344
+ return { ok: false, error: `sage-mem: ${currentRead.error};请先修复或删除它再保存(不会静默覆盖)` }
345
+ }
346
+ const current = currentRead.data
347
+ const mergedLimits = { ...(current?.limits ?? {}), ...nextLimits }
348
+ // 实验性:只覆盖这次给出的键,没给就沿用文件里的有效值(缺失 = 全关)。
349
+ const mergedLab = { ...pendingExperimental(current), ...(labPatch ?? {}) }
350
+ // ui 只覆盖这次给出的键;没给就沿用文件里的有效值(坏值 / 缺失一律按默认「两个都显示」)。
351
+ // 2.7.0:落盘只写 canonical 的 entry,旧 sidebarEntry 由 pendingUi 迁移进来、不再写出。
352
+ const mergedUi = { ...pendingUi(current), ...(uiPatch ?? {}) }
353
+ await writeFileAtomic(SETTINGS_FILE, JSON.stringify({ limits: mergedLimits, experimental: mergedLab, ui: mergedUi, updatedAt: Date.now() }, null, 2))
354
+ }
355
+ if (nextReserved !== null) {
356
+ await writeFileAtomic(RESERVED_FILE, `${JSON.stringify(nextReserved, null, 2)}\n`)
357
+ }
358
+ // 2.17.0:live 开关写盘后立刻生效;必须在下面读快照之前(否则返回的已生效值是旧的)。
359
+ if (labPatch !== null) applyRuntimeExperimental(labPatch)
360
+ // 上限 / 保护名单在模块加载时就固化了,写盘即提示重启;ui 是**客户端行为**,改完立刻生效,
361
+ // 所以只有前两者会强制 true,纯 ui 补丁照实回传(通常就是 false)。
362
+ const settings = await readSettingsSnapshot(ctx)
363
+ // 2.11.0:实验性补丁只在**碰到要重启的键**时才强制 true —— 带 `live: true` 的
364
+ // 由 client 半当场应用,写盘即生效,不该再吓用户一次。
365
+ const labNeedsRestart = labPatch !== null && Object.keys(labPatch).some((k) => !EXPERIMENTAL_SPECS[k]?.live)
366
+ return {
367
+ ok: true,
368
+ settings,
369
+ restartRequired: limitsPatch || nextReserved !== null || labNeedsRestart ? true : settings.restartRequired,
370
+ }
371
+ }