whale-memory-core 0.3.0 → 0.4.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.
Files changed (2) hide show
  1. package/lib/self-prompt.js +100 -18
  2. package/package.json +1 -1
@@ -1,11 +1,14 @@
1
1
  // 她自己的提示词 overlay:不碰默认段,整段追加;版本只追加,可回退
2
+ // 护栏:大小上限、控制字符清理、重复内容不写、原子写、单写者锁、篡改可检测
2
3
  import fs from 'node:fs'
3
4
  import path from 'node:path'
5
+ import crypto from 'node:crypto'
4
6
 
5
7
  const DIR = 'prompt-overlay'
6
8
  const ACTIVE = 'prompt-overlay.md'
7
9
  const VERSIONS = 'versions'
8
10
  const MAX_CHARS = 2000
11
+ const MAX_APPEND_TOTAL = 12000
9
12
 
10
13
  function base(dataDir) {
11
14
  const d = path.join(dataDir, 'plugin-data', 'biomimetic-memory', DIR)
@@ -13,30 +16,82 @@ function base(dataDir) {
13
16
  return d
14
17
  }
15
18
 
19
+ const sha1 = (s) => crypto.createHash('sha1').update(s).digest('hex').slice(0, 16)
20
+
21
+ // 清理不可见控制字符;换行和制表保留
22
+ function clean(text) {
23
+ return String(text || '')
24
+ .replace(/\r\n?/g, '\n')
25
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200b-\u200f\u2028\u2029]/g, '')
26
+ .trim()
27
+ }
28
+
29
+ function atomicWrite(file, body) {
30
+ const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
31
+ fs.writeFileSync(tmp, body, 'utf8')
32
+ fs.renameSync(tmp, file)
33
+ }
34
+
35
+ // 单写者锁:另一个进程正在写时等一会儿;超过 timeout 报错,不静默覆盖
36
+ function withLock(dir, fn, { timeoutMs = 2000 } = {}) {
37
+ const lock = path.join(dir, '.lock')
38
+ const start = Date.now()
39
+ for (;;) {
40
+ try {
41
+ fs.mkdirSync(lock)
42
+ break
43
+ } catch (e) {
44
+ if (e.code !== 'EEXIST') throw e
45
+ try {
46
+ const st = fs.statSync(lock)
47
+ if (Date.now() - st.mtimeMs > 10000) { fs.rmSync(lock, { recursive: true, force: true }); continue }
48
+ } catch { /* 锁刚被释放 */ }
49
+ if (Date.now() - start > timeoutMs) throw new Error('提示词文件被另一个进程锁着,稍后再试。')
50
+ const t = Date.now()
51
+ while (Date.now() - t < 25) { /* 短等待 */ }
52
+ }
53
+ }
54
+ try { return fn() } finally { try { fs.rmSync(lock, { recursive: true, force: true }) } catch { } }
55
+ }
56
+
16
57
  export function load(dataDir) {
17
58
  try {
18
- const f = path.join(base(dataDir), ACTIVE)
19
- const text = fs.readFileSync(f, 'utf8').trim()
20
- return text || ''
59
+ return clean(fs.readFileSync(path.join(base(dataDir), ACTIVE), 'utf8'))
21
60
  } catch { return '' }
22
61
  }
23
62
 
