dsh-cooper-memory 0.0.0-stage → 0.1.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/web.mjs ADDED
@@ -0,0 +1,230 @@
1
+ #!/usr/bin/env node
2
+ // web.mjs —— 本地 Web 界面(只绑 127.0.0.1,默认端口 17890,与 README 一致)
3
+ // 同一份 mem.db:左边目录树,中间检索,右边分块编辑 / 版本历史 / 比对 / 回滚 / 记忆管理
4
+ import http from 'node:http';
5
+ import { openDb } from './lib/db.mjs';
6
+ import {
7
+ searchChunks, getChunk, editChunk, chunkHistory, chunkVersionText,
8
+ rollbackChunk, diffTexts, tree, remember, confirmMemory, rejectMemory,
9
+ listMemories, recall,
10
+ } from './lib/core.mjs';
11
+ import { runAutoExtract, recentTurns, llmDistill } from './lib/extract.mjs';
12
+ import { probe as llmProbe } from './lib/llm.mjs';
13
+
14
+ const PORT = Number(process.env.MEM_WEB_PORT || 17890);
15
+ const HOST = '127.0.0.1';
16
+ const db = openDb();
17
+
18
+ const json = (res, code, obj) => {
19
+ const body = JSON.stringify(obj);
20
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' });
21
+ res.end(body);
22
+ };
23
+
24
+ const readBody = (req) => new Promise((resolve, reject) => {
25
+ let b = '';
26
+ req.on('data', (c) => (b += c));
27
+ req.on('end', () => { try { resolve(b ? JSON.parse(b) : {}); } catch (e) { reject(e); } });
28
+ req.on('error', reject);
29
+ });
30
+
31
+ const HTML = `<!doctype html>
32
+ <html lang="zh-CN"><head><meta charset="utf-8"><title>本地记忆 / 知识库</title>
33
+ <style>
34
+ *{box-sizing:border-box} body{margin:0;font:14px/1.6 -apple-system,Segoe UI,sans-serif;background:#0f1115;color:#d6d9de}
35
+ header{padding:10px 16px;border-bottom:1px solid #23262d;display:flex;gap:12px;align-items:center}
36
+ header b{color:#8ab4f8} input,textarea,button,select{font:inherit;color:#d6d9de;background:#181b21;border:1px solid #2b2f38;border-radius:6px;padding:6px 8px}
37
+ button{cursor:pointer} button:hover{background:#20242c}
38
+ .wrap{display:grid;grid-template-columns:260px 320px 1fr;height:calc(100vh - 49px)}
39
+ .col{overflow:auto;padding:12px;border-right:1px solid #23262d}
40
+ .col:last-child{border-right:0}
41
+ pre{margin:0;white-space:pre-wrap;font:12px/1.5 ui-monospace,Consolas,monospace;color:#9aa4b2}
42
+ .item{padding:6px 8px;border-radius:6px;cursor:pointer;border:1px solid transparent}
43
+ .item:hover{background:#181b21;border-color:#2b2f38}
44
+ .item.active{background:#1c2330;border-color:#3b4a63}
45
+ .meta{color:#6b7686;font-size:12px}
46
+ .chunk{white-space:pre-wrap;background:#14171d;border:1px solid #23262d;border-radius:8px;padding:10px;max-height:38vh;overflow:auto}
47
+ textarea{width:100%;height:220px;resize:vertical}
48
+ .row{display:flex;gap:8px;margin:8px 0;flex-wrap:wrap;align-items:center}
49
+ .diff{font:12px/1.5 ui-monospace,monospace;white-space:pre-wrap;max-height:40vh;overflow:auto;background:#14171d;border-radius:8px;padding:10px}
50
+ .add{color:#7ee787}.del{color:#ff7b72}
51
+ .muted{color:#6b7686}
52
+ </style></head>
53
+ <body>
54
+ <header>
55
+ <b>本地记忆 / 知识库</b>
56
+ <input id="q" placeholder="检索…" style="width:280px">
57
+ <button onclick="doSearch()">搜索</button>
58
+ <span class="muted" id="stat"></span>
59
+ <button onclick="loadMemories('pending')">待确认记忆</button>
60
+ <button onclick="loadMemories('active')">全部记忆</button>
61
+ <button onclick="runExtract()">规则提取</button>
62
+ <button onclick="runDistill(this)">LLM 蒸馏</button>
63
+ </header>
64
+ <div class="wrap">
65
+ <div class="col"><div class="meta">目录树</div><pre id="tree"></pre></div>
66
+ <div class="col"><div class="meta">结果</div><div id="results"></div></div>
67
+ <div class="col" id="detail"><div class="muted">选一个分块查看</div></div>
68
+ </div>
69
+ <script>
70
+ let cur=null;
71
+ const $=id=>document.getElementById(id);
72
+ async function api(p,o){const r=await fetch(p,o);return r.json()}
73
+ async function loadTree(){ $('tree').textContent=(await api('/api/tree')).tree || '(空)' }
74
+ async function doSearch(){
75
+ const q=$('q').value.trim(); if(!q) return;
76
+ const d=await api('/api/search?q='+encodeURIComponent(q));
77
+ $('results').innerHTML=d.results.map(r=>
78
+ \`<div class="item" onclick="openChunk(\${r.chunk_id})">
79
+ <div>\${esc(r.path)} <span class="meta">#\${r.ordinal}</span></div>
80
+ <div class="meta">score \${r.score}</div>
81
+ <div class="meta">\${esc(r.text.slice(0,90))}…</div></div>\`).join('') || '<div class="muted">无结果</div>';
82
+ $('stat').textContent=\`融合 \${d.fused} 条\`;
83
+ }
84
+ function esc(s){return (s||'').replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]))}
85
+ async function openChunk(id){
86
+ cur=id;
87
+ const c=await api('/api/chunk?id='+id);
88
+ const h=await api('/api/history?id='+id);
89
+ $('detail').innerHTML=\`
90
+ <div class="meta">\${esc(c.rel_path)} · ordinal #\${c.ordinal} · 当前 v\${c.version} · tier \${c.tier}</div>
91
+ <div class="chunk" id="curtext">\${esc(c.text)}</div>
92
+ <div class="row"><textarea id="edit">\${esc(c.text)}</textarea></div>
93
+ <div class="row">
94
+ <button onclick="saveEdit()">保存为新版本</button>
95
+ <span class="muted">基于 v\${c.version}</span>
96
+ </div>
97
+ <div class="meta">版本历史</div>
98
+ <div>\${h.map(v=>\`<div class="item" onclick="showDiff(\${id},\${v.version})">v\${v.version} · \${v.editor} · \${v.created_at.slice(0,19)} · \${v.chars}字 · \${esc(v.note||'')}</div>\`).join('')}</div>
99
+ <div class="row"><span class="muted">比对:</span><select id="fromV">\${h.map(v=>\`<option value="\${v.version}">v\${v.version}</option>\`).join('')}</select>
100
+ <select id="toV"><option value="">当前</option>\${h.map(v=>\`<option value="\${v.version}">v\${v.version}</option>\`).join('')}</select>
101
+ <button onclick="compare()">比对</button>
102
+ <button onclick="doRollback()">回滚到所选版本</button></div>
103
+ <div class="diff" id="diff"></div>\`;
104
+ }
105
+ async function saveEdit(){
106
+ const t=$('edit').value;
107
+ const r=await api('/api/chunk',{method:'POST',headers:{'content-type':'application/json'},
108
+ body:JSON.stringify({id:cur,text:t,note:'web edit',base_version:null})});
109
+ if(r.error){alert(r.error);return}
110
+ openChunk(cur);
111
+ }
112
+ async function showDiff(id,to){
113
+ const from=to===1?2:1;
114
+ const d=await api(\`/api/diff?id=\${id}&from=\${to}&to=\${to}\`);
115
+ $('diff').textContent=d.mode==='too-large'?'文本过大,跳过比对':JSON.stringify(d,null,1);
116
+ }
117
+ async function compare(){
118
+ const f=$('fromV').value, t=$('toV').value;
119
+ const d=await api(\`/api/diff?id=\${cur}&from=\${f}\${t?'&to='+t:''}\`);
120
+ if(d.mode==='too-large'){$('diff').textContent=d.note;return}
121
+ $('diff').innerHTML=d.hunks.map(h=>\`<div class="\${h.op==='+'?'add':h.op==='-'?'del':''}">\${h.op} \${esc(h.line)}</div>\`).join('');
122
+ }
123
+ async function doRollback(){
124
+ const v=$('fromV').value;
125
+ if(!confirm('回滚到 v'+v+'?会生成新版本。')) return;
126
+ await api('/api/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({id:cur,version:Number(v)})});
127
+ openChunk(cur);
128
+ }
129
+ async function loadMemories(status){
130
+ const d=await api('/api/memories?status='+status);
131
+ $('detail').innerHTML='<div class="meta">记忆 · '+status+'</div>'+d.map(m=>
132
+ \`<div class="item"><div><span class="meta">[\${m.kind}/\${m.status}]</span> \${esc(m.text)}</div>
133
+ <div class="meta">\${m.confirmed_at?('确认于 '+m.confirmed_at.slice(0,19)):''} · 置信 \${m.confidence}\${m.supersedes_id?(' · <b style="color:#d29922">确认后将替代 #'+m.supersedes_id+'</b>'):''}\${m.superseded_by?(' · 已被 #'+m.superseded_by+' 替代'):''}</div>
134
+ <div class="row">\${m.status==='pending'?\`<button onclick="cf(\${m.id})">确认</button><button onclick="rj(\${m.id})">拒绝</button>\`:''}</div></div>\`).join('');
135
+ }
136
+ async function cf(id){await api('/api/confirm',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({id})});loadMemories('pending')}
137
+ async function rj(id){await api('/api/reject',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({id,note:'web reject'})});loadMemories('pending')}
138
+ async function runExtract(){
139
+ const r=await api('/api/extract',{method:'POST',headers:{'content-type':'application/json'},body:'{}'});
140
+ if(r.error){alert(r.error);return}
141
+ alert('扫描 '+r.scannedFiles+' 个会话文件,新增 '+r.added.length+' 条待确认');
142
+ loadMemories('pending');
143
+ }
144
+ async function runDistill(btn){
145
+ const old=btn.textContent; btn.textContent='蒸馏中…'; btn.disabled=true;
146
+ try{
147
+ const r=await api('/api/distill',{method:'POST',headers:{'content-type':'application/json'},body:'{}'});
148
+ if(r.error){alert(r.error);return}
149
+ alert('批次 '+r.batches+',候选 '+r.candidates.length+',新增 '+r.added.length);
150
+ loadMemories('pending');
151
+ }finally{ btn.textContent=old; btn.disabled=false; }
152
+ }
153
+ loadTree();
154
+ </script></body></html>`;
155
+
156
+ const server = http.createServer(async (req, res) => {
157
+ const url = new URL(req.url, `http://${HOST}:${PORT}`);
158
+ const p = url.pathname;
159
+ try {
160
+ if (p === '/' ) { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(HTML); return; }
161
+ if (p === '/api/tree') return json(res, 200, { tree: tree(db) });
162
+ if (p === '/api/search') {
163
+ const r = searchChunks(db, { query: url.searchParams.get('q') || '', limit: Number(url.searchParams.get('limit') || 10) });
164
+ return json(res, 200, {
165
+ fused: r.fused,
166
+ results: r.results.map((x) => ({ chunk_id: x.id, path: x.rel_path, ordinal: x.ordinal, score: Number(x.score.toFixed(4)), text: x.text })),
167
+ });
168
+ }
169
+ if (p === '/api/chunk' && req.method === 'GET') {
170
+ const c = getChunk(db, Number(url.searchParams.get('id')));
171
+ return c ? json(res, 200, c) : json(res, 404, { error: 'not found' });
172
+ }
173
+ if (p === '/api/chunk' && req.method === 'POST') {
174
+ const b = await readBody(req);
175
+ try {
176
+ const r = editChunk(db, Number(b.id), String(b.text), { note: b.note || '', baseVersion: b.base_version ?? null });
177
+ return json(res, 200, r);
178
+ } catch (e) { return json(res, 409, { error: e.message }); }
179
+ }
180
+ if (p === '/api/history') return json(res, 200, chunkHistory(db, Number(url.searchParams.get('id'))));
181
+ if (p === '/api/diff') {
182
+ const id = Number(url.searchParams.get('id'));
183
+ const from = Number(url.searchParams.get('from'));
184
+ const to = url.searchParams.get('to') ? Number(url.searchParams.get('to')) : null;
185
+ const a = chunkVersionText(db, id, from);
186
+ const b = to ? chunkVersionText(db, id, to) : getChunk(db, id);
187
+ if (!a || !b) return json(res, 404, { error: 'variant not found' });
188
+ return json(res, 200, diffTexts(a.text, b.text));
189
+ }
190
+ if (p === '/api/rollback' && req.method === 'POST') {
191
+ const b = await readBody(req);
192
+ try { return json(res, 200, rollbackChunk(db, Number(b.id), Number(b.version))); }
193
+ catch (e) { return json(res, 400, { error: e.message }); }
194
+ }
195
+ if (p === '/api/memories') return json(res, 200, listMemories(db, { status: url.searchParams.get('status'), limit: 200 }));
196
+ if (p === '/api/recall') return json(res, 200, recall(db, url.searchParams.get('q') || ''));
197
+ if (p === '/api/memory' && req.method === 'POST') {
198
+ const b = await readBody(req);
199
+ return json(res, 200, remember(db, { ...b, source: b.source || 'web' }));
200
+ }
201
+ if (p === '/api/confirm' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, confirmMemory(db, Number(b.id))); }
202
+ if (p === '/api/reject' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, rejectMemory(db, Number(b.id), { note: b.note || '' })); }
203
+ if (p === '/api/distill' && req.method === 'POST') {
204
+ const b = await readBody(req).catch(() => ({}));
205
+ const turns = recentTurns(b.sessions_dir || undefined, b.turns_limit ?? 60);
206
+ const r = await llmDistill(db, { turns, limit: b.limit ?? 30, dryRun: !!b.dry_run });
207
+ return json(res, 200, { batches: r.batches, candidates: r.candidates || [], added: r.added || [] });
208
+ }
209
+ if (p === '/api/probe-llm') {
210
+ return json(res, 200, await llmProbe());
211
+ }
212
+ if (p === '/api/extract' && req.method === 'POST') {
213
+ const b = await readBody(req).catch(() => ({}));
214
+ const r = runAutoExtract(db, {
215
+ sessionsDir: b.sessions_dir || undefined,
216
+ limit: b.limit ?? 30,
217
+ dryRun: !!b.dry_run,
218
+ });
219
+ return json(res, 200, { scannedFiles: r.scannedFiles, newFiles: r.newFiles, candidates: r.candidates, added: r.added });
220
+ }
221
+ json(res, 404, { error: 'not found' });
222
+ } catch (e) {
223
+ json(res, 500, { error: String(e.message || e) });
224
+ }
225
+ });
226
+
227
+ server.listen(PORT, HOST, () => {
228
+ console.log(`memory web: http://${HOST}:${PORT}`);
229
+ console.log(`db: ${process.env.MEM_DB || (process.env.MEM_ROOT || '~/.dsh-memory') + '/mem.db'}`);
230
+ });