dsh-cross-memory 0.2.0 → 0.2.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/README.md CHANGED
@@ -18,10 +18,16 @@
18
18
  | 分层注入 | 每个会话注入一次有界摘要;另有按需补注(当前这轮明显相关时)、标题轮转与增量块。 |
19
19
  | 按需召回 | 关键词 + 时间衰减 + 一跳扩展;命中原因可在日志里核对。 |
20
20
  | 原始片段(可选) | 补注块可附带来源会话的原文片段,默认关闭,因为它会把别的会话的原文带进当前上下文。 |
21
- | persona | 维护一份「这个人是谁」的简短画像,注入在记忆摘要之前,单独设字节预算。 |
21
+ | persona | 维护「这个人是谁」的画像(`persona/human.md`),注入在记忆摘要之前,默认预算 12000 字节;设置 → 记忆 → 画像 可查看/编辑,并可锁定不让后台改写。 |
22
22
  | 开放承诺 | 把会话里答应过、但还没到期/没做的事记成台账,到期未闭环会提醒。 |
23
23
  | 反思与技能草稿 | 每周从记忆里提炼跨项目观察(必须引用来源记忆);可把重复流程提成技能草稿,需你手动晋升。 |
24
- | GUI | 设置 → 记忆:浏览/搜索/新增/删除、配置项、待裁决;插件页该包下也有同一张配置卡。 |
24
+ | GUI | 设置 → 记忆:浏览/搜索/新增/删除、**画像查看/编辑与锁定**、配置项、待裁决;插件页该包下也有同一张配置卡。 |
25
+
26
+ ### Persona 画像
27
+
28
+ - **在哪看**:画像是记忆库里的 `persona/human.md`(旧的单文件 `persona.md` 仍兼容读取)。每次会话开始时它被包进 `<persona>…snapshot 日期…</persona>`,注入在记忆摘要之前;超过 `personaMaxBytes`(默认 **12000**,0 关闭)的部分按行截断。
29
+ - **怎么编辑**:**设置 → 记忆 → 画像**,改完点「保存画像」即写回,不经过后台合并,不用重启宿主。
30
+ - **锁定**:同一页勾选「锁定画像」会在画像旁边写 `persona/human.lock`;锁定后后台 consolidation 即使提出画像改写也会跳过(日志会记 `persona is locked; the automatic profile update was skipped`),只有你手动保存才会改变它。取消勾选即解除。
25
31
 
26
32
  更细的设计说明见 [`docs/DETAIL.zh.md`](docs/DETAIL.zh.md)(英文版 [`docs/DETAIL.md`](docs/DETAIL.md))。
27
33
 
@@ -172,7 +178,7 @@ $DSH_HOME/memories/
172
178
  │ └── archive/<id>.md
173
179
  ├── sessions/<session-id>.md # 证据笔记(被挖掘过的会话)
174
180
  ├── skills/<name>/SKILL.md # 技能草稿(未晋升前 DSH 看不到)
175
- ├── persona/ # persona 画像
181
+ ├── persona/ # persona 画像(human.md;human.lock 存在表示已锁定)
176
182
  ├── reflections/ # 每周反思
177
183
  └── state.db # SQLite 状态
