sage-mem 2.33.3 → 3.0.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.
package/lib/index.js CHANGED
@@ -38,6 +38,9 @@ import { checkUpdate as checkUpdateImpl } from './update.js'
38
38
  import { applySettingsPatch, MAX_RAW_BYTES, parseExperimentalPatch, parseUiPatch, pendingExperimental, pendingUi, rawName, readExternalSettings, readReservedFile, readSettingsFileDetailed, readSettingsSnapshot, RESERVED_FILE, SETTINGS_FILE } from './settings.js'
39
39
  import { createRecallInjector, createSessionInjectState, readRecallDebug } from './recall/index.js'
40
40
  import { mountAutodream, mountMemoryTools, mountMirror, mountObserve, mountPreCompact, mountWriteGate } from './assembly/index.js'
41
+ import { ensureLocalInstance } from './sync/instance.js'
42
+ // 3.0.0:跨设备冲突的裁决实现(`conflict/applyResolution` 背后的那一步)。
43
+ import { resolveSyncConflict } from './sync/resolve.js'
41
44
 
42
45
  /**
43
46
  * 读方法的拒绝:**抛**一个带 `.code` 的 Error(写方法返回 `{ok:false, code}` 回执,见 prepareWrite)。
@@ -73,7 +76,12 @@ export class MemoryGateway extends TypertRemoteService {
73
76
  // 2.0.0:冲突裁决入口(列表 / 读 / 标失效 / 驳回 / 撤销 / 删除记录)—— conflict.* 服务。
74
77
  // 与 memory / starmap 分开成独立 namespace:混成一个面会让「读记忆」与「改记忆的有效性」
75
78
  // 共用一张契约表,而后者是**写用户文件**的动作。
76
- new ConflictGateway(ctx)
79
+ //
80
+ // 3.0.0:把**本类的写盘能力**以函数形式交给它(`applyResolution` 的「留远端」要把正文写回本地)。
81
+ // 为什么走参数而不是在 ConflictGateway 里 `ctx.get('memory')`:此刻正在注册这个服务本身
82
+ // (与 tools-mount.js 头注同一条时序事实 —— 构造期读自己会拿到 undefined 或半成品)。
83
+ // 也不许在 lib/sync/ 里另写一份带 `expectedRevision` 的写盘:一条记忆的落盘口径只该有一处。
84
+ new ConflictGateway(ctx, (name, content, opts) => this.writeFile(name, content, opts))
77
85
 
78
86
  // 四块挂载(1.2.0 从构造函数里搬出的四段)。顺序保持原样:
79
87
  // autodream → 检索工具 → 观测 → 写入门。
@@ -92,6 +100,12 @@ export class MemoryGateway extends TypertRemoteService {
92
100
  // 2.17.0:压缩前提醒(实验性,默认关;关着时每步只是一次开关读取)。
93
101
  mountPreCompact(ctx, { memoryDir: MEMORY_DIR })
94
102
 
103
+ // 3.0.0:本机设备身份(`<状态根>/instance.json`,只记 id / 机器名 / 创建时间)。
104
+ // **必须在装配期建好**:别的机器要推给我时,写入门第二道要能在我的状态根里读到它;
105
+ // 只在「我自己推送」时才创建,会让一台只收不推的机器永远收不到东西。
106
+ // 失败不阻断(只读盘 / 权限):后果只是别人推给我时要多确认一次,那是可接受的降级。
107
+ ensureLocalInstance(STATE_ROOT).catch(() => {})
108
+
95
109
  // 2.25.0:外部访问读侧(白名单导出 + 只读 MCP)。默认关,关着时一行都不跑。
96
110
  // `readExternal` 给的是**现读**设置(不进 restartRequired):开关改完立刻起停。
97
111
  this.mirror = mountMirror(ctx, { memoryDir: MEMORY_DIR, stateRoot: STATE_ROOT, readExternal: readExternalSettings })
@@ -578,7 +592,16 @@ markRemote(StarmapGateway, 'readFile', 'readFile')
578
592
  * `fs.writeText`:版本守卫 + 逐次沙箱策略(收窄到记忆目录),与 autodream 同一口径。
579
593
  */