24
- export function save(dataDir, text, reason = '') {
25
- const body = String(text || '').trim()
63
+ export function save(dataDir, text, reason = '', opts = {}) {
64
+ const body = clean(text)
26
65
  if (!body) return { ok: false, error: '空的,不写。' }
27
66
  if (body.length > MAX_CHARS) return { ok: false, error: '太长了(' + body.length + '/' + MAX_CHARS + ' 字),删一些再试。' }
67
+
68
+ const current = load(dataDir)
69
+ if (current === body) return { ok: true, noop: true, reason: '和当前版本一样,没有写入。' }
70
+
28
71
  const d = base(dataDir)
29
- const baseStamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 23)
30
- let stamp = baseStamp
31
- let n = 1
32
- while (fs.existsSync(path.join(d, VERSIONS, stamp + '.md'))) {
33
- stamp = baseStamp + '-' + n
34
- n += 1
72
+ try {
73
+ return withLock(d, () => {
74
+ const baseStamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 23)
75
+ let stamp = baseStamp
76
+ let n = 1
77
+ while (fs.existsSync(path.join(d, VERSIONS, stamp + '.md'))) {
78
+ stamp = baseStamp + '-' + n
79
+ n += 1
80
+ }
81
+ atomicWrite(path.join(d, VERSIONS, stamp + '.md'), body)
82
+ atomicWrite(path.join(d, ACTIVE), body)
83
+ fs.appendFileSync(path.join(d, 'history.jsonl'), JSON.stringify({
84
+ at: new Date().toISOString(),
85
+ chars: body.length,
86
+ hash: sha1(body),
87
+ reason: String(reason || '').slice(0, 200),
88
+ snapshot: stamp
89
+ }) + '\n', 'utf8')
90
+ return { ok: true, version: stamp, chars: body.length, hash: sha1(body) }
91
+ }, opts)
92
+ } catch (e) {
93
+ return { ok: false, error: String(e && e.message ? e.message : e) }
35
94
  }
36
- fs.writeFileSync(path.join(d, VERSIONS, stamp + '.md'), body, 'utf8')
37
- fs.writeFileSync(path.join(d, ACTIVE), body, 'utf8')
38
- fs.appendFileSync(path.join(d, 'history.jsonl'), JSON.stringify({ at: new Date().toISOString(), chars: body.length, reason: String(reason || '').slice(0, 200), snapshot: stamp }) + '\n', 'utf8')
39
- return { ok: true, version: stamp, chars: body.length }
40
95
  }
41
96
 
42
97
  export function history(dataDir, limit = 10) {
@@ -47,12 +102,39 @@ export function history(dataDir, limit = 10) {
47
102
  } catch { return [] }
48
103
  }
49
104
 
50
- export function revert(dataDir, version) {
105
+ export function revert(dataDir, version, reason = '') {
51
106
  try {
52
107
  const d = base(dataDir)
53
108
  const body = fs.readFileSync(path.join(d, VERSIONS, String(version) + '.md'), 'utf8')
54
- return save(dataDir, body, '回退到 ' + version)
109
+ return save(dataDir, body, reason || ('回退到 ' + version))
55
110
  } catch { return { ok: false, error: '找不到这个版本。' } }
56
111
  }
57
112
 
58
- export const internals = { MAX_CHARS, VERSIONS, ACTIVE }
113
+ // 生效内容 = 默认段 + 她的 overlay;超总长会明确报告截断,不悄悄切
114
+ export function render(basePrompt, dataDir, { marker = '\n\n<!-- 她自己的补充 -->\n' } = {}) {
115
+ const overlay = load(dataDir)
116
+ const base = String(basePrompt || '')
117
+ if (!overlay) return { text: base, appended: false, truncated: false }
118
+ const full = base + marker + overlay
119
+ if (full.length <= MAX_APPEND_TOTAL) return { text: full, appended: true, truncated: false }
120
+ const room = MAX_APPEND_TOTAL - base.length - marker.length
121
+ return {
122
+ text: base + marker + overlay.slice(0, Math.max(0, room)),
123
+ appended: true,
124
+ truncated: true,
125
+ note: 'overlay 超过总长上限,已截断;建议她精简。'
126
+ }
127
+ }
128
+
129
+ // 篡改检测:生效文件应该和最新版本文件一致
130
+ export function verify(dataDir) {
131
+ const active = load(dataDir)
132
+ const h = history(dataDir, 1)[0]
133
+ if (!h) return { ok: active === '', note: active ? '有生效文件但没有历史版本。' : '还没有写过。' }
134
+ let versionBody = ''
135
+ try { versionBody = clean(fs.readFileSync(path.join(base(dataDir), VERSIONS, String(h.snapshot) + '.md'), 'utf8')) } catch { }
136
+ const ok = active === versionBody
137
+ return { ok, activeHash: sha1(active), versionHash: sha1(versionBody), version: h.snapshot }
138
+ }
139
+
140
+ export const internals = { MAX_CHARS, MAX_APPEND_TOTAL, VERSIONS, ACTIVE, sha1 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
5
  "type": "module",
6
6
  "main": "./index.js",