178
184
  ```
package/lib/client.js CHANGED
@@ -5,7 +5,7 @@ window.__ModuleLoader__.load({
5
5
  var exports = module.exports;
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
7
  const PACKAGE = "dsh-cross-memory";
8
- const REMOTE_INVOCATION_DATA = [{"method":"overview","parameters":[],"result":"overview"},{"method":"list","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text","optional":true},{"name":"query","wire":"query","shape":"text","optional":true},{"name":"kind","wire":"kind","shape":"text","optional":true},{"name":"limit","wire":"limit","shape":"number","optional":true}],"result":"entries"},{"method":"add","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text"},{"name":"kind","wire":"kind","shape":"text","optional":true},{"name":"title","wire":"title","shape":"text"},{"name":"body","wire":"body","shape":"text"},{"name":"tags","wire":"tags","shape":"text","optional":true}],"result":"entry"},{"method":"forget","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text"},{"name":"id","wire":"id","shape":"text"}],"result":"removed"},{"method":"promoteSkill","parameters":[{"name":"name","wire":"name","shape":"text"}],"result":"skill"},{"method":"discardSkill","parameters":[{"name":"name","wire":"name","shape":"text"}],"result":"discard"},{"method":"disputes","parameters":[],"result":"disputes"},{"method":"resolveDispute","parameters":[{"name":"id","wire":"id","shape":"text"},{"name":"decision","wire":"decision","shape":"text"}],"result":"text"}];
8
+ const REMOTE_INVOCATION_DATA = [{"method":"overview","parameters":[],"result":"overview"},{"method":"list","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text","optional":true},{"name":"query","wire":"query","shape":"text","optional":true},{"name":"kind","wire":"kind","shape":"text","optional":true},{"name":"limit","wire":"limit","shape":"number","optional":true}],"result":"entries"},{"method":"add","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text"},{"name":"kind","wire":"kind","shape":"text","optional":true},{"name":"title","wire":"title","shape":"text"},{"name":"body","wire":"body","shape":"text"},{"name":"tags","wire":"tags","shape":"text","optional":true}],"result":"entry"},{"method":"forget","parameters":[{"name":"project","wire":"project","shape":"text","optional":true},{"name":"scope","wire":"scope","shape":"text"},{"name":"id","wire":"id","shape":"text"}],"result":"removed"},{"method":"promoteSkill","parameters":[{"name":"name","wire":"name","shape":"text"}],"result":"skill"},{"method":"discardSkill","parameters":[{"name":"name","wire":"name","shape":"text"}],"result":"discard"},{"method":"persona","parameters":[],"result":"persona"},{"method":"savePersona","parameters":[{"name":"text","wire":"text","shape":"text"},{"name":"locked","wire":"locked","shape":"flag"}],"result":"persona"},{"method":"disputes","parameters":[],"result":"disputes"},{"method":"resolveDispute","parameters":[{"name":"id","wire":"id","shape":"text"},{"name":"decision","wire":"decision","shape":"text"}],"result":"text"}];
9
9
  // ---- client/card.js ----
10
10
  /**
11
11
  * The tunables card, embedded at the foot of the Memories settings page.
@@ -674,6 +674,7 @@ window.__ModuleLoader__.load({
674
674
  promoted: '已提升',
675
675
  tunables: '配置项',
676
676
  tabMemories: '记忆',
677
+ tabPersona: '画像',
677
678
  tabConfig: '配置',
678
679
  tabDisputes: '待裁决',
679
680
  disputesTitle: '合并时需要你拍板的事',
@@ -689,6 +690,13 @@ window.__ModuleLoader__.load({
689
690
  updated: '更新于',
690
691
  saved: '已保存。',
691
692
  removed: '已删除。',
693
+ personaIntro: '这就是每个会话开头注入的「这个人是谁」画像(<persona> 块)。手动保存后,后台合并默认仍可能按需改写;勾选锁定后,只有你的保存会改变它。',
694
+ personaLock: '锁定画像:后台合并不要自动改写',
695
+ personaLockHint: '锁定只阻止后台合并写入,不影响每个会话的注入。',
696
+ personaPlaceholder: '这个人是谁:工作方式、偏好、不能违反的边界……',
697
+ personaSave: '保存画像',
698
+ personaSaved: '画像已保存。',
699
+ personaBudgetNote: '注入字节预算在「配置」里的 personaMaxBytes 调整(默认 12000);超出预算的部分按行截断。',
692
700
  needTitle: '标题和正文都要填。',
693
701
  },
694
702
  en: {
@@ -720,6 +728,7 @@ window.__ModuleLoader__.load({
720
728
  promoted: 'Promoted',
721
729
  tunables: 'Tunables',
722
730
  tabMemories: 'Memories',
731
+ tabPersona: 'Persona',
723
732
  tabConfig: 'Configuration',
724
733
  tabDisputes: 'Needs review',
725
734
  disputesTitle: 'Decisions consolidation will not make on its own',
@@ -735,6 +744,13 @@ window.__ModuleLoader__.load({
735
744
  updated: 'updated',
736
745
  saved: 'Saved.',
737
746
  removed: 'Deleted.',
747
+ personaIntro: 'This is the "who this user is" profile injected at the start of every conversation (the <persona> block). Saving it by hand still leaves background consolidation free to rewrite it; lock it to make your saves the only writes.',
748
+ personaLock: 'Lock the profile: background consolidation must not rewrite it',
749
+ personaLockHint: 'The lock only stops automatic writes; injection is unchanged.',
750
+ personaPlaceholder: 'Who this person is: how they work, what they prefer, the boundaries they set…',
751
+ personaSave: 'Save profile',
752
+ personaSaved: 'Profile saved.',
753
+ personaBudgetNote: 'The injection byte budget is personaMaxBytes under Configuration (default 12000); text beyond it is cut at a line boundary.',
738
754
  needTitle: 'A title and a body are both required.',
739
755
  },
740
756
  }
@@ -965,6 +981,10 @@ window.__ModuleLoader__.load({
965
981
  const [tab, setTab] = React.useState('memories')
966
982
  const [disputes, setDisputes] = React.useState([])
967
983
  const [draft, setDraft] = React.useState({ scope: 'global', kind: 'fact', title: '', body: '', tags: '' })
984
+ const [personaDraft, setPersonaDraft] = React.useState('')
985
+ const [personaLocked, setPersonaLocked] = React.useState(false)
986
+ const [personaLoaded, setPersonaLoaded] = React.useState(false)
987
+ const [personaBusy, setPersonaBusy] = React.useState(false)
968
988
 
969
989
  const loadOverview = React.useCallback(async () => {
970
990
  if (api === undefined) return
@@ -1014,6 +1034,25 @@ window.__ModuleLoader__.load({
1014
1034
  }
1015
1035
  }, [api])
1016
1036
 
1037
+ const loadPersona = React.useCallback(async () => {
1038
+ if (api === undefined || typeof api.persona !== 'function') return
1039
+ try {
1040
+ const result = await api.persona()
1041
+ setPersonaDraft(result?.text ?? '')
1042
+ setPersonaLocked(result?.locked === true)
1043
+ setPersonaLoaded(true)
1044
+ setError(null)
1045
+ } catch (failure) {
1046
+ setError(errorText(failure))
1047
+ }
1048
+ }, [api])
1049
+
1050
+ // The profile is only read when its tab is opened: it is a document the
1051
+ // user edits, not page furniture.
1052
+ React.useEffect(() => {
1053
+ if (tab === 'persona' && !personaLoaded) void loadPersona()
1054
+ }, [tab, personaLoaded, loadPersona])
1055
+
1017
1056
  React.useEffect(() => { void loadOverview() }, [loadOverview])
1018
1057
  React.useEffect(() => { void loadEntries() }, [loadEntries])
1019
1058
  React.useEffect(() => { void loadDisputes() }, [loadDisputes])
@@ -1051,6 +1090,28 @@ window.__ModuleLoader__.load({
1051
1090
  }
1052
1091
  }
1053
1092
 
1093
+ const onSavePersona = async () => {
1094
+ if (api === undefined || typeof api.savePersona !== 'function') {
1095
+ setError(copy.unavailable)
1096
+ return
1097
+ }
1098
+ setPersonaBusy(true)
1099
+ setNotice(null)
1100
+ try {
1101
+ // One object keyed by the wire fields, like every other Remote call.
1102
+ const result = await api.savePersona({ text: personaDraft, locked: personaLocked })
1103
+ setPersonaDraft(result?.text ?? '')
1104
+ setPersonaLocked(result?.locked === true)
1105
+ setPersonaLoaded(true)
1106
+ setNotice(copy.personaSaved)
1107
+ setError(null)
1108
+ } catch (failure) {
1109
+ setError(errorText(failure))
1110
+ } finally {
1111
+ setPersonaBusy(false)
1112
+ }
1113
+ }
1114
+
1054
1115
  const onForget = async (entry) => {
1055
1116
  if (api === undefined) return
1056
1117
  if (typeof window !== 'undefined' && !window.confirm(copy.confirm)) return
@@ -1251,6 +1312,14 @@ window.__ModuleLoader__.load({
1251
1312
  className: `dshm-tab${tab === 'memories' ? ' dshm-tab-active' : ''}`,
1252
1313
  onClick: () => setTab('memories'),
1253
1314
  }, copy.tabMemories),
1315
+ h('button', {
1316
+ key: 'persona',
1317
+ type: 'button',
1318
+ role: 'tab',
1319
+ 'aria-selected': tab === 'persona',
1320
+ className: `dshm-tab${tab === 'persona' ? ' dshm-tab-active' : ''}${personaLocked ? ' dshm-tab-locked' : ''}`,
1321
+ onClick: () => setTab('persona'),
1322
+ }, personaLocked ? `🔒 ${copy.tabPersona}` : copy.tabPersona),
1254
1323
  h('button', {
1255
1324
  key: 'config',
1256
1325
  type: 'button',
@@ -1294,6 +1363,46 @@ window.__ModuleLoader__.load({
1294
1363
  }),
1295
1364
  ])
1296
1365
 
1366
+ const personaPanel = h('div', { key: 'panel-persona', role: 'tabpanel', className: 'dshm-panel' }, [
1367
+ h('p', { key: 'intro', className: 'dshm-note' }, copy.personaIntro),
1368
+ api === undefined || typeof api.savePersona !== 'function'
1369
+ ? h('p', { key: 'unavailable', className: 'dshm-status dshm-error' }, copy.unavailable)
1370
+ : null,
1371
+ h('textarea', {
1372
+ key: 'text',
1373
+ className: 'dshm-area',
1374
+ rows: 14,
1375
+ value: personaDraft,
1376
+ placeholder: copy.personaPlaceholder,
1377
+ disabled: api === undefined || personaBusy,
1378
+ onChange: (event) => setPersonaDraft(event.target.value),
1379
+ }),
1380
+ h('label', { key: 'lock', className: 'dshm-inline' }, [
1381
+ h('input', {
1382
+ key: 'input',
1383
+ className: 'dshm-check',
1384
+ type: 'checkbox',
1385
+ checked: personaLocked,
1386
+ disabled: api === undefined || personaBusy,
1387
+ onChange: (event) => setPersonaLocked(event.target.checked),
1388
+ }),
1389
+ copy.personaLock,
1390
+ ]),
1391
+ h('p', { key: 'lock-hint', className: 'dshm-note' }, copy.personaLockHint),
1392
+ h('p', { key: 'budget', className: 'dshm-note' }, copy.personaBudgetNote),
1393
+ h('div', { key: 'actions', className: 'dshm-actions' }, [
1394
+ h('button', {
1395
+ key: 'save',
1396
+ type: 'button',
1397
+ className: 'dshm-btn dshm-btn-primary',
1398
+ disabled: personaBusy || api === undefined,
1399
+ onClick: onSavePersona,
1400
+ }, copy.personaSave),
1401
+ ]),
1402
+ notice !== null ? h('p', { key: 'notice', className: 'dshm-status dshm-ok' }, notice) : null,
1403
+ error !== null ? h('p', { key: 'error', className: 'dshm-status dshm-error' }, error) : null,
1404
+ ])
1405
+
1297
1406
  // Only the decisions a pass refused to make alone. Each row is one reading
1298
1407
  // of the disputed text with the change marked in place, and a scope move is
1299
1408
  // stated in the head rather than buried in the reason sentence.
@@ -1344,7 +1453,7 @@ window.__ModuleLoader__.load({
1344
1453
  const children = [head]
1345
1454
  if (overview !== null) children.push(h('p', { key: 'store', className: 'dshm-path' }, `${copy.store}: ${overview.storePath}`))
1346
1455
  children.push(tabList)
1347
- children.push(tab === 'config' ? configPanel : tab === 'disputes' ? disputesPanel : memoriesPanel)
1456
+ children.push(tab === 'config' ? configPanel : tab === 'disputes' ? disputesPanel : tab === 'persona' ? personaPanel : memoriesPanel)
1348
1457
  return h('div', { className: 'dshm-page' }, children)
1349
1458
  }
1350
1459
  }
@@ -1378,6 +1487,7 @@ window.__ModuleLoader__.load({
1378
1487
  '.dshm-input:focus{outline:none;border-color:var(--dsw-alias-brand-primary)}',
1379
1488
  '.dshm-input:disabled{opacity:.6}',
1380
1489
  '.dshm-check{width:16px;height:16px;accent-color:var(--dsw-alias-brand-primary)}',
1490
+ '.dshm-inline{display:flex;align-items:center;gap:8px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary);cursor:pointer}',
1381
1491
  '.dshm-reset{height:26px;padding:0 8px;font:inherit;font-size:12px;border-radius:13px;border:.5px solid var(--dsw-alias-border-l3);background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}',
1382
1492
  '.dshm-reset:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}',
1383
1493
  '.dshm-status{font-size:12px;line-height:18px;margin:0}',
package/lib/config.js CHANGED
@@ -454,7 +454,7 @@ export const Config = z.object({
454
454
  /** Whether a model decides if a judgement-based notice is worth an interruption. */
455
455
  noticeGate: z.boolean().default(true).description('Before raising a notice that has no rule behind it (an undated promise that has been sitting for days), ask a model whether it is worth interrupting for. The default answer is silence: a gate that cannot run, or that fails, suppresses the notice. Rule-based notices (daily digest, backlog warning, a promise whose deadline passed) are never gated.').volatile(),
456
456
  /** Byte budget for the persona block injected ahead of the memory summary. */
457
- personaMaxBytes: z.number().default(1200).description('Byte budget for the persona block (who the user is, in their own words) injected once per conversation ahead of the memory summary. 0 disables the block. Kept separate from the summary budget because the profile is context for the whole turn, not one of the memories being listed.').volatile(),
457
+ personaMaxBytes: z.number().default(12000).description('Byte budget for the persona block (who the user is, in their own words) injected once per conversation ahead of the memory summary. 0 disables the block. The profile is edited in Settings → Memories → Persona; locking it there stops the consolidation pass from rewriting it. Kept separate from the summary budget because the profile is context for the whole turn, not one of the memories being listed.').volatile(),
458
458
  /** Share of a scope above which a query term stops counting as recall evidence. */
459
459
  evidenceMaxDf: z.number().default(DEFAULT_EVIDENCE_MAX_DF).description('A query term that appears in more than this share of one scope does not count towards the recall gate\'s evidence requirement. 0.15 is measured on a real 200-entry store: it catches exactly one term (dsh, 22% of entries) and cuts false admissions by three quarters without changing any of ten labelled probes. 0 disables the discount and restores the pre-2026-10-23 behaviour.').volatile(),
460
460
  /** Local-time windows whose tokens are the expensive ones. */
@@ -515,7 +515,7 @@ export const MEMORIES_SETTINGS_DEFAULTS = {
515
515
  consolidateTimeoutMs: DEFAULT_CONSOLIDATE_TIMEOUT_MS,
516
516
  autoDecide: true,
517
517
  autoDecideMinConfidence: 0.7,
518
- personaMaxBytes: 1200,
518
+ personaMaxBytes: 12000,
519
519
  noticeGate: true,
520
520
  reflectionEnabled: true,
521
521
  noticesEnabled: true,
@@ -621,7 +621,7 @@ export function normalizeSettings(input) {
621
621
  consolidateTimeoutMs: positive(value.consolidateTimeoutMs, DEFAULT_CONSOLIDATE_TIMEOUT_MS),
622
622
  autoDecide: value.autoDecide ?? true,
623
623
  autoDecideMinConfidence: clampUnit(value.autoDecideMinConfidence, 0.7),
624
- personaMaxBytes: positive(value.personaMaxBytes, 1200, 0),
624
+ personaMaxBytes: positive(value.personaMaxBytes, 12000, 0),
625
625
  noticeGate: value.noticeGate ?? true,
626
626
  reflectionEnabled: value.reflectionEnabled ?? true,
627
627
  noticesEnabled: value.noticesEnabled ?? true,
package/lib/index.js CHANGED
@@ -29,7 +29,7 @@ import { MemoryStore, slugify } from './storage.js';
29
29
  import { StateStore, importLegacyState, statePath } from './state.js';
30
30
  import { browseMemories, EXPAND_SEEDS, hubTerms, matchCredit, prefilterEntries, QUALIFIED_SCORE_FACTOR, relatedHits, searchMemories } from './search.js';
31
31
  import { readFile } from 'node:fs/promises';
32
- import { readPersona, renderPersonaBlock, writePersona } from './persona.js';
32
+ import { isPersonaLocked, readPersona, renderPersonaBlock, writePersona } from './persona.js';
33
33
  import { StoreSyncService } from './sync-runtime.js';
34
34
  import { ackNotice, admitNotice, dueNotices, pruneNotices, readNotices, withNotice, writeNotices } from './notices.js';
35
35
  import { systemNotification } from './notify.js';
@@ -2799,9 +2799,16 @@ export class MemoriesRuntime {
2799
2799
  // The profile is a document, not a memory: it is injected as its own block
2800
2800
  // at a known budget, so it is written beside the store rather than into it.
2801
2801
  if (plan.persona !== undefined && plan.persona.trim().length > 0) {
2802
- await writePersona(this.store.memoriesDir, plan.persona).catch((error) => {
2803
- this.log.warn('dsh-cross-memory: could not write the persona profile: %s', error instanceof Error ? error.message : String(error));
2804
- });
2802
+ // A locked profile is the user's document: the pass may still propose a
2803
+ // rewrite, but it must not land one behind their back.
2804
+ if (await isPersonaLocked(this.store.memoriesDir).catch(() => false)) {
2805
+ this.log.info('dsh-cross-memory: persona is locked; the automatic profile update was skipped');
2806
+ }
2807
+ else {
2808
+ await writePersona(this.store.memoriesDir, plan.persona).catch((error) => {
2809
+ this.log.warn('dsh-cross-memory: could not write the persona profile: %s', error instanceof Error ? error.message : String(error));
2810
+ });
2811
+ }
2805
2812
  }
2806
2813
  // Skill drafts are staged, not installed: a background pass must not
2807
2814
  // silently grow the model's skill catalog.
package/lib/persona.js CHANGED
@@ -17,7 +17,7 @@
17
17
  *
18
18
  * @module dsh-cross-memory/persona
19
19
  */
20
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
20
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
21
21
  import { dirname, join } from 'node:path';
22
22
  /** Directory holding the profile, inside the memory store. */
23
23
  export const PERSONA_DIR = 'persona';
@@ -29,6 +29,12 @@ export const PERSONA_MAX_SOURCE_CHARS = 6000;
29
29
  export function personaPath(memoriesDir) {
30
30
  return join(memoriesDir, PERSONA_DIR, 'human.md');
31
31
  }
32
+ /** Marker file that stops the consolidation pass rewriting the profile. */
33
+ export const PERSONA_LOCK_FILE = 'human.lock';
34
+ /** Path of the manual-edit lock marker. */
35
+ export function personaLockPath(memoriesDir) {
36
+ return join(memoriesDir, PERSONA_DIR, PERSONA_LOCK_FILE);
37
+ }
32
38
  /**
33
39
  * Read the profile.
34
40
  *
@@ -110,3 +116,48 @@ export function renderPersonaBlock(body, maxBytes, now = Date.now()) {
110
116
  function byteLength(text) {
111
117
  return Buffer.byteLength(text, 'utf8');
112
118
  }
119
+ /**
120
+ * Whether the user locked the profile against automatic rewrites.
121
+ *
122
+ * The lock is an opt-in marker beside the profile: a missing or empty file
123
+ * means unlocked, so upgrading a store never silently changes the behaviour.
124
+ *
125
+ * @param memoriesDir - the memory store root.
126
+ * @returns whether the consolidation pass must leave the profile alone.
127
+ */
128
+ export async function isPersonaLocked(memoriesDir) {
129
+ const marker = await readFile(personaLockPath(memoriesDir), 'utf8').catch(() => undefined);
130
+ return marker !== undefined && marker.trim().length > 0;
131
+ }
132
+ /**
133
+ * Set or clear the manual-edit lock.
134
+ *
135
+ * The marker carries a timestamp rather than the word "true": it is read as a
136
+ * boolean by {@link isPersonaLocked}, and the timestamp is what a person sees
137
+ * when they open the file to ask when it was locked. The write is atomic for the
138
+ * same reason the profile is.
139
+ *
140
+ * @param memoriesDir - the memory store root.
141
+ * @param locked - whether automatic rewrites are forbidden.
142
+ */
143
+ export async function setPersonaLocked(memoriesDir, locked) {
144
+ const target = personaLockPath(memoriesDir);
145
+ if (!locked) {
146
+ await rm(target, { force: true });
147
+ return;
148
+ }
149
+ await mkdir(dirname(target), { recursive: true });
150
+ const temp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
151
+ await writeFile(temp, `${new Date().toISOString()}\n`, 'utf8');
152
+ await rename(temp, target);
153
+ }
154
+ /**
155
+ * Remove the profile, including the legacy single file, so the next read finds
156
+ * nothing to inject. Used when the editor saves an empty document.
157
+ *
158
+ * @param memoriesDir - the memory store root.
159
+ */
160
+ export async function clearPersona(memoriesDir) {
161
+ await rm(personaPath(memoriesDir), { force: true });
162
+ await rm(join(memoriesDir, LEGACY_PERSONA_FILE), { force: true });
163
+ }
package/lib/remote.js CHANGED
@@ -29,6 +29,7 @@
29
29
  import { existsSync } from 'node:fs';
30
30
  import { join } from 'node:path';
31
31
  import { browseMemories, searchMemories } from './search.js';
32
+ import { clearPersona, isPersonaLocked, readPersona, setPersonaLocked, writePersona } from './persona.js';
32
33
  import { discardDraft, listDrafts, promote } from './skills.js';
33
34
  import { MEMORY_KINDS, toMemoryKind } from './types.js';
34
35
  /** npm package owning the Remote methods. */
@@ -92,6 +93,19 @@ export const REMOTE_INVOCATION_DATA = [
92
93
  parameters: [{ name: 'name', wire: 'name', shape: 'text' }],
93
94
  result: 'discard',
94
95
  },
96
+ {
97
+ method: 'persona',
98
+ parameters: [],
99
+ result: 'persona',
100
+ },
101
+ {
102
+ method: 'savePersona',
103
+ parameters: [
104
+ { name: 'text', wire: 'text', shape: 'text' },
105
+ { name: 'locked', wire: 'locked', shape: 'flag' },
106
+ ],
107
+ result: 'persona',
108
+ },
95
109
  {
96
110
  method: 'disputes',
97
111
  parameters: [],
@@ -220,10 +234,16 @@ function hostCodec(shape) {
220
234
  const view = asRecord(value, 'skill');
221
235
  return { name: asText(view.name, 'skill.name'), path: asText(view.path, 'skill.path') };
222
236
  }
237
+ case 'flag':
238
+ return asFlag(value, 'argument');
223
239
  case 'discard': {
224
240
  const view = asRecord(value, 'discard');
225
241
  return { name: asText(view.name, 'discard.name'), removed: asFlag(view.removed, 'discard.removed') };
226
242
  }
243
+ case 'persona': {
244
+ const view = asRecord(value, 'persona');
245
+ return { text: asText(view.text, 'persona.text'), locked: asFlag(view.locked, 'persona.locked') };
246
+ }
227
247
  case 'disputes': {
228
248
  const view = asRecord(value, 'disputes');
229
249
  return {
@@ -417,6 +437,21 @@ export function createRemoteService(host) {
417
437
  const wanted = (name ?? '').trim();
418
438
  return { name: wanted, removed: await discardDraft(store.memoriesDir, wanted) };
419
439
  },
440
+ async persona() {
441
+ return {
442
+ text: (await readPersona(store.memoriesDir)) ?? '',
443
+ locked: await isPersonaLocked(store.memoriesDir),
444
+ };
445
+ },
446
+ async savePersona(text, locked) {
447
+ const body = (text ?? '').trim();
448
+ if (body.length > 0)
449
+ await writePersona(store.memoriesDir, body);
450
+ else
451
+ await clearPersona(store.memoriesDir);
452
+ await setPersonaLocked(store.memoriesDir, locked === true);
453
+ return { text: body, locked: locked === true };
454
+ },
420
455
  async disputes() {
421
456
  if (host.disputes === undefined)
422
457
  return { disputes: [] };
@@ -167,6 +167,11 @@ function fakeApi(calls, rows = DISPUTES) {
167
167
  calls.push(args);
168
168
  return Promise.resolve('Applied.');
169
169
  },
170
+ persona: () => Promise.resolve({ text: '他先确认再改代码。', locked: false }),
171
+ savePersona: (args) => {
172
+ calls.push(args);
173
+ return Promise.resolve({ text: args.text, locked: args.locked });
174
+ },
170
175
  };
171
176
  }
172
177
  test('the disputes panel accepts and rejects through the Remote API', async () => {
@@ -312,3 +317,25 @@ test('a retirement strikes the body and renders no replacement', async () => {
312
317
  assert.equal(findClass(panel, 'dshm-ins'), undefined, 'nothing replaces a retirement');
313
318
  assert.equal(findClass(panel, 'dshm-del'), undefined);
314
319
  });
320
+ test('the persona tab loads the profile and saves text plus the lock flag', async () => {
321
+ const calls = [];
322
+ const module = await loadSection();
323
+ const { render } = await mountSection(fakeApi(calls), module.SECTION_COPY.zh);
324
+ const memories = await render();
325
+ click(findByText(memories, 'button', '画像'));
326
+ const panel = await render();
327
+ const area = [...walk(panel)].find((element) => element.type === 'textarea');
328
+ assert.equal(area?.props.value, '他先确认再改代码。', 'the stored profile is in the editor');
329
+ (area?.props.onChange)({ target: { value: '新的画像' } });
330
+ const edited = await render();
331
+ const lock = [...walk(edited)].find((element) => element.type === 'input' && element.props.type === 'checkbox');
332
+ assert.equal(lock?.props.checked, false, 'the lock starts from the stored flag');
333
+ (lock?.props.onChange)({ target: { checked: true } });
334
+ const locked = await render();
335
+ assert.equal([...walk(locked)].find((element) => element.type === 'input' && element.props.type === 'checkbox')?.props.checked, true);
336
+ click(findByText(locked, 'button', '保存画像'));
337
+ await new Promise((resolve) => { setTimeout(resolve, 20); });
338
+ assert.deepEqual(calls.at(-1), { text: '新的画像', locked: true }, 'one object with both wire fields');
339
+ const after = await render();
340
+ assert.match(textOf(after), /画像已保存。/u, 'the save is reported');
341
+ });
@@ -62,11 +62,13 @@ test('the daily cap is a guard rail against a runaway trigger', () => {
62
62
  assert.match(verdict.ok === false ? verdict.reason : '', /guard rail/u);
63
63
  });
64
64
  test('quiet hours defer a notice instead of dropping it', () => {
65
- const at22 = Date.parse('2026-10-23T14:00:00Z'); // 22:00 in UTC+8
65
+ // Local-time constructors: quiet hours use the host clock, so an absolute UTC
66
+ // timestamp would only test the machine's timezone (and fail on UTC CI).
67
+ const at22 = new Date(2026, 9, 23, 22, 0, 0).getTime();
66
68
  const due = quietHoursEnd(at22, '22:00-08:00');
67
69
  assert.ok(due > at22, 'held until the window ends');
68
70
  assert.equal(quietHoursEnd(at22, ''), at22, 'no window means no delay');
69
- const daytime = Date.parse('2026-10-23T02:00:00Z'); // 10:00 in UTC+8
71
+ const daytime = new Date(2026, 9, 23, 10, 0, 0).getTime();
70
72
  assert.equal(quietHoursEnd(daytime, '22:00-08:00'), daytime, 'outside the window it fires now');
71
73
  });
72
74
  test('the queue round-trips, delivers once, and expires', async (t) => {
@@ -14,7 +14,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { join } from 'node:path';
16
16
  import test from 'node:test';
17
- import { personaPath, readPersona, renderPersonaBlock, writePersona } from '../persona.js';
17
+ import { clearPersona, isPersonaLocked, personaLockPath, personaPath, readPersona, renderPersonaBlock, setPersonaLocked, writePersona } from '../persona.js';
18
18
  import { MemoryStore } from '../storage.js';
19
19
  import { parsePlan } from '../consolidate.js';
20
20
  test('a profile round-trips through the store directory', async (t) => {
@@ -71,3 +71,16 @@ test('a legacy single-file profile is still read as the human block', async (t)
71
71
  await writeFile(join(dir, 'persona.md'), '旧的单文件画像\n', 'utf8');
72
72
  assert.equal(await readPersona(dir), '旧的单文件画像', 'upgrading does not lose the profile');
73
73
  });
74
+ test('the manual-edit lock is a timestamped marker, and clearing removes the profile', async (t) => {
75
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-lock-'));
76
+ t.after(() => rm(dir, { recursive: true, force: true }));
77
+ assert.equal(await isPersonaLocked(dir), false, 'an untouched store is unlocked');
78
+ await writePersona(dir, '他先确认再改代码。');
79
+ await setPersonaLocked(dir, true);
80
+ assert.equal(await isPersonaLocked(dir), true, 'the marker locks the profile');
81
+ assert.match(await readFile(personaLockPath(dir), 'utf8'), /\d{4}-\d{2}-\d{2}T/u, 'the marker records when it was locked');
82
+ await clearPersona(dir);
83
+ assert.equal(await readPersona(dir), undefined, 'clearing removes the profile the injector reads');
84
+ await setPersonaLocked(dir, false);
85
+ assert.equal(await isPersonaLocked(dir), false, 'unlocking removes the marker');
86
+ });
@@ -86,6 +86,7 @@ test('the wire table and the expanded descriptors agree', () => {
86
86
  // Every shape the browser renders is covered by a codec factory call.
87
87
  assert.ok(seen.has('overview') && seen.has('entries') && seen.has('entry') && seen.has('removed'));
88
88
  assert.ok(seen.has('skill') && seen.has('discard') && seen.has('text') && seen.has('number'));
89
+ assert.ok(seen.has('persona') && seen.has('flag'));
89
90
  });
90
91
  test('the host codecs validate instead of passing values through', () => {
91
92
  const byMethod = new Map(REMOTE_CONTRIBUTION.invocations.map((descriptor) => [descriptor.method, descriptor]));
@@ -102,6 +103,16 @@ test('the host codecs validate instead of passing values through', () => {
102
103
  assert.equal(numberCodec?.create().parse(10), 10);
103
104
  assert.throws(() => numberCodec?.create().parse('10'), /must be a number/u);
104
105
  });
106
+ test('the settings page can read, save and lock the persona profile', async (t) => {
107
+ const { store, dshHome } = await roots(t);
108
+ const service = createRemoteService({ store, dshHome });
109
+ assert.deepEqual(await service.persona(), { text: '', locked: false }, 'an empty store has no profile');
110
+ const saved = await service.savePersona('他先确认再改代码。', true);
111
+ assert.deepEqual(saved, { text: '他先确认再改代码。', locked: true });
112
+ assert.deepEqual(await service.persona(), saved, 'the saved document and its lock are read back');
113
+ await service.savePersona('', false);
114
+ assert.deepEqual(await service.persona(), { text: '', locked: false }, 'saving an empty document clears it');
115
+ });
105
116
  test('the settings page can list and resolve the decisions waiting for a person', async (t) => {
106
117
  const { store, dshHome } = await roots(t);
107
118
  const seen = [];
@@ -53,7 +53,7 @@ function entryText(id, body, updated) {
53
53
  async function twoWayFixture() {
54
54
  const base = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-sync-'));
55
55
  const remote = join(base, 'remote.git');
56
- execFileSync('git', ['init', '--bare', '--quiet', remote]);
56
+ execFileSync('git', ['init', '--bare', '--quiet', '-b', 'main', remote]);
57
57
  const left = join(base, 'left');
58
58
  const right = join(base, 'right');
59
59
  await mkdir(join(left, 'entries'), { recursive: true });
@@ -6,6 +6,10 @@ export declare const LEGACY_PERSONA_FILE = "persona.md";
6
6
  export declare const PERSONA_MAX_SOURCE_CHARS = 6000;
7
7
  /** Path of the profile. */
8
8
  export declare function personaPath(memoriesDir: string): string;
9
+ /** Marker file that stops the consolidation pass rewriting the profile. */
10
+ export declare const PERSONA_LOCK_FILE = "human.lock";
11
+ /** Path of the manual-edit lock marker. */
12
+ export declare function personaLockPath(memoriesDir: string): string;
9
13
  /**
10
14
  * Read the profile.
11
15
  *
@@ -41,3 +45,32 @@ export declare function writePersona(memoriesDir: string, body: string): Promise
41
45
  * @returns the framed block, or `undefined` when there is nothing to show.
42
46
  */
43
47
  export declare function renderPersonaBlock(body: string | undefined, maxBytes: number, now?: number): string | undefined;
48
+ /**
49
+ * Whether the user locked the profile against automatic rewrites.
50
+ *
51
+ * The lock is an opt-in marker beside the profile: a missing or empty file
52
+ * means unlocked, so upgrading a store never silently changes the behaviour.
53
+ *
54
+ * @param memoriesDir - the memory store root.
55
+ * @returns whether the consolidation pass must leave the profile alone.
56
+ */
57
+ export declare function isPersonaLocked(memoriesDir: string): Promise<boolean>;
58
+ /**
59
+ * Set or clear the manual-edit lock.
60
+ *
61
+ * The marker carries a timestamp rather than the word "true": it is read as a
62
+ * boolean by {@link isPersonaLocked}, and the timestamp is what a person sees
63
+ * when they open the file to ask when it was locked. The write is atomic for the
64
+ * same reason the profile is.
65
+ *
66
+ * @param memoriesDir - the memory store root.
67
+ * @param locked - whether automatic rewrites are forbidden.
68
+ */
69
+ export declare function setPersonaLocked(memoriesDir: string, locked: boolean): Promise<void>;
70
+ /**
71
+ * Remove the profile, including the legacy single file, so the next read finds
72
+ * nothing to inject. Used when the editor saves an empty document.
73
+ *
74
+ * @param memoriesDir - the memory store root.
75
+ */
76
+ export declare function clearPersona(memoriesDir: string): Promise<void>;
@@ -11,6 +11,10 @@ export type WireShape =
11
11
  'text'
12
12
  /** A numeric parameter. */
13
13
  | 'number'
14
+ /** A boolean flag parameter. */
15
+ | 'flag'
16
+ /** The persona profile plus whether it is locked against automatic rewrites. */
17
+ | 'persona'
14
18
  /** Store home, per-project counts, staged skill drafts. */
15
19
  | 'overview'
16
20
  /** A ranked entry page plus the total before paging. */
@@ -199,11 +203,20 @@ export interface MemoriesRemote {
199
203
  readonly name: string;
200
204
  readonly removed: boolean;
201
205
  }>;
206
+ persona(): Promise<PersonaView>;
207
+ savePersona(text?: string, locked?: boolean): Promise<PersonaView>;
202
208
  disputes(): Promise<{
203
209
  readonly disputes: readonly DisputeView[];
204
210
  }>;
205
211
  resolveDispute(id?: string, decision?: string): Promise<string>;
206
212
  }
213
+ /** The persona profile as the settings page edits it. */
214
+ export interface PersonaView {
215
+ /** Stored markdown, empty when no profile exists yet. */
216
+ readonly text: string;
217
+ /** Whether automatic consolidation must leave the profile alone. */
218
+ readonly locked: boolean;
219
+ }
207
220
  /** One consolidation decision, as the settings page renders it. */
208
221
  export interface DisputeView {
209
222
  readonly id: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-cross-memory",
3
3
  "description": "Cross-session memory for the DeepSeek Harness: project-scoped and global memories with an explicit memory tool, idle-time background extraction, consolidation, and layered summary injection",
4
- "version": "0.2.0",
4
+ "version": "0.2.1",
5
5
  "private": false,
6
6
  "publishConfig": {
7
7
  "access": "public"