580
594
  export class ConflictGateway extends TypertRemoteService {
581
- constructor(ctx) { super(ctx, 'conflict') }
595
+ /**
596
+ * @param {object} ctx
597
+ * @param {(name: string, content: string, opts?: object) => Promise<object>} [writeMemory]
598
+ * 记忆正文的写通道(本类 `MemoryGateway.writeFile`,三条闸门 + 版本守卫都在那边)。
599
+ * 只在 `applyResolution` 的「留远端」分支用到;缺了就回 `unsupported`,绝不自己另写一份。
600
+ */
601
+ constructor(ctx, writeMemory) {
602
+ super(ctx, 'conflict')
603
+ this.writeMemory = typeof writeMemory === 'function' ? writeMemory : null
604
+ }
582
605
 
583
606
  /** 解析「这次要标的是哪一方」:只能是记录里的 file 或 otherFile,否则 null。 */
584
607
  targetOf(record, requested) {
@@ -742,6 +765,66 @@ export class ConflictGateway extends TypertRemoteService {
742
765
  if (!removed.ok) return { ok: false, code: removed.code, error: removed.error }
743
766
  return { ok: true }
744
767
  }
768
+
769
+ /**
770
+ * 3.0.0:裁决一条**跨设备**冲突(`docs/3.0.0-arbitration-ui.md` §3.4)。
771
+ *
772
+ * 三条出路,判据是「保留哪一份」(不是「操作谁」):
773
+ * - `local` —— 保本地那份,把本地正文推到远端(远端在这期间又变过就 STALE,一个字不写)
774
+ * - `remote` —— 保远端那份,把远端正文写回本地(带 `expectedRevision`,本地被改过就拒)
775
+ * - `manual` —— 人自己改,插件一个字节都不写
776
+ *
777
+ * 这一层只做三件事:把 id / choice 收成字符串、把**写盘通道**注进去、把回来的收据补齐成
778
+ * 结果 schema 的形状。判断全在 `lib/sync/resolve.js`(状态机、基线、上行协议都在那里,
779
+ * 单测 `test/sync-arbitration-test.mjs` 逐条守着)—— 这里再判一遍就是第二个真相源。
780
+ *
781
+ * 失败**不抛**:`{ ok:false, code, error }` 与其余六条同一种回执风格。同时六个「回声」字段
782
+ * (choice / wrote / baseUpdated / status / recordId)一个都不省 —— 结果 schema 里它们必填,
783
+ * 而界面要靠 `wrote` 说清「已经写到远端了,只是记录没改成」这种半态,不能在传输层被 strip。
784
+ */
785
+ async applyResolution(opts) {
786
+ const id = typeof opts?.id === 'string' ? opts.id : ''
787
+ const choice = String(opts?.choice ?? '')
788
+ let res
789
+ try {
790
+ res = await resolveSyncConflict({
791
+ id,
792
+ choice,
793
+ memoryDir: MEMORY_DIR,
794
+ stateRoot: STATE_ROOT,
795
+ // 拿不到写通道时**照样调**:resolve 会把 `remote` 这一支判成 `unsupported`,
796
+ // 而 `local` / `manual` 不需要它(少一条通道不该让另外两条路也走不通)。
797
+ deps: { writeMemory: this.writeMemory ?? undefined },
798
+ })
799
+ } catch (err) {
800
+ return {
801
+ ok: false,
802
+ code: 'sync_failed',
803
+ error: `错误:sync_failed — ${err?.message ?? err}`,
804
+ choice,
805
+ wrote: 'none',
806
+ baseUpdated: false,
807
+ status: '',
808
+ recordId: id,
809
+ }
810
+ }
811
+ const receipt = {
812
+ ok: res?.ok === true,
813
+ choice: String(res?.choice ?? choice),
814
+ // 只有 resolve 明确说过的那两个值才算「写成了」;其余一律 `none`(不猜)。
815
+ wrote: res?.wrote === 'remote' || res?.wrote === 'local' ? res.wrote : 'none',
816
+ baseUpdated: res?.baseUpdated === true,
817
+ status: String(res?.status ?? ''),
818
+ recordId: String(res?.recordId ?? id),
819
+ }
820
+ // 基线写不进去是**部分成功**:文件已经写成,所以 baseError 与 code / error 分开报。
821
+ if (res?.baseError) receipt.baseError = String(res.baseError)
822
+ if (!receipt.ok) {
823
+ receipt.code = String(res?.code ?? 'sync_failed')
824
+ receipt.error = String(res?.error ?? `错误:${receipt.code} — 裁决没有完成`)
825
+ }
826
+ return receipt
827
+ }
745
828
  }
746
829
 
747
830
  markRemote(ConflictGateway, 'list', 'list')
@@ -750,9 +833,12 @@ markRemote(ConflictGateway, 'invalidate', 'invalidate')
750
833
  markRemote(ConflictGateway, 'dismiss', 'dismiss')
751
834
  markRemote(ConflictGateway, 'undo', 'undo')
752
835
  markRemote(ConflictGateway, 'removeRecord', 'removeRecord')
836
+ markRemote(ConflictGateway, 'applyResolution', 'applyResolution')
753
837
 
754
838
  // 2.1.8(N02):裁决入口整段按冲突 id 串行(第二方进队后重新读状态;理由见 util.js 的 serializeByKey)。
755
- serializeByKey(ConflictGateway, ['invalidate', 'dismiss', 'undo', 'removeRecord'])
839
+ // 3.0.0 的 `applyResolution` 一并纳入:它同样「先读记录、再写文件、再改记录」,
840
+ // 两次并发点击若各自读到 open,就会各写一次正文(远端那一条甚至会被推两次)。
841
+ serializeByKey(ConflictGateway, ['invalidate', 'dismiss', 'undo', 'removeRecord', 'applyResolution'])
756
842
 
757
843
  /**
758
844
  * autodream 的 remote 面:设置页「自动做梦」标签页唯一的数据通道。
@@ -131,25 +131,44 @@ function scheduleLeaseRetry() {
131
131
  if (typeof leaseRetryTimer.unref === 'function') leaseRetryTimer.unref()
132
132
  }
133
133
 
134
+ /**
135
+ * 把一条增量并进已有条目 —— **合并语义只有这一份**。
136
+ *
137
+ * `injected` / `read` 取**较晚**的(它们是「最近一次」);`readRev` 跟着 `read` 走
138
+ * (谁把 `read` 推新,就用谁那份 revision)。
139
+ *
140
+ * 为什么单独一个函数:这套语义原先在四处各写一遍(内存累计、落盘合并、写失败重排队、
141
+ * 读盘归一)。四处少一处就会让同一个键在不同环节得到不同答案,而台账是自动归档阈值
142
+ * **唯一**的数据源 —— 那类偏差不会抛错,只会让某条记忆的闲置天数悄悄算错。
143
+ */
144
+ function mergePatch(cur, patch) {
145
+ const read = Math.max(cur.read ?? 0, patch.read ?? 0)
146
+ return {
147
+ injected: Math.max(cur.injected ?? 0, patch.injected ?? 0),
148
+ read,
149
+ readRev: read > 0 && read === (patch.read ?? 0) && patch.readRev ? patch.readRev : (cur.readRev ?? ''),
150
+ }
151
+ }
152
+
134
153
  /**
135
154
  * 把一次观测并进内存增量表。
136
155
  *
137
156
  * 为什么是「增量」而不是「整条时间戳」:v2 有四个字段,同一批里可能先记注入、再记读取。
138
157
  * 直接 `set(name, at)` 会让后写的把先写的**冲掉** —— 那正是旧版台账丢计时的那类问题。
139
158
  *
140
- * 各字段的合并语义**不一样**,写错就会丢数据:
141
- * - `injected` / `read`:取**较晚**的(它们是「最近一次」);
142
- * - `readRev`:跟着 `read` 走(谁把 `read` 推新,就用谁那份 revision)。
159
+ * ⚠️ **键一律走 `nameKey`**(`memory/naming.js` 的唯一名字基准),不存调用方给的原文。
160
+ * 存原文会有两个后果,都不是崩溃而是**静默失配**:
161
+ * - `MEMORY.MD` 与 `memory.md` 会各占一个键,而读侧(`reconcile` / `idleDays`)只会去查
162
+ * 其中一个 —— 名字带大写的那条记忆就永远「没被用过」;
163
+ * - 键可能带目录成分(`../MEMORY.md`),而回收死键那一步是
164
+ * `stat(join(memoryDir, key))` —— 那等于让一个外部字符串决定 stat 的目标。
165
+ * 两者都由 `nameKey` 的 `basename(...).toLowerCase()` 一并挡住。
143
166
  */
144
167
  function record(name, patch) {
145
168
  if (typeof name !== 'string' || !name) return
146
- const cur = pending.get(name) ?? {}
147
- const read = Math.max(cur.read ?? 0, patch.read ?? 0)
148
- pending.set(name, {
149
- injected: Math.max(cur.injected ?? 0, patch.injected ?? 0),
150
- read,
151
- readRev: read > 0 && read === (patch.read ?? 0) && patch.readRev ? patch.readRev : (cur.readRev ?? ''),
152
- })
169
+ const key = nameKey(name)
170
+ if (!key) return
171
+ pending.set(key, mergePatch(pending.get(key) ?? {}, patch))
153
172
  scheduleFlush()
154
173
  }
155
174
 
@@ -203,7 +222,16 @@ export async function readAccessLedger(file = ACCESS_LEDGER_FILE) {
203
222
  for (const [k, v] of Object.entries(src)) {
204
223
  if (typeof k !== 'string' || !k) continue
205
224
  if (!Number.isFinite(v) && !(v && typeof v === 'object' && !Array.isArray(v))) continue
206
- out[k] = ledgerEntry(v)
225
+ /**
226
+ * 键也归一(`nameKey`)—— 台账在磁盘上是**既有数据**,里面可能存着 `Project_X.md`
227
+ * 这种写法,也可能被人手改出带路径的键。返回原文会让它在内存里与写侧的新键并成两份,
228
+ * 而查侧只认其中一份(症状:那条记忆的闲置天数回落成 mtime)。
229
+ * 两条键撞到同一个 nameKey 时按同一套合并语义并成一条,不丢更晚的时间戳。
230
+ */
231
+ const key = nameKey(k)
232
+ if (!key) continue
233
+ const entry = ledgerEntry(v)
234
+ out[key] = out[key] ? mergePatch(out[key], entry) : entry
207
235
  }
208
236
  return out
209
237
  } catch {
@@ -227,7 +255,10 @@ async function currentMemoryNames(memoryDir) {
227
255
  let unknown = false
228
256
  const collect = async (dir) => {
229
257
  const entries = await readdir(dir, { withFileTypes: true })
230
- for (const e of entries) if (e.isFile() && isMemoryEntry(e.name)) out.add(e.name)
258
+ // 键按 `nameKey` 归一(与 `record` 写进去的键同一基准):台账的键是小写规范形,
259
+ // 而磁盘上的名字可能带大写(`Project_X.md`)。拿原文去比对会让这类键在大小写敏感的卷上
260
+ // 每一轮 flush 都被判成死键删掉 —— 计时就这么没了,且没有任何信号。
261
+ for (const e of entries) if (e.isFile() && isMemoryEntry(e.name)) out.add(nameKey(e.name))
231
262
  }
232
263
  // 记忆根目录:**任何**读失败(含 ENOENT)都算「不知道」。
233
264
  // 根目录不存在不等于「记忆都没了」,而是「这个路径根本不是记忆目录」——参数传错、
@@ -289,16 +320,11 @@ async function flushAccessLocked(memoryDir) {
289
320
  batch = pending
290
321
  pending = new Map()
291
322
  const onDisk = await readAccessLedger(file)
292
- // 逐字段合并(`readAccessLedger` 已经归一成 v2 条目,不用再分代)。
293
- // 语义与内存里的 `record` 一致:时间戳取较晚、`readRev` 跟 `read` 走。
323
+ // 逐字段合并(`readAccessLedger` 已经归一成 v2 条目、键也已按 nameKey 归一,不用再分代)。
324
+ // 语义与内存里的 `record` 一致:时间戳取较晚、`readRev` 跟 `read` 走 —— 同一套 `mergePatch`。
294
325
  for (const [name, patch] of batch) {
295
326
  const cur = onDisk[name] ?? { injected: 0, read: 0, readRev: '' }
296
- const read = Math.max(cur.read ?? 0, patch.read ?? 0)
297
- onDisk[name] = {
298
- injected: Math.max(cur.injected ?? 0, patch.injected ?? 0),
299
- read,
300
- readRev: read > 0 && read === (patch.read ?? 0) && patch.readRev ? patch.readRev : (cur.readRev ?? ''),
301
- }
327
+ onDisk[name] = mergePatch(cur, patch)
302
328
  }
303
329
  if (alive) {
304
330
  for (const key of Object.keys(onDisk)) {
@@ -323,13 +349,7 @@ async function flushAccessLocked(memoryDir) {
323
349
  } catch (err) {
324
350
  // 放回内存时**逐字段并回去**,不能整条覆盖 —— 否则失败重试会把期间新攒的字段冲掉。
325
351
  for (const [name, patch] of batch ?? []) {
326
- const cur = pending.get(name) ?? {}
327
- const read = Math.max(cur.read ?? 0, patch.read ?? 0)
328
- pending.set(name, {
329
- injected: Math.max(cur.injected ?? 0, patch.injected ?? 0),
330
- read,
331
- readRev: read > 0 && read === (patch.read ?? 0) && patch.readRev ? patch.readRev : (cur.readRev ?? ''),
332
- })
352
+ pending.set(name, mergePatch(pending.get(name) ?? {}, patch))
333
353
  }
334
354
  if (debugEnabled()) console.warn(`sage-mem: access ledger flush failed: ${err?.message ?? err}`)
335
355
  return { ok: false, error: err?.message ?? String(err) }
@@ -366,7 +386,9 @@ export function fileType(f) {
366
386
  export function idleDays(f, ledger = {}, now = Date.now()) {
367
387
  // 走 `injectedAt` 而不是直接读值:手写的 v1 台账(裸数字)与 v2 条目都能收,
368
388
  // 调用方不必分代 —— 归档候选的计算不该因为台账升了一代就整体失效。
369
- const seen = injectedAt(ledger?.[f?.file])
389
+ // 查表按 `nameKey`:台账的键是那个基准(见 `record`),这里拿原文查会漏掉名字带大写的条目,
390
+ // 于是它的闲置天数悄悄回落到 updated / mtime —— 自动归档阈值就此算错。
391
+ const seen = injectedAt(ledger?.[nameKey(f?.file ?? '')])
370
392
  const fromMeta = Date.parse(f?.updated || '')
371
393
  const base = Number.isFinite(seen)
372
394
  ? seen
@@ -18,7 +18,7 @@
18
18
  import { ARCHIVE_DIR_NAME, addArchiveMeta, inspectDir, inspectMemoryEntry, localStamp, readArchivedMeta, scanArchived, shadowsReserved, stripArchiveMeta } from './scan.js'
19
19
  import { isReserved, nameKey, safeName } from './naming.js'
20
20
  import { parseFrontmatter } from './frontmatter.js'
21
- import { revisionOf } from './chunks.js'
21
+ import { revisionOfText } from './chunks.js'
22
22
  import { retireTaken, returnSource, takeOverSource, writeFileAtomic, writeFileExclusive } from './util.js'
23
23
  import { readLockState } from './lock.js'
24
24
  import { ensureIndexEntry, dropIndexEntry } from './index-file.js'
@@ -386,7 +386,7 @@ export async function restoreMemory(memoryDir, name) {
386
386
  *
387
387
  * 身份由两半组成,缺一不可:
388
388
  * · `archived_rev`(每次归档新生成的随机标记)→ 同分钟重新归档也绝不复用;
389
- * · `revisionOf(去掉留痕的正文)`(sha256 前 12 位)→ 正文被改过(哪怕代次没变)立刻失配。
389
+ * · `revisionOfText(去掉留痕的正文)`(sha256 前 12 位)→ 正文被改过(哪怕代次没变)立刻失配。
390
390
  * 两半都在**盘上的字节**上算,调用方只能交回「它看见的那一份」的身份 ——
391
391
  * 服务端拿它核对,界面上的二次确认只是交互,不是判据。
392
392
  *
@@ -398,7 +398,7 @@ export async function restoreMemory(memoryDir, name) {
398
398
  export function archivedRevisionOf(content) {
399
399
  const src = String(content ?? '')
400
400
  const meta = readArchivedMeta(src)
401
- return `${meta.archivedRev || ''}@${revisionOf(stripArchiveMeta(src))}`
401
+ return `${meta.archivedRev || ''}@${revisionOfText(stripArchiveMeta(src))}`
402
402
  }
403
403
 
404
404
  /**
@@ -33,13 +33,26 @@ export const CHUNK_MAX_CHARS = 900
33
33
  export const CHUNK_MIN_CHARS = 60
34
34
 
35
35
  /**
36
- * 内容 revision:`sha256:<前 12 位>`。
36
+ * 内容 revision(**短展示形**):`sha256:<前 12 位>`,入参是**字符串正文**。
37
37
  *
38
38
  * 12 位十六进制 = 48 bit,对本场景(一份记忆目录内区分版本)绰绰有余,而短到能塞进
39
39
  * 注入的状态卡与工具响应里不心疼。**它只表示「内容变了」,不表示「更新了」** ——
40
40
  * 加一行注释也会换 revision,这不是错误信息,是「你之前读到的正文已经不是现在这份」。
41
+ *
42
+ * ── 为什么这个名字(2.33.4 改名,别改回去)──
43
+ * 仓库里有两个同源但**不能互换**的 revision:
44
+ * · 本函数 `revisionOfText(string)` → `sha256:<12 位>`,**展示 / 缓存域**(工具文本、检索缓存);
45
+ * · `memory/write-protocol.js` 的 `revisionOfBytes(Buffer)` → **64 位裸 hex**,**写守卫域**
46
+ * (`expectedRevision` / 删除确认)。
47
+ * 两者算的是**同一份字节的 sha256**:本函数的 12 位就是 `revisionOfBytes` 返回值的前 12 位。
48
+ * 唯一差别是**入参类型**与**截断方式**。改名前两个函数都叫 `revisionOf`,且都不校验入参类型 ——
49
+ * 把短形交回 `expectedRevision` 不会抛异常,只会得到一个「看起来正常、值却对不上」的字符串,
50
+ * 表现为一次永远失败或永不放过的版本守卫。名字里带上 `Text` / `Bytes`,搬错调用点就不再无声。
51
+ *
52
+ * @param {string} content — 正文(非字符串按空串算,见下方 `String(content ?? '')`)
53
+ * @returns {string} `sha256:<12 位十六进制>`
41
54
  */
42
- export function revisionOf(content) {
55
+ export function revisionOfText(content) {
43
56
  const hex = createHash('sha256').update(String(content ?? ''), 'utf8').digest('hex')
44
57
  return `sha256:${hex.slice(0, 12)}`
45
58
  }
@@ -69,7 +82,7 @@ export function frontmatterEndLine(lines) {
69
82
  export function chunkFile(f, knownRevision) {
70
83
  const file = String(f?.file ?? '')
71
84
  const content = String(f?.content ?? '')
72
- const revision = typeof knownRevision === 'string' && knownRevision ? knownRevision : revisionOf(content)
85
+ const revision = typeof knownRevision === 'string' && knownRevision ? knownRevision : revisionOfText(content)
73
86
  const lines = content.split(/\r?\n/)
74
87
  const from = frontmatterEndLine(lines)
75
88
  const out = []
@@ -81,6 +81,13 @@ export const CONFLICT_FIELD_LIMITS = Object.freeze({
81
81
  note: 4096,
82
82
  tool: 256,
83
83
  version: 256,
84
+ // 3.0.0 追加字段(同样是只增不改,`v` 仍是 1):`origin` 是「这条冲突是谁造的」,
85
+ // 它只可能是 `sync` / `autodream` / `manual` 之一(或不认识的同类短标识),16 字节够装;
86
+ // `host` / `remotePath` 只在 `origin === 'sync'` 时有值,照 `file` 那一档给 512 ——
87
+ // 远端记忆目录是真的会长,而这两个字段短到 48 字节就会把「哪台机器、哪个目录」切没。
88
+ origin: 16,
89
+ host: 512,
90
+ remotePath: 512,
84
91
  })
85
92
 
86
93
  /**
@@ -222,7 +229,8 @@ function shortDigest(parts) {
222
229
  *
223
230
  * 截断:各字段按 `CONFLICT_FIELD_LIMITS` 卡字节,截过就置 `truncated: true`。
224
231
  *
225
- * @param {{kind?, file?, expectedVersion?, actualVersion?, incoming?, onDisk?, note?, tool?, at?, id?}} input
232
+ * @param {{kind?, file?, expectedVersion?, actualVersion?, incoming?, onDisk?, note?, tool?,
233
+ * origin?, host?, remotePath?, at?, id?}} input
226
234
  */
227
235
  export function buildConflict(input) {
228
236
  const src = input && typeof input === 'object' ? input : {}
@@ -245,14 +253,24 @@ export function buildConflict(input) {
245
253
  const tool = clampText(src.tool, CONFLICT_FIELD_LIMITS.tool)
246
254
  const expectedVersion = clampText(versionText(src.expectedVersion), CONFLICT_FIELD_LIMITS.version)
247
255
  const actualVersion = clampText(versionText(src.actualVersion), CONFLICT_FIELD_LIMITS.version)
256
+ // 3.0.0 追加的来源三分。`origin` 不认识的字符串**原样保留**(与 `kind` 同一套哲学:
257
+ // 静默归一成某个已知值等于把「未知」伪装成「已知」);`host` / `remotePath` 只在
258
+ // `origin === 'sync'` 时有意义,别的来源传进来也照存(不替调用方做语义裁剪)。
259
+ const origin = clampText(src.origin, CONFLICT_FIELD_LIMITS.origin)
260
+ const host = clampText(src.host, CONFLICT_FIELD_LIMITS.host)
261
+ const remotePath = clampText(src.remotePath, CONFLICT_FIELD_LIMITS.remotePath)
248
262
 
249
263
  const truncated =
250
264
  file.cut || otherFile.cut || invalidatedFile.cut || decision.cut || appliedVersion.cut ||
251
- incoming.cut || onDisk.cut || note.cut || tool.cut || expectedVersion.cut || actualVersion.cut
265
+ incoming.cut || onDisk.cut || note.cut || tool.cut || expectedVersion.cut || actualVersion.cut ||
266
+ origin.cut || host.cut || remotePath.cut
252
267
 
253
268
  const stamp = compactStamp(at)
254
269
  // ⚠️ `otherFile` **只在非空时**进指纹:空串也拼进去的话,所有 1.x 老种类的 id 都会变 ——
255
270
  // 老记录还在盘上、新记录的 id 换了,就成了「同一件事两个身份」。
271
+ // ⚠️ 3.0.0 的 `origin` / `host` / `remotePath` **不进指纹**:它们描述的是「谁先撞上这件事」,
272
+ // 不是「冲突本身」。同一起冲突先被同步发现、再被 autodream 撞见,仍然是**一条**记录
273
+ // (`sameConflict` 是去重判据 —— 让它因为来源不同就判成两件事,跟这条指纹同一个病)。
256
274
  const digestParts = [kind, file.text, expectedVersion.text, actualVersion.text, incoming.text, onDisk.text]
257
275
  if (otherFile.text) digestParts.push(otherFile.text)
258
276
  const digest = shortDigest(digestParts)
@@ -277,6 +295,10 @@ export function buildConflict(input) {
277
295
  decidedAt,
278
296
  appliedVersion: appliedVersion.text,
279
297
  invalidatedFile: invalidatedFile.text,
298
+ // 3.0.0:来源(尾部追加,与 2.0.0 追加 `otherFile` / `decision` 同一个姿势)。
299
+ origin: origin.text,
300
+ host: host.text,
301
+ remotePath: remotePath.text,
280
302
  }
281
303
  }
282
304
 
@@ -381,6 +403,25 @@ export async function writeConflict(record, opts) {
381
403
  return { ok: true, bytes: Buffer.byteLength(text, 'utf8'), path, truncated }
382
404
  }
383
405
 
406
+ /**
407
+ * 老记录(≤ 2.x)**没有** 3.0.0 追加的三个来源键:读出来一律补成空串。
408
+ *
409
+ * 为什么不留给调用方各自兜底:`readConflict` 的 `record` 与 `listConflicts` 的 `items`
410
+ * 会被面板、注入侧、测试一起消费,每个消费点写一遍 `?? ''` 早晚漏一处 —— 而漏掉的那处
411
+ * 表现成「有 origin 的是 string、没有的是 undefined」:`=== 'sync'` 这类比较看不出问题,
412
+ * 走 `typeof` / `startsWith` 的分支却会崩。
413
+ *
414
+ * 三个键都**只补不覆盖**:有值就逐字保留(包括不认识的 origin,见 `buildConflict`)。
415
+ */
416
+ function withOriginFields(record) {
417
+ return {
418
+ ...record,
419
+ origin: typeof record.origin === 'string' ? record.origin : '',
420
+ host: typeof record.host === 'string' ? record.host : '',
421
+ remotePath: typeof record.remotePath === 'string' ? record.remotePath : '',
422
+ }
423
+ }
424
+
384
425
  /**
385
426
  * 解析一条记录的正文。形状不对就报原因 —— 判据是「读不读得出这是哪条冲突」:
386
427
  * 必须有非空 `id`,`status` 必须是已知状态。`kind` 允许未知(老记录 / 别处写的记录照读)。
@@ -425,7 +466,9 @@ export async function readConflict(id, opts) {
425
466
  const parsed = parseConflictText(text)
426
467
  if (!parsed.ok) return { ok: false, code: 'malformed', path, error: parsed.reason }
427
468
 
428
- const record = { ...parsed.record, id: cid }
469
+ // 整份 JSON 反序列化 → 不认识的键**原样保留**(新字段天然读得出来);
470
+ // 只是老记录缺的那三个来源键在这里补成空串(`withOriginFields`)。
471
+ const record = withOriginFields({ ...parsed.record, id: cid })
429
472
  const warnings = []
430
473
  if (parsed.record.id !== cid) {
431
474
  warnings.push(`文件内声明的冲突 id(${parsed.record.id})与文件名(${cid})不一致,已按文件名归一`)
@@ -586,7 +629,7 @@ export async function listConflicts(opts) {
586
629
  broken.push(name)
587
630
  continue
588
631
  }
589
- items.push({ ...parsed.record, id })
632
+ items.push(withOriginFields({ ...parsed.record, id }))
590
633
  }
591
634
 
592
635
  // 新的在前(队列的第一眼应该是最新那条);没有 at 的排在后面,同档按 id 排,保证顺序确定。
@@ -614,6 +657,12 @@ export function summarizeConflict(record) {
614
657
  decidedAt: typeof r.decidedAt === 'string' ? r.decidedAt : '',
615
658
  appliedVersion: typeof r.appliedVersion === 'string' ? r.appliedVersion : '',
616
659
  invalidatedFile: typeof r.invalidatedFile === 'string' ? r.invalidatedFile : '',
660
+ // 3.0.0:来源三字段。缺省空串 = 老记录 = 面板按 `'manual'` 处理(additive 契约)。
661
+ // 面板靠它把「跨设备差异」与本地冲突分开渲染 —— 靠 `kind` 猜不可靠:
662
+ // `both-changed`(同步)与 autodream 的 `external_change` 语义上都是「两边都动过」。
663
+ origin: typeof r.origin === 'string' ? r.origin : '',
664
+ host: typeof r.host === 'string' ? r.host : '',
665
+ remotePath: typeof r.remotePath === 'string' ? r.remotePath : '',
617
666
  truncated: r.truncated === true,
618
667
  }
619
668
  }
@@ -18,7 +18,7 @@
18
18
  import { MEMORY_DIR } from './config.js'
19
19
  import { inspectMemoryEntry, readVerified, shadowsReserved } from './scan.js'
20
20
  import { safeName } from './naming.js'
21
- import { revisionOf } from './chunks.js'
21
+ import { revisionOfText } from './chunks.js'
22
22
  import { join } from 'node:path'
23
23
 
24
24
  /** 一屏默认给多少字节。4 KB ≈ 一屏可读正文,比一次注入的 60 KB 会话预算小一个量级。 */
@@ -233,7 +233,7 @@ export async function readSlice(req = {}) {
233
233
  // 读的是闸门检查过的同一个句柄(SEC-01):路径在检查与读取之间被换掉会返回 changed,
234
234
  // 而不是把没检查过的内容当记忆交出去。
235
235
  const content = await readVerified(full, gate, 'utf8')
236
- const revision = revisionOf(content)
236
+ const revision = revisionOfText(content)
237
237
  /**
238
238
  * 带了 revision 就一定校验,且**不返回任何内容 / 行号**:过期行号比「读不到」危险得多 ——
239
239
  * 调用方会以为自己在说「那份文件的第 40 行」,实际读到的是改过之后的第 40 行。
@@ -15,7 +15,7 @@ import { parseBaseline, parseFrontmatter } from './frontmatter.js'
15
15
  import { isMemoryEntry, isReserved, nameKey } from './naming.js'
16
16
  import { readExternalSettings } from '../settings.js'
17
17
  import { readLockState } from './lock.js'
18
- import { revisionOf } from './write-protocol.js'
18
+ import { revisionOfBytes } from './write-protocol.js'
19
19
  import { exposedByOf } from '../mirror/policy.js'
20
20
  import { warnLog } from './util.js'
21
21
  import { createDirWatcher } from './watch.js'
@@ -766,8 +766,8 @@ export async function listMemoryFiles(ctx, memoryDir) {
766
766
  size: f.content.length,
767
767
  tags: meta.tags,
768
768
  // 2.21.0:删除确认必须能交回「我看到的是哪一版」。与 readFile 用同一个
769
- // 正文字节 sha256(write-protocol.revisionOf),名字不再是身份。
770
- revision: revisionOf(Buffer.from(f.content, 'utf8')),
769
+ // 正文字节 sha256(write-protocol.revisionOfBytes),名字不再是身份。
770
+ revision: revisionOfBytes(Buffer.from(f.content, 'utf8')),
771
771
  // 锁定状态跟着每条一起给:卡片上的「锁定 / 已锁定」按钮要据此渲染
772
772
  locked: lockState.status === 'unknown' ? false : lockState.locked.has(nameKey(f.file)),
773
773
  // 2.30.0:`'exclude' | 'include' | 'prefix' | 'tag' | 'none'`。
@@ -14,7 +14,7 @@
14
14
  * 一篇文档的改动会影响所有词的 IDF。
15
15
  */
16
16
 
17
- import { chunkFile, revisionOf } from './chunks.js'
17
+ import { chunkFile, revisionOfText } from './chunks.js'
18
18
  import { buildStats, coverageOf, evidence, maxMatchedRun, queryTermsOf, scoreDoc, termFreq, tokenize, COVERAGE_WEIGHT } from './bm25.js'
19
19
  import { rankSummaries, score as summaryScore } from './retrieval.js'
20
20
  import { extractTitle } from './scan.js'
@@ -108,7 +108,7 @@ export function chunksOf(files) {
108
108
  const file = String(f?.file ?? '')
109
109
  const content = String(f?.content ?? '')
110
110
  if (!file) continue
111
- const revision = revisionOf(content)
111
+ const revision = revisionOfText(content)
112
112
  revisions.push(`${file}:${revision}`)
113
113
  const hit = chunkCache.get(file)
114
114
  if (hit && hit.revision === revision) {
@@ -255,7 +255,7 @@ export function summaryHits(query, files, limit = DEFAULT_LIMIT) {
255
255
  if (summaryScore(query, fileBase) > 0) matchedBy.push('filename')
256
256
  return {
257
257
  file: f.file,
258
- revision: revisionOf(String(f.content ?? '')),
258
+ revision: revisionOfText(String(f.content ?? '')),
259
259
  score: f.score,
260
260
  // 回落标签是 `summary` 而不是 `description`:`retrieval.js` 的打分是**三个字段去标点
261
261
  // 拼成一串**之后再算双字,所以跨字段边界也能产生命中(`description: '收尾待'` +
@@ -39,8 +39,20 @@ export const ERR_STALE_REVISION = 'stale_revision'
39
39
  /** 冲突码:`create`(createIfAbsent)撞上已有文件 —— 新建绝不覆盖已有内容。 */
40
40
  export const ERR_ALREADY_EXISTS = 'already_exists'
41
41
 
42
- /** 内容 revision:字节的 sha256。读与写必须用同一个算法,调用方原样回传。 */
43
- export function revisionOf(bytes) {
42
+ /**
43
+ * 内容 revision(**全长守卫形**):字节的 sha256,**64 位裸 hex**,入参是 `Buffer`。
44
+ * 读与写必须用同一个算法,调用方原样回传。
45
+ *
46
+ * ── 为什么这个名字(2.33.4 改名,别改回去)──
47
+ * `memory/chunks.js` 里还有一个同源函数 `revisionOfText(string)` → `sha256:<前 12 位>`,
48
+ * 用于**展示 / 缓存**(工具文本、检索缓存);本函数用于**写守卫域**
49
+ * (`opts.expectedRevision` 与删除确认)。两者的前 12 位十六进制是同一串,
50
+ * 也就是 `revisionOfText` 的值去掉 `sha256:` 前缀 —— 同源,但**入参类型不同、截断方式不同**,
51
+ * 两个值域**不可互换**。改名前两个都叫 `revisionOf` 且都不校验入参类型:把短形交给
52
+ * `expectedRevision` 不抛异常,只会得到一个值域不对的字符串(守卫要么永远拒绝、要么永不生效),
53
+ * 是典型的静默失配。名字里带 `Text` / `Bytes` 就是让这种搬错在调用点一眼可见。
54
+ */
55
+ export function revisionOfBytes(bytes) {
44
56
  return createHash('sha256').update(bytes).digest('hex')
45
57
  }
46
58
 
@@ -53,7 +65,7 @@ export function revisionOf(bytes) {
53
65
  */
54
66
  export async function readSnapshot(full, gate, name) {
55
67
  const bytes = await readVerified(full, gate, false)
56
- return { name, content: bytes.toString('utf8'), revision: revisionOf(bytes) }
68
+ return { name, content: bytes.toString('utf8'), revision: revisionOfBytes(bytes) }
57
69
  }
58
70
 
59
71
  /** 旧调用方的兼容提示(一次写入一行,不做去重 —— 谁漏传一眼就能在日志里翻到)。 */
@@ -215,7 +227,7 @@ export async function writeSnapshot(target, content, gate, opts, meta) {
215
227
  if (err?.code === 'EEXIST') return rejected(ERR_ALREADY_EXISTS, `sage-mem: ${name} 刚刚被别的写入建出来了,新建没有覆盖它`)
216
228
  return rejected('io_error', `sage-mem: 写入 ${name} 失败:${String(err?.message ?? err)}`)
217
229
  }
218
- return { ok: true, file: name, revision: revisionOf(Buffer.from(content, 'utf8')), created: true }
230
+ return { ok: true, file: name, revision: revisionOfBytes(Buffer.from(content, 'utf8')), created: true }
219
231
  }
220
232
 
221
233
  // ② 带 expectedRevision:盘上版本与调用方读到的不一致 → 拒绝,内容一个字节不动。
@@ -226,7 +238,7 @@ export async function writeSnapshot(target, content, gate, opts, meta) {
226
238
  }
227
239
  let current
228
240
  try {
229
- current = revisionOf(await readVerified(target, gate, false))
241
+ current = revisionOfBytes(await readVerified(target, gate, false))
230
242
  } catch (err) {
231
243
  return rejected(ERR_STALE_REVISION, `sage-mem: 读不到 ${name} 的当前版本(${err?.code ?? err}),没有写入`)
232
244
  }
@@ -247,7 +259,7 @@ export async function writeSnapshot(target, content, gate, opts, meta) {
247
259
  } catch (err) {
248
260
  return rejected('io_error', `sage-mem: 写入 ${name} 失败:${String(err?.message ?? err)}`)
249
261
  }
250
- return { ok: true, file: name, revision: revisionOf(Buffer.from(content, 'utf8')) }
262
+ return { ok: true, file: name, revision: revisionOfBytes(Buffer.from(content, 'utf8')) }
251
263
  }
252
264
 
253
265
  /**
@@ -327,7 +339,7 @@ export async function deleteMemoryFile(ctx, name, opts) {
327
339
 
328
340
  let actual
329
341
  try {
330
- actual = revisionOf(await readFile(taken.taken))
342
+ actual = revisionOfBytes(await readFile(taken.taken))
331
343
  } catch (err) {
332
344
  const back = await returnSource(taken.taken, full)
333
345
  return {
@@ -16,7 +16,7 @@
16
16
  import { mkdir, readdir, readFile, unlink } from 'node:fs/promises'
17
17
  import { join } from 'node:path'
18
18
  import { parseFrontmatter } from '../memory/frontmatter.js'
19
- import { revisionOf } from '../memory/write-protocol.js'
19
+ import { revisionOfBytes } from '../memory/write-protocol.js'
20
20
  import { scanMemoryDirDetailed } from '../memory/scan.js'
21
21
  import { warnLog, writeFileAtomic } from '../memory/util.js'
22
22
  import { stampHuman } from '../shared/stamp.js'
@@ -33,7 +33,7 @@ import {
33
33
  /** 增量账的格式版本。形状(不是加字段)变了才 +1。 */
34
34
  const STATE_VERSION = 1
35
35
 
36
- const shaOf = (text) => revisionOf(Buffer.from(text, 'utf8'))
36
+ const shaOf = (text) => revisionOfBytes(Buffer.from(text, 'utf8'))
37
37
 
38
38
  /**
39
39
  * 建一个导出器。
@@ -247,6 +247,16 @@ export function exposedByOf(name, tags, external) {
247
247
  // `project_` 开头,但它不是一个记忆名。导出层拿到的名字来自 `scan.js`(已经过滤过),
248
248
  // 这道判定是给面板逐条勾选与将来的调用方兜底的 —— 判据只有一份,就别指望上游一定干净。
249
249
  if (!isPlainMdName(file)) return 'none'
250
+ /**
251
+ * 下面这段的 `.toLowerCase()` 与 `nameKey`(`memory/naming.js` 的唯一基准)**等价,且有意不换**:
252
+ * 上一行已经用 `isPlainMdName` 把名字压成单段,剩下的差别只有大小写。
253
+ *
254
+ * 为什么不图字面统一:本文件是 `structure-test` 第 5 组点名的**纯逻辑层**
255
+ * (「纯函数:可对字符串断言、import 时不读环境」),而 `memory/naming.js` 会经
256
+ * `memory/config.js` 在 import 时读 `reserved.json` 与环境变量。为了换一个等价的函数,
257
+ * 把一个纯判据模块变成 import 就碰盘的模块 —— 代价比收益大,而且那种破坏不会让任何测试变红。
258
+ * 真要统一,方向是让 `nameKey` 搬到零依赖的 `shared/`,而不是让 policy 往上伸手。
259
+ */
250
260
  const lower = file.toLowerCase()
251
261
  if ((external.exclude ?? []).some((n) => String(n).toLowerCase() === lower)) return 'exclude'
252
262
  if ((external.include ?? []).some((n) => String(n).toLowerCase() === lower)) return 'include'
@@ -330,5 +340,7 @@ export function buildMirrorIndex(entries, { stamp } = {}) {
330
340
  * 可能留着上一轮导出、现在已经退出白名单的文件。
331
341
  */
332
342
  export function isMirrorReadableName(name) {
343
+ // `isPlainMdName` 在前:名字到这里已经是单段,`toLowerCase()` 与 `nameKey` 同义(理由见
344
+ // `exposedByOf` 里那段「有意不换」的注释)。
333
345
  return typeof name === 'string' && isPlainMdName(name) && !name.startsWith('.') && name.toLowerCase() !== MIRROR_INDEX_NAME.toLowerCase()
334
346
  }