dsh-yuhui 0.0.0-stage → 0.78.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/CHECKLIST.md ADDED
@@ -0,0 +1,41 @@
1
+ # 鱼洄 · 改动清单(技能蒸馏:把踩过的坑留成清单)
2
+
3
+ > 用法:动代码前看一遍「改前」,改完跑 `node tools/check.mjs`,出问题查「排错」。
4
+ > 这份清单是从真实事故里长出来的,每条后面标着日期。
5
+
6
+ ## 改前
7
+
8
+ 1. **备份**
9
+ - 库:`ls -1t ~/.dsh/yuhui/backups | head -3`,超 6 小时就 `cp yuhui.db backups/yuhui-$(date +%Y%m%d-%H%M%S).db`;
10
+ - 代码:`cp index.js index.js.bak-$(date +%H%M)`(或改哪个备哪个)。
11
+ 2. **先读再改**:`grep` 到相关函数,读完再动手;不靠记忆猜行号。
12
+ 3. **改一处,验一处**:别一口气改五个文件。
13
+
14
+ ## 改后
15
+
16
+ ```bash
17
+ node tools/check.mjs
18
+ ```
19
+
20
+ 它做四件事:全部 js 过语法 → 页面脚本单独 check → 严格桩 DOM 渲染 → 起实例探四个接口 → 打印数据核对。
21
+
22
+ **四项全绿才算改完。**
23
+
24
+ ## 排错:这几类坑我都踩过
25
+
26
+ | 症状 | 真因 | 怎么查 |
27
+ |---|---|---|
28
+ | 页面某页报 `X is not defined` | 重构后残留的旧引用(2026-12-02 `attBox`) | 页面脚本 `node --check` + 桩 DOM 跑一遍 |
29
+ | `appendChild: parameter 1 is not of type Node` | 传进去的不是节点(`attachBlock` 返回 `{btn, thumbs}`) | 同上;桩 DOM 会直接抛在出错那行 |
30
+ | 功能“没反应”但没报错 | **静默失败**:try/catch 吞了(2026-12-02 备份少 import,两天没备成) | 加日志落文件;或手动调用一次看返回值 |
31
+ | 定时任务不跑 | ① 子进程找不到 `node`(PATH 里没有,2026-11-30)② 标记位写在成功之前(2026-12-02 渔火不重试) | 用 `process.execPath`;标记位放在成功回调里 |
32
+ | 检索“该想起却没想起” | 字面对不上、同义词缺(2026-12-02 命中率只有 23%) | 体检页的「差一点想起」 |
33
+ | 服务起不来、日志空白 | 缺 `--profile web`,或没用 pty(`script -qfc`) | 照 `tools/check.mjs` 里的启动方式 |
34
+
35
+ ## 别做的事
36
+
37
+ - 别把 `node` 写死在代码里(用 `process.execPath`);
38
+ - 别在 try 里吞掉错误却不留痕(至少写一行日志);
39
+ - 别把“我觉得它在跑”当证据,**看时间戳、看文件、看接口**。
40
+
41
+ (2026-12-02 建)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-yuhui contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # 鱼洄(dsh-yuhui)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 [DeepSeek Harness](https://github.com/deepseek-ai) 用的**本地记忆库**:把每天说过的话存进 SQLite,聊天时挑相关的几条塞回上下文,每晚自己写日记、整理旧记录。
4
+
5
+ 一句话:**让 agent 记得住,而且记得的是真的——有时间、能查、能改。**
6
+
7
+ ![记忆页](docs/memory.png)
8
+
9
+ ---
10
+
11
+ ## 它解决什么
12
+
13
+ 普通的 AI 对话,关掉就忘;靠一个越堆越长的上下文窗口,既贵又容易糊。
14
+ 鱼洄换个做法:**把记忆落在库子里**,每次只取相关的那几条回来。
15
+
16
+ - 想知道"上一次说过什么"——查得到,带日期;
17
+ - 想改口——旧条作废,新条生效,不覆盖;
18
+ - 想删掉——先归档,随时能捞回来;
19
+ - **不联网也能查**,数据全在本机。
20
+
21
+ ## 能力一览
22
+
23
+ | 能力 | 说明 |
24
+ |---|---|
25
+ | **记忆** | 六层(事实/处境/画像/自我/事件/日记),带权重、情绪、出处 |
26
+ | **检索注入** | 每轮挑 3 条塞进上下文;命中不了就空着,宁可不带 |
27
+ | **原文** | 对话原文旁路落库,按会话/时间可查 |
28
+ | **规矩(常驻)** | 标记为常驻的记忆**每轮必带**,不靠检索运气 |
29
+ | **日记 + 时间轴** | 每晚自动写一篇日记、三行时间轴(本地定时) |
30
+ | **做梦** | 每天深夜巩固(碎记录合成一条)、修剪(长期没想起的降权) |
31
+ | **归墟(归档)** | 确定用不上的自动沉下去,只打标记,随时能捞 |
32
+ | **体检页** | 注入命中率、冷记忆、备份状态——**能看见才算数** |
33
+ | **星图(可选)** | 另装 `dsh-yuhui-firelight`,把记忆画成图;不装也能用 |
34
+
35
+ ## 装
36
+
37
+ **前提**:Node.js(20 以上)+ 已装 DSH(`npm i -g @deepseek-ai/dsh`)。
38
+
39
+ **一条命令(推荐,直接从 GitHub 装)**:
40
+
41
+ ```bash
42
+ dsh plugin --profile web add github:fucheng21/dsh-yuhui
43
+ ```
44
+
45
+ **或者 clone 下来装本地目录**(改代码方便):
46
+
47
+ ```bash
48
+ git clone https://github.com/fucheng21/dsh-yuhui.git
49
+ dsh plugin --profile web add ./dsh-yuhui
50
+ ```
51
+
52
+ 重启 DSH。第一次启动自己建库建表——**空库、空配置也能跑**,称呼和记忆留给你自己填。
53
+
54
+ > 如果 GitHub 直装时 pnpm 报「git-hosted plugins build … blocked」,在 `~/.dsh/profiles/web/pnpm-workspace.yaml` 里加一行再重试:
55
+ > ```yaml
56
+ > allowBuilds:
57
+ > - dsh-yuhui
58
+ > ```
59
+ > (这一步是 pnpm 的安全默认;本插件没有编译步骤,放行只是让安装继续。)
60
+
61
+ ### 装完怎么确认它在工作(三步)
62
+
63
+ 1. **库建出来了**:`ls ~/.dsh/yuhui/yuhui.db`
64
+ 2. **接口通**:打开 DSH 的插件页 →「鱼洄」→ 有「记忆/日记/体检」几个页签
65
+ 3. **注入生效**:说一句长一点的话(20 字以上),再看体检页的「今天的注入」+1
66
+
67
+ ### 第一次跑要填什么
68
+
69
+ `~/.dsh/yuhui/config.json`:
70
+
71
+ ```json
72
+ {
73
+ "ownerName": "你怎么称呼对方",
74
+ "assistantName": "这个 agent 叫什么",
75
+ "diaryPrompt": "(可选)日记怎么写,替换默认那段"
76
+ }
77
+ ```
78
+
79
+ 不填也能用:称呼退到「你」,助手名退到「我」。
80
+
81
+ ![体检页](docs/checkup.png)
82
+
83
+ ## 数据在哪
84
+
85
+ ```
86
+ ~/.dsh/yuhui/
87
+ yuhui.db # 全部记忆(SQLite,19 张表)
88
+ backups/ # 每 6 小时库备份 + 代码备份(各留 5 份)
89
+ weekly/ # 周记
90
+ config.json # 称呼等设置
91
+ vocab.json # 自己并进来的检索词(不改代码也能长)
92
+ ```
93
+
94
+ **换机器怎么搬**:拷 `yuhui.db` 过去即可;两台同时写会打架,等"服务端模式"(规划中)。
95
+
96
+ ## 给别的客户端用(MCP)
97
+
98
+ 鱼洄的库不止插件能用——`tools/mcp-server.mjs` 把它包成 MCP,任何支持 MCP 的客户端(Cursor / Claude Desktop …)都能 `recall` / `remember`。
99
+
100
+ ```bash
101
+ # stdio 模式(客户端里配 command)
102
+ node tools/mcp-server.mjs
103
+
104
+ # HTTP 模式(多个客户端,或同一台机器上别的程序)
105
+ node tools/mcp-server.mjs --http 7317 # POST http://127.0.0.1:7317/mcp
106
+ ```
107
+
108
+ 四个动作:`recall`(想)/ `remember`(记)/ `task`(任务卡)/ `handoff`(交接卡)。
109
+
110
+ **注意**:MCP 只解决“谁能读”,库还在那台机器上;跨机器共享要等服务端模式。
111
+
112
+ 接 Antigravity / Cursor 的具体配置、以及“库该放哪台机器”,见 [docs/MCP.md](docs/MCP.md)。
113
+
114
+ ## 改代码之前先看
115
+
116
+ ```bash
117
+ node tools/check.mjs
118
+ ```
119
+
120
+ 一条命令跑完:**语法 → 页面脚本 → 严格桩 DOM → 起实例探接口 → 数据核对**。四项全绿再提交。
121
+
122
+ `CHECKLIST.md` 里是踩过的坑(静默失败、子进程找不到 node、`appendChild` 传非节点……),照着排能省时间。
123
+
124
+ ## 设计上的几条取舍
125
+
126
+ - **宁可不带,不乱塞**:检索没命中就空着,别拿无关记忆凑数;
127
+ - **原文不删**:压缩、摘要、归档都留着原文,随时能回查;
128
+ - **能改口**:改一条记忆=旧条作废 + 新条生效,不是覆盖;
129
+ - **失败要留痕**:定时任务失败写日志,不静默。
130
+
131
+ ## 目录
132
+
133
+ ```
134
+ index.js 插件入口:建表、工具、定时器、注入拼装
135
+ routes.js 只读接口 + 页面挂载
136
+ page.js 页面(原生 JS,无框架)
137
+ api-write.js 写入接口
138
+ diary.js 日记与时间轴
139
+ dream.js 做梦(巩固/修剪)+ 归墟归档
140
+ automem.js 从对话里抽记忆
141
+ owner.js 称呼与助手名(读配置,不写死)
142
+ tools/ check(自检)、weekly(周记)、vocab-*(词表)
143
+ ```
144
+
145
+ ## 许可
146
+
147
+ MIT,见 `LICENSE`。
package/api-util.js ADDED
@@ -0,0 +1,49 @@
1
+ /** 鱼洄 · 接口公用件(json/读体/哈希/写记忆) */
2
+
3
+ import { join } from 'node:path'
4
+ import { homedir } from 'node:os'
5
+ import { writeFileSync, unlinkSync, readFileSync, mkdirSync } from 'node:fs'
6
+ import { createHash, randomBytes } from 'node:crypto'
7
+ import { DatabaseSync } from 'node:sqlite'
8
+
9
+ const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
10
+ export const DB_FILE = join(HOME, 'yuhui', 'yuhui.db')
11
+
12
+ export function openDb(writable = false) {
13
+ return new DatabaseSync(DB_FILE, writable ? {} : { readOnly: true })
14
+ }
15
+
16
+ export function json(res, code, body) {
17
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
18
+ res.end(JSON.stringify(body))
19
+ }
20
+
21
+ export function readBody(req, limit = 64 * 1024) {
22
+ return new Promise((resolve, reject) => {
23
+ let size = 0
24
+ const chunks = []
25
+ req.on('data', (c) => {
26
+ size += c.length
27
+ if (size > limit) { reject(new Error('body-too-large')); try { req.destroy() } catch { /* 忽略 */ } ; return }
28
+ chunks.push(c)
29
+ })
30
+ req.on('end', () => {
31
+ try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}) } catch { resolve({}) }
32
+ })
33
+ req.on('error', reject)
34
+ })
35
+ }
36
+
37
+ export function hashOf(layer, text) {
38
+ return createHash('sha1').update(layer + '|' + text).digest('hex').slice(0, 16)
39
+ }
40
+
41
+ export function insertMemory(db, { layer, text, tags = '', weight = 3, emotion = 0, person = 'master', source = 'ui' }) {
42
+ const h = hashOf(layer, text)
43
+ const now = Date.now()
44
+ const info = db.prepare(`INSERT INTO memory (person_id, layer, kind, text, tags, weight, emotion, source, channel, hash, created, updated)
45
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`).run(person, layer, '', text, tags, Number(weight) || 3, Number(emotion) || 0, source, 'ui', h, now, now)
46
+ const id = Number(info.lastInsertRowid)
47
+ try { db.prepare('INSERT INTO memory_fts (rowid, text, tags) VALUES (?,?,?)').run(id, text, tags) } catch { /* 索引失败不影响主表 */ }
48
+ return id
49
+ }
package/api-write.js ADDED
@@ -0,0 +1,341 @@
1
+ /** 鱼洄 · 写接口(POST /api/plugins/yuhui/*) */
2
+
3
+ import { join, dirname } from 'node:path'
4
+ import { homedir } from 'node:os'
5
+ import { writeFileSync, unlinkSync, readFileSync, mkdirSync } from 'node:fs'
6
+ import { createHash, randomBytes } from 'node:crypto'
7
+ import { json, readBody, hashOf, insertMemory, openDb } from './api-util.js'
8
+
9
+ const LAYERS_ALLOWED = new Set(['fact', 'situation', 'profile', 'self', 'event', 'diary'])
10
+
11
+ export async function handleWrite(req, res, path) {
12
+ const body = await readBody(req)
13
+ const db = openDb(true)
14
+ try {
15
+ if (path === '/add') {
16
+ const text = String(body.text || '').trim()
17
+ const layer = String(body.layer || 'fact')
18
+ if (!text) return json(res, 400, { error: 'text-required' })
19
+ if (!LAYERS_ALLOWED.has(layer)) return json(res, 400, { error: 'bad-layer' })
20
+ const id = insertMemory(db, {
21
+ layer, text,
22
+ tags: String(body.tags || ''),
23
+ weight: Number(body.weight ?? 3),
24
+ emotion: Number(body.emotion ?? 0),
25
+ person: String(body.person || 'master'),
26
+ })
27
+ return json(res, 200, { ok: true, id })
28
+ }
29
+
30
+ if (path === '/supersede') {
31
+ const id = Number(body.id)
32
+ const text = String(body.text || '').trim()
33
+ const old = db.prepare('SELECT * FROM memory WHERE id = ?').get(id)
34
+ if (!old) return json(res, 404, { error: 'not-found' })
35
+ if (!text) return json(res, 400, { error: 'text-required' })
36
+ const newId = insertMemory(db, {
37
+ layer: old.layer, text,
38
+ tags: old.tags || '', weight: old.weight, emotion: old.emotion,
39
+ person: old.person_id || 'master', source: 'ui-supersede',
40
+ })
41
+ db.prepare("UPDATE memory SET status='superseded', valid_to=?, superseded_by=? WHERE id=?").run(Date.now(), newId, id)
42
+ return json(res, 200, { ok: true, id: newId, replaced: id })
43
+ }
44
+
45
+ if (path === '/delete') {
46
+ const id = Number(body.id)
47
+ const row = db.prepare('SELECT text FROM memory WHERE id = ?').get(id)
48
+ if (!row) return json(res, 404, { error: 'not-found' })
49
+ db.prepare('DELETE FROM memory WHERE id = ?').run(id)
50
+ try { db.prepare("INSERT INTO memory_fts (memory_fts, rowid, text, tags) VALUES ('delete', ?, ?, '')").run(id, row.text) } catch { /* 索引清理失败不影响主表 */ }
51
+ return json(res, 200, { ok: true, id })
52
+ }
53
+
54
+ if (path === '/turn/add') {
55
+ ensureTurns(db)
56
+ const role = String(body.role || '')
57
+ const text = String(body.text || '').trim()
58
+ if (role !== 'user' && role !== 'assistant') return json(res, 400, { error: 'bad-role' })
59
+ if (!text) return json(res, 400, { error: 'text-required' })
60
+ const info = db.prepare('INSERT INTO turns (role, text, at, session, title) VALUES (?,?,?,?,?)')
61
+ .run(role, text, Number(body.at) || Date.now(), String(body.session || ''), String(body.title || ''))
62
+ return json(res, 200, { ok: true, id: Number(info.lastInsertRowid) })
63
+ }
64
+
65
+ if (path === '/config') {
66
+ const dir = join(homedir(), '.dsh', 'yuhui')
67
+ try { mkdirSync(dir, { recursive: true }) } catch { /* 已有 */ }
68
+ if (typeof body.injectOn === 'boolean') {
69
+ const f = join(dir, 'inject.off')
70
+ if (body.injectOn) { try { unlinkSync(f) } catch { /* 本来就没有 */ } }
71
+ else writeFileSync(f, new Date().toISOString())
72
+ }
73
+ if (typeof body.firelightAuto === 'boolean') {
74
+ const cfgFile = join(dir, 'config.json')
75
+ let cfg = {}
76
+ try { cfg = JSON.parse(readFileSync(cfgFile, 'utf8')) } catch { /* 忽略 */ }
77
+ cfg.firelightAuto = body.firelightAuto
78
+ writeFileSync(cfgFile, JSON.stringify(cfg, null, 2))
79
+ }
80
+ if (typeof body.priceIn === 'number' || typeof body.priceOut === 'number') {
81
+ const cfgFile = join(dir, 'config.json')
82
+ let cfg = {}
83
+ try { cfg = JSON.parse(readFileSync(cfgFile, 'utf8')) } catch { /* 忽略 */ }
84
+ if (typeof body.priceIn === 'number') cfg.priceIn = Math.max(0, body.priceIn)
85
+ if (typeof body.priceOut === 'number') cfg.priceOut = Math.max(0, body.priceOut)
86
+ writeFileSync(cfgFile, JSON.stringify(cfg, null, 2))
87
+ }
88
+ if (typeof body.backupKeep === 'number') {
89
+ const cfgFile = join(dir, 'config.json')
90
+ let cfg = {}
91
+ try { cfg = JSON.parse(readFileSync(cfgFile, 'utf8')) } catch { /* 忽略 */ }
92
+ cfg.backupKeep = Math.max(2, Math.min(20, Math.round(body.backupKeep)))
93
+ writeFileSync(cfgFile, JSON.stringify(cfg, null, 2))
94
+ }
95
+ return json(res, 200, { ok: true })
96
+ }
97
+
98
+ if (path === '/hook') {
99
+ // 当场记开关:开=建 hook.on 文件,关=删掉。立刻生效,不用重启
100
+ const on = body.on === true
101
+ const flag = join(homedir(), '.dsh', 'yuhui', 'hook.on')
102
+ try {
103
+ if (on) writeFileSync(flag, new Date().toISOString())
104
+ else { try { unlinkSync(flag) } catch { /* 本来就没有 */ } }
105
+ return json(res, 200, { ok: true, on })
106
+ } catch (e) {
107
+ return json(res, 500, { error: String(e?.message || e) })
108
+ }
109
+ }
110
+
111
+ if (path === '/impression/add') {
112
+ const text = String(body.text || '').trim()
113
+ if (!text) return json(res, 400, { error: 'empty-text' })
114
+ const info = db.prepare('INSERT INTO impression (person_id, text, weight, created) VALUES (?,?,?,?)')
115
+ .run(String(body.person || 'master'), text, Number(body.weight ?? 3), Date.now())
116
+ return json(res, 200, { ok: true, id: Number(info.lastInsertRowid) })
117
+ }
118
+
119
+ if (path === '/impression/revise') {
120
+ const id = Number(body.id)
121
+ const text = String(body.text || '').trim()
122
+ if (!id || !text) return json(res, 400, { error: 'id-and-text-required' })
123
+ const cur = db.prepare('SELECT person_id, weight FROM impression WHERE id=?').get(id)
124
+ if (!cur) return json(res, 404, { error: 'not-found' })
125
+ const info = db.prepare('INSERT INTO impression (person_id, text, weight, created) VALUES (?,?,?,?)')
126
+ .run(cur.person_id, text, Number(cur.weight || 3), Date.now())
127
+ const newId = Number(info.lastInsertRowid)
128
+ db.prepare("UPDATE impression SET status='superseded', superseded_by=?, updated=? WHERE id=?").run(newId, Date.now(), id)
129
+ return json(res, 200, { ok: true, id: newId })
130
+ }
131
+
132
+ if (path === '/x/chat') {
133
+ const url = new URL(req.url || '/', 'http://localhost')
134
+ if (!xAuthed(req, url)) return json(res, 401, { error: 'bad-token' })
135
+ const text = String(body.text || (body.messages || []).map((m) => m.content).join('\n') || '').trim()
136
+ if (!text) return json(res, 400, { error: 'empty' })
137
+ // 先把开场包拼进系统提示——这就是“一接入就认识”
138
+ const system = buildBrief(db)
139
+ let reply = ''
140
+ let usage = null
141
+ let err = ''
142
+ try {
143
+ const txt = readFileSync(join(homedir(), '.dsh', '.credentials.yaml'), 'utf8')
144
+ const m = /DEEPSEEK_API_KEY\s*:\s*(\S+)/.exec(txt)
145
+ const key = m ? m[1].replace(/^["']|["']$/g, '') : process.env.DEEPSEEK_API_KEY
146
+ if (!key) throw new Error('没有 key')
147
+ const ctl = new AbortController()
148
+ const timer = setTimeout(() => ctl.abort(), 60000)
149
+ const r = await fetch('https://api.deepseek.com/chat/completions', {
150
+ method: 'POST',
151
+ headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json' },
152
+ body: JSON.stringify({
153
+ model: String(body.model || 'deepseek-chat'),
154
+ messages: [{ role: 'system', content: system }, { role: 'user', content: text }],
155
+ max_tokens: Math.min(2000, Number(body.maxTokens || 800)),
156
+ }),
157
+ signal: ctl.signal,
158
+ })
159
+ clearTimeout(timer)
160
+ const t2 = await r.text()
161
+ if (!r.ok) throw new Error('HTTP ' + r.status + ' ' + t2.slice(0, 120))
162
+ const data = JSON.parse(t2)
163
+ reply = data?.choices?.[0]?.message?.content || ''
164
+ usage = data?.usage || null
165
+ } catch (e) { err = String(e?.message || e).slice(0, 160) }
166
+ try {
167
+ db.prepare('INSERT INTO usage (at, feature, model, in_tok, out_tok, ok, ms, note) VALUES (?,?,?,?,?,?,?,?)')
168
+ .run(Date.now(), '共享对话', String(body.model || 'deepseek-chat'), usage?.prompt_tokens || 0, usage?.completion_tokens || 0, err ? 0 : 1, 0, err ? err : '带开场包')
169
+ } catch { /* 记账失败无所谓 */ }
170
+ if (err) return json(res, 200, { ok: false, error: err })
171
+ return json(res, 200, { ok: true, reply, usage, briefChars: system.length })
172
+ }
173
+
174
+ if (path === '/x/remember') {
175
+ const url = new URL(req.url || '/', 'http://localhost')
176
+ if (!xAuthed(req, url)) return json(res, 401, { error: 'bad-token' })
177
+ const text = String(body.text || '').trim()
178
+ if (text.length < 4) return json(res, 400, { error: 'text-too-short' })
179
+ const layer = ['fact', 'situation', 'profile', 'self', 'event', 'diary'].includes(body.layer) ? body.layer : 'fact'
180
+ const source = String(body.source || 'external').slice(0, 40)
181
+ const hash = createHash('sha1').update(text).digest('hex').slice(0, 16)
182
+ const dup = db.prepare('SELECT id FROM memory WHERE hash = ?').get(hash)
183
+ if (dup) return json(res, 200, { ok: true, id: dup.id, deduped: true })
184
+ const ts = Date.now()
185
+ const info = db.prepare("INSERT INTO memory (layer, kind, text, tags, weight, emotion, source, channel, hash, created, updated, status, valid_to) VALUES (?,?,?,?,3,0,?,'external',?,?,0,'active',0)")
186
+ .run(layer, String(body.kind || ''), text, String(body.tags || ''), source, hash, ts)
187
+ return json(res, 200, { ok: true, id: Number(info.lastInsertRowid), deduped: false })
188
+ }
189
+
190
+ if (path === '/attach/remove') {
191
+ const id = Number(body.id)
192
+ if (!id) return json(res, 400, { error: 'bad-id' })
193
+ try {
194
+ const row = db.prepare('SELECT file FROM attachment WHERE id = ?').get(id)
195
+ db.prepare('DELETE FROM attachment WHERE id = ?').run(id)
196
+ if (row && row.file) {
197
+ try { unlinkSync(join(homedir(), '.dsh', 'yuhui', 'files', row.file)) } catch { /* 文件不在就算了 */ }
198
+ }
199
+ return json(res, 200, { ok: true, removed: id })
200
+ } catch (e) { return json(res, 500, { error: 'remove-failed', message: String(e?.message || e).slice(0, 120) }) }
201
+ }
202
+
203
+ if (path === '/attach') {
204
+ // 传图:dataUrl 形如 data:image/jpeg;base64,xxxx
205
+ const dataUrl = String(body.dataUrl || '')
206
+ const m = dataUrl.match(/^data:image\/(png|jpe?g|webp);base64,([A-Za-z0-9+/=]+)$/)
207
+ if (!m) return json(res, 400, { error: 'bad-image' })
208
+ const ext = m[1] === 'jpeg' ? 'jpg' : m[1]
209
+ const buf = Buffer.from(m[2], 'base64')
210
+ if (buf.length > 8 * 1024 * 1024) return json(res, 400, { error: 'too-large' })
211
+ const dir = join(homedir(), '.dsh', 'yuhui', 'files')
212
+ try { mkdirSync(dir, { recursive: true }) } catch { /* 已有 */ }
213
+ const name = 'a' + Date.now() + '.' + ext
214
+ writeFileSync(join(dir, name), buf)
215
+ const info = db.prepare('INSERT INTO attachment (owner_type, owner_id, file, note, at) VALUES (?,?,?,?,?)')
216
+ .run(String(body.owner_type || 'memory'), String(body.owner_id || ''), name, String(body.note || ''), Date.now())
217
+ return json(res, 200, { ok: true, id: Number(info.lastInsertRowid), file: name })
218
+ }
219
+
220
+ if (path === '/feel') {
221
+ const num = (v, d) => (v === undefined || v === null || v === '' ? d : Number(v))
222
+ db.prepare('INSERT INTO affect (at, valence, arousal, tension, emotion, impulse, note) VALUES (?,?,?,?,?,?,?)')
223
+ .run(Date.now(), num(body.valence, 0), num(body.arousal, 0), num(body.tension, 0),
224
+ String(body.emotion || ''), String(body.impulse || ''), String(body.note || ''))
225
+ return json(res, 200, { ok: true })
226
+ }
227
+
228
+ if (path === '/vocab/add' || path === '/vocab/remove') {
229
+ // 把候选词并进 vocab.json(不改代码);remove 用来撤
230
+ const tag = String(body.tag || '').trim()
231
+ const words = (Array.isArray(body.words) ? body.words : [body.word]).map((w) => String(w || '').trim()).filter(Boolean)
232
+ if (!tag || !words.length) return json(res, 400, { error: 'tag-and-words-required' })
233
+ const file = join(homedir(), '.dsh', 'yuhui', 'vocab.json')
234
+ let cur = {}
235
+ try { cur = JSON.parse(readFileSync(file, 'utf8')) } catch { cur = {} }
236
+ const list = new Set(Array.isArray(cur[tag]) ? cur[tag] : [])
237
+ if (path === '/vocab/add') for (const w of words) list.add(w)
238
+ else for (const w of words) list.delete(w)
239
+ cur[tag] = [...list]
240
+ mkdirSync(dirname(file), { recursive: true })
241
+ writeFileSync(file, JSON.stringify(cur, null, 1))
242
+ return json(res, 200, { ok: true, tag, words: cur[tag] })
243
+ }
244
+
245
+ if (path === '/archive') {
246
+ // 归档:不删、不改状态,只打个时间戳;注入和渔火会跳过它,主动搜还搜得到
247
+ const id = Number(body.id)
248
+ const on = body.on === undefined ? true : !!body.on
249
+ if (!id) return json(res, 400, { error: 'id-required' })
250
+ const cur = db.prepare('SELECT id FROM memory WHERE id = ?').get(id)
251
+ if (!cur) return json(res, 404, { error: 'not-found' })
252
+ db.prepare('UPDATE memory SET archived_at = ?, updated = ? WHERE id = ?').run(on ? Date.now() : 0, Date.now(), id)
253
+ return json(res, 200, { ok: true, id, archived: on })
254
+ }
255
+
256
+ if (path === '/pin') {
257
+ // 常驻:打上/摘掉 tag「常驻」,注入时不再靠检索碰运气
258
+ const id = Number(body.id)
259
+ const on = body.on === undefined ? true : !!body.on
260
+ if (!id) return json(res, 400, { error: 'id-required' })
261
+ const cur = db.prepare('SELECT tags FROM memory WHERE id = ?').get(id)
262
+ if (!cur) return json(res, 404, { error: 'not-found' })
263
+ const list = String(cur.tags || '').split(',').map((x) => x.trim()).filter(Boolean).filter((x) => x !== '常驻')
264
+ if (on) list.push('常驻')
265
+ const tags = list.join(',')
266
+ db.prepare('UPDATE memory SET tags = ?, updated = ? WHERE id = ?').run(tags, Date.now(), id)
267
+ try { db.exec("INSERT INTO memory_fts(memory_fts) VALUES('rebuild')") } catch { /* 索引失败不影响 */ }
268
+ return json(res, 200, { ok: true, id, tags, pinned: on })
269
+ }
270
+
271
+ if (path === '/edit') {
272
+ const id = Number(body.id)
273
+ const text = typeof body.text === 'string' ? body.text.trim() : null
274
+ const weight = body.weight === undefined ? null : Number(body.weight)
275
+ if (!id || (text === null && weight === null)) return json(res, 400, { error: 'nothing-to-change' })
276
+ if (text !== null && !text) return json(res, 400, { error: 'empty-text' })
277
+ const cur = db.prepare('SELECT text, weight FROM memory WHERE id = ?').get(id)
278
+ if (!cur) return json(res, 404, { error: 'not-found' })
279
+ const nextText = text === null ? cur.text : text
280
+ const nextWeight = weight === null ? cur.weight : Math.min(5, Math.max(1, weight))
281
+ db.prepare('UPDATE memory SET text = ?, weight = ? WHERE id = ?').run(nextText, nextWeight, id)
282
+ // memory_fts 是外部内容表,不能直接 UPDATE;用 rebuild 重建索引(几十条,很快)
283
+ try { db.exec("INSERT INTO memory_fts(memory_fts) VALUES('rebuild')") } catch { /* 索引没重建也不挡改动 */ }
284
+ return json(res, 200, { ok: true, before: cur, after: { text: nextText, weight: nextWeight } })
285
+ }
286
+
287
+ if (path === '/person/rename') {
288
+ const id = String(body.id || '').trim()
289
+ const name = String(body.name || '').trim()
290
+ if (!id || !name) return json(res, 400, { error: 'id-and-name-required' })
291
+ const info = db.prepare('UPDATE person SET display_name = ? WHERE id = ?').run(name, id)
292
+ return json(res, 200, { ok: true, changed: Number(info.changes) })
293
+ }
294
+
295
+ if (path === '/loop/due') {
296
+ const id = Number(body.id)
297
+ const due = String(body.due || '').trim()
298
+ const info = db.prepare('UPDATE loop SET due = ? WHERE id = ?').run(due, id)
299
+ return json(res, 200, { ok: true, changed: Number(info.changes) })
300
+ }
301
+
302
+ if (path === '/diag') {
303
+ // 收前端自检报告(主题用),只留最近一条
304
+ const data = JSON.stringify(body).slice(0, 200000)
305
+ db.exec('CREATE TABLE IF NOT EXISTS diag (id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, body TEXT)')
306
+ db.prepare('INSERT INTO diag (at, body) VALUES (?,?)').run(Date.now(), data)
307
+ db.prepare('DELETE FROM diag WHERE id NOT IN (SELECT id FROM diag ORDER BY id DESC LIMIT 3)').run()
308
+ return json(res, 200, { ok: true, bytes: data.length })
309
+ }
310
+
311
+ if (path === '/loop/close') {
312
+ const id = Number(body.id)
313
+ const info = db.prepare("UPDATE loop SET status='done', closed_at=? WHERE id=? AND status='open'").run(Date.now(), id)
314
+ return json(res, 200, { ok: true, changed: Number(info.changes) })
315
+ }
316
+
317
+ if (path === '/loop/add') {
318
+ const what = String(body.what || '').trim()
319
+ if (!what) return json(res, 400, { error: 'what-required' })
320
+ const info = db.prepare('INSERT INTO loop (who, what, due, status, created) VALUES (?,?,?,?,?)')
321
+ .run(String(body.who || 'me'), what, String(body.due || ''), 'open', Date.now())
322
+ return json(res, 200, { ok: true, id: Number(info.lastInsertRowid) })
323
+ }
324
+
325
+ if (path === '/day/set') {
326
+ const date = String(body.date || '').trim()
327
+ const lines = Array.isArray(body.lines) ? body.lines.map((x) => String(x)).slice(0, 3) : []
328
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return json(res, 400, { error: 'bad-date' })
329
+ if (lines.length === 0) return json(res, 400, { error: 'lines-required' })
330
+ db.prepare(`INSERT INTO day (date, lines, updated) VALUES (?,?,?)
331
+ ON CONFLICT(date) DO UPDATE SET lines=excluded.lines, updated=excluded.updated`)
332
+ .run(date, JSON.stringify(lines), Date.now())
333
+ return json(res, 200, { ok: true, date, lines })
334
+ }
335
+
336
+ return json(res, 404, { error: 'no-such-write-route', path })
337
+ } finally {
338
+ try { db.close() } catch { /* 忽略 */ }
339
+ }
340
+ }
341
+