dsh-memory-domains 0.2.1 → 0.2.3

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/client.js CHANGED
@@ -837,6 +837,7 @@ window.__ModuleLoader__.load({
837
837
  syncBar();
838
838
  refreshDomains();
839
839
  refreshSessions();
840
+ if (reviewJob) pollReview(reviewJob); // 关面板期间轮询被停,重开要恢复,否则按钮永远卡「整理中」
840
841
  } else if (rootEl) {
841
842
  rootEl.classList.remove('dshmb-on');
842
843
  clearTimeout(reviewTimer);
package/index.js CHANGED
@@ -101,9 +101,14 @@ function flushMeta() {
101
101
  try { fs.writeFileSync(metaFile(), JSON.stringify(Object.fromEntries(metaCache))) } catch { /* ok */ }
102
102
  }
103
103
 
104
+ let warming = false
104
105
  async function warmSessionMeta() {
105
- const files = listSessionFiles(CURRENT.sessionsDir)
106
- let dirty = false
106
+ if (warming) return
107
+ warming = true
108
+ try {
109
+ // 最近的会话优先预热;每 25 个落盘一次,进程中途死掉不丢已完成的进度
110
+ const files = listSessionFiles(CURRENT.sessionsDir).sort((a, b) => b.mtime - a.mtime)
111
+ let dirty = false, sinceFlush = 0
107
112
  for (const f of files) {
108
113
  const cur = metaCache.get(f.id)
109
114
  if (cur && cur.size === f.size && cur.mtime === f.mtime) continue
@@ -112,9 +117,11 @@ async function warmSessionMeta() {
112
117
  metaCache.set(f.id, { size: f.size, mtime: f.mtime, title: data.title, cwd: data.cwd, msgs: data.msgs.length })
113
118
  dirty = true
114
119
  } catch { /* 解不出跳过 */ }
120
+ if (++sinceFlush >= 25) { flushMeta(); sinceFlush = 0 }
115
121
  await new Promise(r => setImmediate(r)) // 让出事件循环,不阻塞 API
116
122
  }
117
123
  if (dirty) flushMeta()
124
+ } finally { warming = false }
118
125
  }
119
126
 
120
127
  function sessionsPending() {
@@ -150,7 +157,10 @@ function domainList() {
150
157
 
151
158
  const api = {
152
159
  // GET /api/sessions — 会话清单(秒回:标题走缓存,pending>0 表示后台还在预热)
153
- 'GET /api/sessions': async () => ({
160
+ 'GET /api/sessions': async () => {
161
+ // 预热只在 apply 跑一次;运行期新会话靠这里自愈(pending>0 时补一轮,幂等+防重入)
162
+ if (sessionsPending() > 0) warmSessionMeta().catch(() => {})
163
+ return {
154
164
  ok: true,
155
165
  pending: sessionsPending(),
156
166
  sessions: listSessions(CURRENT.sessionsDir, { parseTitles: false }).map(s => ({
@@ -158,7 +168,8 @@ const api = {
158
168
  cwd: s.cwd ? String(s.cwd).split(/[\\/]/).pop() : '', // 只回 basename,不泄整机路径
159
169
  ws: s.ws, mtime: s.mtime, msgs: s.msgs,
160
170
  })),
161
- }),
171
+ }
172
+ },
162
173
 
163
174
  // ---- 领域 ----
164
175
  'GET /api/domains': async () => ({ ok: true, domains: domainList() }),
@@ -228,10 +239,19 @@ const api = {
228
239
  const body = await readBody(req)
229
240
  const session = String(body.session || '').trim()
230
241
  if (!session) return jsonErr(400, 'session required')
242
+ // 同一会话只允许一个 running job——绕过 UI 直连 API 也不会产出重复草稿;
243
+ // 先查重再解压轨迹,重复请求不白跑 IO
244
+ const dup = [...reviewJobs.entries()].find(([, j]) => j.session === session && j.state === 'running')
245
+ if (dup) return { ok: true, job: dup[0], deduped: true }
231
246
  const data = readSession(CURRENT.sessionsDir, session)
232
247
  if (!data || !data.msgs.length) return jsonErr(404, '会话不存在或没有可读消息')
233
248
  const jobId = `job-${Date.now().toString(36)}`
234
- reviewJobs.set(jobId, { state: 'running', session, started: Date.now() })
249
+ reviewJobs.set(jobId, { id: jobId, state: 'running', session, started: Date.now() })
250
+ // running 态兜底 TTL:客户端不轮询(关面板等)时 job 也不能在 Map 里永久滞留
251
+ setTimeout(() => {
252
+ const j = reviewJobs.get(jobId)
253
+ if (j && j.state === 'running') finishJob(jobId, { state: 'error', error: 'job timeout' })
254
+ }, CURRENT.reviewTimeoutMs + 60_000).unref?.()
235
255
  reviewSession(CURRENT, data, { domains: domainList() })
236
256
  .then(({ drafts }) => {
237
257
  for (const d of drafts) store.addCandidate(CURRENT.memoryDir, session, { ...d, source: `review:${session}` })
package/lib/github.js CHANGED
@@ -19,14 +19,28 @@ export async function distillQueries(cfg, domain, { chat } = {}) {
19
19
  role: 'user',
20
20
  content: [
21
21
  '你是 GitHub 项目发现助手。根据下面这个技术领域,输出 3~5 个适合在 GitHub 搜索的关键词 query。',
22
- '要求:每行一个 query;优先 repo name/description/topics 里常见的英文术语(可中英混合);简短精准,避免过长;不要序号、不要解释。',
22
+ '要求:优先 repo name/description/topics 里常见的英文术语(可中英混合);简短精准,避免过长。',
23
+ '只输出一个 JSON 数组,如 ["ros robotics", "embedded stm32 control"],不要解释。',
23
24
  `领域名称:${domain.name}`,
24
25
  `领域描述:${domain.desc}`,
25
26
  ].join('\n'),
26
27
  }], Math.min(cfg.reviewTimeoutMs || 180_000, 60_000))
28
+ const clean = s => String(s || '').trim().replace(/^`+|`+$/g, '').slice(0, 80)
29
+ const ok = s => s.length >= 2 && !/[。!?;:]/.test(s) // 全角句读是解释性文字的特征;ASCII ':' 保留(language:python 限定符)
30
+ // 优先 JSON 数组解析;失败退回逐行解析(容忍模型不守格式)
31
+ const m = String(text || '').match(/\[[^\[\]]*\]/) // 首个无嵌套括号组,防 '["a"] 说明 [b]' 贪婪误配
32
+ if (m) {
33
+ try {
34
+ const arr = JSON.parse(m[0])
35
+ if (Array.isArray(arr)) {
36
+ const qs = arr.map(clean).filter(ok).slice(0, 5)
37
+ if (qs.length) return qs
38
+ }
39
+ } catch { /* 落回行解析 */ }
40
+ }
27
41
  return String(text || '').split('\n')
28
- .map(l => l.replace(/^[-*\d.、))\s]+/, '').trim().replace(/^`+|`+$/g, ''))
29
- .filter(l => l.length >= 2 && l.length <= 80)
42
+ .map(l => clean(l.replace(/^[-*\d.、))\s]+/, '')))
43
+ .filter(ok)
30
44
  .slice(0, 5)
31
45
  }
32
46
 
package/lib/store.js CHANGED
@@ -105,7 +105,15 @@ export function updateDomain(dir, slug, { name, desc }) {
105
105
  return d
106
106
  }
107
107
 
108
- /** 删除领域:还有记忆条目时拒绝(避免误删知识),先归档/删除/迁移。 */
108
+ /** 候选区里是否有草稿建议归属该领域(删领域前要一起考虑)。 */
109
+ function candidatesReferenceDomain(dir, slug) {
110
+ const candDir = path.join(dir, 'candidates')
111
+ let files = []
112
+ try { files = fs.readdirSync(candDir).filter(f => f.endsWith('.jsonl')) } catch { return false }
113
+ return files.some(f => readJsonl(path.join(candDir, f)).some(c => c.domain === slug))
114
+ }
115
+
116
+ /** 删除领域:还有记忆条目或待审草稿引用时拒绝(避免误删知识/草稿悬空),先归档/删除/迁移。 */
109
117
  export function deleteDomain(dir, slug) {
110
118
  const domains = listDomains(dir)
111
119
  const i = domains.findIndex(d => d.slug === slug)
@@ -113,6 +121,9 @@ export function deleteDomain(dir, slug) {
113
121
  if (listMemories(dir, 'domain', slug).length > 0) {
114
122
  return { ok: false, error: '该领域下还有记忆条目,请先归档/删除或迁移' }
115
123
  }
124
+ if (candidatesReferenceDomain(dir, slug)) {
125
+ return { ok: false, error: '该领域还有待审草稿引用,请先处理草稿' }
126
+ }
116
127
  domains.splice(i, 1)
117
128
  saveDomains(dir, domains)
118
129
  try { fs.rmSync(domainFileFor(dir, slug), { force: true }) } catch { /* ok */ }
@@ -184,16 +195,27 @@ export function addMemory(dir, entry) {
184
195
  * 返回更新后的条目或 null。 */
185
196
  const CONTENT_FIELDS = ['title', 'content', 'type', 'evidence', 'domain']
186
197
  const HISTORY_CAP = 20
198
+ // patch 白名单:scope/domain 不允许改——条目物理上躺在哪个文件里由 scope+key 决定,
199
+ // 放开会造成"文件在 A 领域、条目自称 B 领域"的错位。跨库移动请走 promote/delete+create。
200
+ const PATCHABLE = new Set(['title', 'content', 'type', 'evidence', 'status', 'priority'])
187
201
  export function updateMemory(dir, scope, key, id, patch) {
188
202
  const p = fileForScope(dir, scope, key || null)
189
203
  const entries = readJsonl(p)
190
204
  const i = entries.findIndex(e => e.id === id)
191
205
  if (i < 0) return null
192
206
  const prev = entries[i]
193
- const touched = CONTENT_FIELDS.some(f => patch[f] !== undefined && patch[f] !== prev[f])
194
- const next = { ...prev, ...patch, id: prev.id, updated_at: new Date().toISOString() }
195
- if (patch.priority !== undefined) { // 元数据不进 history;'normal' 即删除标记
196
- if (patch.priority === 'high') next.priority = 'high'; else delete next.priority
207
+ const clean = {}
208
+ for (const k of Object.keys(patch || {})) if (PATCHABLE.has(k)) clean[k] = patch[k]
209
+ // 与 addMemory 同规格:type 校验枚举、字符串截断
210
+ if (clean.type !== undefined && !TYPES.includes(clean.type)) delete clean.type
211
+ if (clean.title !== undefined) clean.title = String(clean.title).slice(0, 200)
212
+ if (clean.content !== undefined) clean.content = String(clean.content).slice(0, 8000)
213
+ if (clean.evidence !== undefined) clean.evidence = String(clean.evidence).slice(0, 500)
214
+ if (clean.status !== undefined) clean.status = clean.status === 'archived' ? 'archived' : 'active'
215
+ const touched = CONTENT_FIELDS.some(f => clean[f] !== undefined && clean[f] !== prev[f])
216
+ const next = { ...prev, ...clean, id: prev.id, updated_at: new Date().toISOString() }
217
+ if (clean.priority !== undefined) { // 元数据不进 history;'normal' 即删除标记
218
+ if (clean.priority === 'high') next.priority = 'high'; else delete next.priority
197
219
  }
198
220
  if (touched) {
199
221
  // 快照瘦身:审计要的是"改了什么",截断存即可,不背全文
@@ -221,11 +243,13 @@ export function deleteMemory(dir, scope, key, id) {
221
243
  return true
222
244
  }
223
245
 
224
- /** 领域记忆升级全局(复制不删原件;promoted_from_id 用于检索去重)。 */
246
+ /** 领域记忆升级全局(复制不删原件;promoted_from_id 用于检索去重)。重复升级幂等。 */
225
247
  export function promoteToGlobal(dir, domainSlug, id) {
226
248
  const src = listMemories(dir, 'domain', domainSlug)
227
249
  const e = src.find(x => x.id === id)
228
250
  if (!e) return null
251
+ const dup = listMemories(dir, 'global').find(x => x.promoted_from_id === id && x.promoted_from === `domain:${domainSlug}`)
252
+ if (dup) return dup
229
253
  const { domain: _d, scope: _sc, ...rest } = e
230
254
  return addMemory(dir, { ...rest, scope: 'global', promoted_from: `domain:${domainSlug}`, promoted_from_id: id, source: e.source })
231
255
  }
@@ -269,7 +293,9 @@ export function acceptCandidate(dir, session, id, target) {
269
293
  const draft = cands[i]
270
294
  const scope = target?.scope === 'global' ? 'global' : 'domain'
271
295
  const domain = scope === 'domain' ? String(target?.domain || draft.domain || '') : ''
296
+ // 先校验再动草稿:领域被删等情况必须在 splice 之前抛,否则草稿已删却入库失败=静默丢失
272
297
  if (scope === 'domain' && !domain) throw new Error('入库需要选择领域或全局')
298
+ if (scope === 'domain' && !getDomain(dir, domain)) throw new Error(`领域不存在: ${domain}`)
273
299
  cands.splice(i, 1)
274
300
  writeJsonl(cp, cands)
275
301
  const { status: _st, domain: _dd, ...rest } = draft
@@ -337,6 +363,10 @@ export function migrateLegacy(dir) {
337
363
  target = { scope: 'global' }
338
364
  }
339
365
  const { session: _s, scope: _sc, domain: _od, ...rest } = old
366
+ // 崩溃中途重跑的幂等:目标库已有同 id 条目就跳过(addMemory 保留原 id)
367
+ const exists = (target.scope === 'global' ? listMemories(dir, 'global') : listMemories(dir, 'domain', target.domain))
368
+ .some(x => x.id === old.id)
369
+ if (exists) continue
340
370
  addMemory(dir, { ...rest, ...target, source_session: session, source: old.source || 'migrated' })
341
371
  n++
342
372
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-memory-domains",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "exports": {