dsh-memvault 0.10.0 → 0.11.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.
@@ -0,0 +1,332 @@
1
+ /**
2
+ * The tacit-knowledge channel: six classes, its own prompt, its own budget.
3
+ *
4
+ * Why a second pipeline instead of widening the fact extractor: that prompt asks
5
+ * for "long-term facts about the user", and pointing it at assistant prose and tool
6
+ * traffic produced rows like 「智能体运行在 DSH 上」 — a real regression recorded in
7
+ * DEVLOG §46. The classes this file collects are different in kind: reasons,
8
+ * contracts, failure modes, couplings, fix paths, habits. They need their own
9
+ * instructions, their own character budget, and their own table.
10
+ *
11
+ * Storage rides on `memories` (so FTS, vectors, RRF and supersede are reused) with a
12
+ * 1:1 side row in `knowledge` that carries the class, the scope level and the
13
+ * counters the flywheel needs.
14
+ */
15
+ import { createHash } from 'node:crypto'
16
+
17
+ /** The six classes, spelled exactly as the taxonomy in the design doc. */
18
+ export const KNOWLEDGE_KINDS = ['rationale', 'contract', 'failure', 'dependency', 'solution', 'persona']
19
+
20
+ /** Scope levels a piece of knowledge can claim. */
21
+ export const KNOWLEDGE_LEVELS = ['global', 'domain', 'project']
22
+
23
+ /** Which classes may ever be promoted into the always-injected block. */
24
+ export const PROMOTABLE_KINDS = ['contract', 'persona']
25
+
26
+ /**
27
+ * The prompt.
28
+ *
29
+ * Written as an instruction about **evidence**, not about summarising: the failure
30
+ * mode of every extraction prompt is a fluent paraphrase that reads like knowledge
31
+ * and carries none. Hence the explicit "quote the sentence you relied on" and the
32
+ * ban on general programming truths (`K_world`), which the model already has and
33
+ * which would flood the store.
34
+ */
35
+ export const DEFAULT_KNOWLEDGE_PROMPT = [
36
+ 'You extract TACIT ENGINEERING KNOWLEDGE from one development transcript.',
37
+ 'Return ONLY a JSON array. Each item:',
38
+ '{"kind":"rationale|contract|failure|dependency|solution|persona",',
39
+ ' "text":"one sentence, self-contained, in the language of the transcript",',
40
+ ' "scope":"global|domain|project", "domain":"short tag or empty",',
41
+ ' "confidence":0.0-1.0, "quote":"the transcript sentence you relied on"}',
42
+ '',
43
+ 'Rules:',
44
+ '- rationale: WHY something is done this way (motive, trade-off, historical constraint).',
45
+ '- contract: an implicit contract or default behaviour invisible in the code.',
46
+ '- failure: a failure mode and its root cause, including silent failures ("looks fine but does nothing").',
47
+ '- dependency: a coupling across files/layers/toolchains that is not written down.',
48
+ '- solution: how a problem was located, verified or fixed, in a way a later reader can repeat.',
49
+ '- persona: a stable working habit or preference of THIS developer.',
50
+ '- Skip anything true of programming in general (K_world): no framework tutorials, no language basics.',
51
+ '- Skip speculation. If the transcript does not state why, do not invent a why.',
52
+ '- "quote" must be copied verbatim from the transcript and at least 20 characters.',
53
+ '- Prefer 0 items over a weak item.',
54
+ 'Return [] when the transcript contains no such knowledge.',
55
+ ].join('\n')
56
+
57
+ /** Stable identity of one piece of knowledge, for dedupe across windows. */
58
+ export function knowledgeDedupeKey(kind, text) {
59
+ const normalized = String(text ?? '').replace(/\s+/g, ' ').trim().toLowerCase()
60
+ return createHash('sha1').update(`${kind}\u0000${normalized}`).digest('hex')
61
+ }
62
+
63
+ /**
64
+ * Keep only the event kinds the knowledge channel reads.
65
+ *
66
+ * A guard rather than a filter of convenience: the first caller passed a count where
67
+ * an array was expected, and the resulting throw was swallowed, so the channel looked
68
+ * like "nothing to extract" for hours. Non-arrays are answered with an empty list and
69
+ * the caller reports a skip.
70
+ */
71
+ export function knowledgeEvents(events) {
72
+ if (!Array.isArray(events)) return []
73
+ const wanted = new Set(['user/message', 'assistant/message', 'tool/call', 'tool/result'])
74
+ return events.filter((event) => wanted.has(event?.type))
75
+ }
76
+
77
+ const normalizeKind = (value) => {
78
+ const kind = String(value ?? '').trim().toLowerCase()
79
+ return KNOWLEDGE_KINDS.includes(kind) ? kind : null
80
+ }
81
+
82
+ /**
83
+ * Parse a model answer into knowledge items.
84
+ *
85
+ * Strict on purpose: `parseFactsStrict` in `extract.js` already learned that a
86
+ * permissive parser turns a malformed answer into zero items silently, which reads
87
+ * exactly like "nothing to extract" in the diagnostics.
88
+ *
89
+ * @returns `Array<{kind, text, scope, domain, confidence, quote}>`; empty array is
90
+ * a valid answer, a non-array is an error.
91
+ */
92
+ export function parseKnowledgeItems(value) {
93
+ let parsed = value
94
+ if (typeof value === 'string') {
95
+ const text = value.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim()
96
+ if (text === '') return []
97
+ try {
98
+ parsed = JSON.parse(text)
99
+ } catch {
100
+ throw new Error('knowledge extraction returned neither JSON nor an empty answer')
101
+ }
102
+ }
103
+ if (parsed === null || parsed === undefined) return []
104
+ if (!Array.isArray(parsed)) throw new Error('knowledge extraction must return a JSON array')
105
+ const items = []
106
+ for (const raw of parsed) {
107
+ if (!raw || typeof raw !== 'object') continue
108
+ const kind = normalizeKind(raw.kind)
109
+ const text = String(raw.text ?? '').trim()
110
+ if (!kind || text.length < 8 || text.length > 600) continue
111
+ const scope = KNOWLEDGE_LEVELS.includes(String(raw.scope ?? '').toLowerCase())
112
+ ? String(raw.scope).toLowerCase()
113
+ : 'project'
114
+ const confidence = Number.isFinite(Number(raw.confidence))
115
+ ? Math.max(0, Math.min(1, Number(raw.confidence)))
116
+ : 0.5
117
+ items.push({
118
+ kind,
119
+ text,
120
+ scope,
121
+ domain: String(raw.domain ?? '').trim().slice(0, 40).toLowerCase(),
122
+ confidence,
123
+ quote: String(raw.quote ?? '').trim().slice(0, 280),
124
+ })
125
+ }
126
+ return items.slice(0, 20)
127
+ }
128
+
129
+ /** Chat-completions extractor with the knowledge prompt. */
130
+ export class LLMKnowledgeExtractor {
131
+ constructor(client, { prompt = DEFAULT_KNOWLEDGE_PROMPT } = {}) {
132
+ this.client = client
133
+ this.prompt = prompt
134
+ }
135
+
136
+ async extract(messages) {
137
+ const transcript = messages.map((message) => String(message?.content ?? '')).join('\n\n').trim()
138
+ if (!transcript) return []
139
+ const answer = await this.client.complete({
140
+ messages: [
141
+ { role: 'system', content: this.prompt },
142
+ { role: 'user', content: transcript },
143
+ ],
144
+ })
145
+ return parseKnowledgeItems(answer)
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Deterministic fallback.
151
+ *
152
+ * Cannot classify well and does not pretend to: it only fires on explicit markers
153
+ * and returns nothing otherwise. Its job is to keep the channel exercisable without
154
+ * a key (and in tests), not to be a substitute for the model.
155
+ */
156
+ export class RuleKnowledgeExtractor {
157
+ constructor({ maxItems = 5 } = {}) {
158
+ this.maxItems = maxItems
159
+ }
160
+
161
+ extract(messages) {
162
+ const text = messages.map((message) => String(message?.content ?? '')).join('\n')
163
+ const rules = [
164
+ { kind: 'rationale', re: /(因为|原因是|之所以|because)\s*([^。\n]{8,120})/i },
165
+ { kind: 'failure', re: /(报错|失败|踩坑|不生效|静默失效|silently|silent failure)[::\s]*([^。\n]{8,120})/i },
166
+ { kind: 'contract', re: /(必须先|必须|禁止|不要用|不能)([^。\n]{6,120})/i },
167
+ { kind: 'solution', re: /(解决办法|修复方式|改用|workaround|固定下来)[::\s]*([^。\n]{6,120})/i },
168
+ { kind: 'persona', re: /(我习惯|我的偏好|我通常|prefer to)([^。\n]{6,120})/i },
169
+ ]
170
+ const items = []
171
+ for (const rule of rules) {
172
+ const match = text.match(rule.re)
173
+ if (!match) continue
174
+ const sentence = String(match[0]).trim()
175
+ items.push({
176
+ kind: rule.kind,
177
+ text: sentence.slice(0, 300),
178
+ scope: 'project',
179
+ domain: '',
180
+ confidence: 0.45,
181
+ quote: sentence.slice(0, 280),
182
+ })
183
+ if (items.length >= this.maxItems) break
184
+ }
185
+ return items
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Write knowledge items: one memory row plus one side row plus its evidence.
191
+ *
192
+ * `memories` carries the text (so retrieval works unchanged); `knowledge` carries
193
+ * the class and the counters; `knowledge_evidence` carries the sentence the model
194
+ * relied on, so a later reviewer can judge the claim instead of trusting a score.
195
+ *
196
+ * Duplicate handling is by `dedupe_key` within `(scope_level, domain)`: the same
197
+ * insight noticed again is not a second row, it is stronger evidence for the first.
198
+ */
199
+ export function rememberKnowledge(store, {
200
+ items = [],
201
+ scope = {},
202
+ sessionId = '',
203
+ seq = null,
204
+ origin = 'extract',
205
+ actor = 'knowledge',
206
+ } = {}) {
207
+ const summary = { added: 0, duplicated: 0, skipped: 0, ids: [], errors: [] }
208
+ if (!store) throw new Error('rememberKnowledge needs a store')
209
+ for (const item of items) {
210
+ try {
211
+ // Normalise before the INSERT: `knowledge.scope_level` has a CHECK constraint,
212
+ // so an unexpected value would abort the row with a raw SQLite error instead of
213
+ // a useful skip reason.
214
+ const level = KNOWLEDGE_LEVELS.includes(item.scope) ? item.scope : 'project'
215
+ const dedupeKey = knowledgeDedupeKey(item.kind, item.text)
216
+ const domain = level === 'domain' ? (item.domain ?? '') : ''
217
+ const existing = store.db.prepare(
218
+ 'SELECT * FROM knowledge WHERE scope_level = ? AND domain = ? AND dedupe_key = ?',
219
+ ).get(level, domain, dedupeKey)
220
+ if (existing) {
221
+ store.db.prepare(
222
+ 'UPDATE knowledge SET confidence = MAX(confidence, ?), updated_at = ? WHERE memory_id = ?',
223
+ ).run(item.confidence, new Date().toISOString(), existing.memory_id)
224
+ addEvidence(store, existing.memory_id, item, { sessionId, seq })
225
+ summary.duplicated += 1
226
+ summary.ids.push(existing.memory_id)
227
+ continue
228
+ }
229
+ const memory = store.addMemory({
230
+ userId: scope.userId ?? null,
231
+ agentId: scope.agentId ?? null,
232
+ runId: scope.runId ?? null,
233
+ text: item.text,
234
+ // Coarse bucket on purpose: `memory_type` is a three-value CHECK from v1,
235
+ // and `knowledge.kind` is the real axis. Changing the CHECK would mean
236
+ // rebuilding a table for a label.
237
+ type: 'agent',
238
+ metadata: { knowledge: item.kind, scopeLevel: level, domain },
239
+ origin,
240
+ confidence: item.confidence,
241
+ actor,
242
+ })
243
+ store.db.prepare(`
244
+ INSERT INTO knowledge (memory_id, kind, scope_level, domain, dedupe_key, confidence,
245
+ status, created_at, updated_at)
246
+ VALUES (?,?,?,?,?,?,?,?,?)
247
+ `).run(
248
+ memory.id, item.kind, item.scope, domain, dedupeKey, item.confidence,
249
+ item.confidence >= 0.6 ? 'active' : 'proposed',
250
+ new Date().toISOString(), new Date().toISOString(),
251
+ )
252
+ addEvidence(store, memory.id, item, { sessionId, seq })
253
+ summary.added += 1
254
+ summary.ids.push(memory.id)
255
+ } catch (error) {
256
+ summary.errors.push(`${item.kind}: ${error?.message ?? String(error)}`)
257
+ summary.skipped += 1
258
+ }
259
+ }
260
+ return summary
261
+ }
262
+
263
+ function addEvidence(store, memoryId, item, { sessionId, seq }) {
264
+ if (!item.quote) return
265
+ store.db.prepare(`
266
+ INSERT INTO knowledge_evidence (memory_id, source_kind, session_id, seq, tool_name, excerpt, weight, captured_at)
267
+ VALUES (?,?,?,?,?,?,?,?)
268
+ `).run(memoryId, 'turn', String(sessionId ?? ''), seq ?? null, '', item.quote.slice(0, 280), 1, new Date().toISOString())
269
+ }
270
+
271
+ /**
272
+ * Health of the knowledge plane, for the panel.
273
+ *
274
+ * Every number here is computed from rows that already exist: no new counters were
275
+ * introduced for the panel, because a metric that needs its own bookkeeping drifts.
276
+ */
277
+ export function knowledgeStats(store, { now = Date.now(), retrievalDays = 7 } = {}) {
278
+ if (!store) throw new Error('knowledgeStats needs a store')
279
+ const byKind = store.db.prepare(`
280
+ SELECT kind,
281
+ COUNT(*) AS total,
282
+ SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active,
283
+ SUM(CASE WHEN status = 'proposed' THEN 1 ELSE 0 END) AS proposed,
284
+ SUM(CASE WHEN status IN ('stale','retired') THEN 1 ELSE 0 END) AS retired,
285
+ SUM(used_count) AS used,
286
+ SUM(refuted_count) AS refuted
287
+ FROM knowledge GROUP BY kind ORDER BY kind
288
+ `).all()
289
+ const evidence = store.db.prepare('SELECT COUNT(*) AS n FROM knowledge_evidence').get()?.n ?? 0
290
+ const promotions = store.db.prepare(
291
+ "SELECT COUNT(*) AS n FROM knowledge WHERE promoted_at IS NOT NULL",
292
+ ).get()?.n ?? 0
293
+ const eligible = store.db.prepare(`
294
+ SELECT COUNT(*) AS n FROM knowledge k
295
+ WHERE k.status = 'active' AND k.kind IN (${PROMOTABLE_KINDS.map(() => '?').join(',')})
296
+ AND k.promoted_at IS NULL AND k.refuted_count = 0 AND k.used_count >= 3
297
+ `).get(...PROMOTABLE_KINDS)?.n ?? 0
298
+
299
+ const since = new Date(now - retrievalDays * 24 * 3600_000).toISOString()
300
+ const retrieval = store.db.prepare(`
301
+ SELECT COUNT(*) AS total,
302
+ SUM(hit) AS hits,
303
+ SUM(injected) AS injected,
304
+ SUM(CASE WHEN answerable = 1 THEN 1 ELSE 0 END) AS answerable,
305
+ SUM(CASE WHEN answerable = 0 THEN 1 ELSE 0 END) AS refused
306
+ FROM retrievals WHERE at >= ?
307
+ `).get(since) ?? { total: 0, hits: 0, injected: 0, answerable: 0, refused: 0 }
308
+
309
+ return {
310
+ kinds: byKind.map((row) => ({
311
+ kind: row.kind,
312
+ total: row.total,
313
+ active: row.active ?? 0,
314
+ proposed: row.proposed ?? 0,
315
+ retired: row.retired ?? 0,
316
+ used: row.used ?? 0,
317
+ refuted: row.refuted ?? 0,
318
+ })),
319
+ evidence,
320
+ promotions,
321
+ eligible,
322
+ retrievals: {
323
+ days: retrievalDays,
324
+ total: retrieval.total ?? 0,
325
+ hits: retrieval.hits ?? 0,
326
+ injected: retrieval.injected ?? 0,
327
+ answerable: retrieval.answerable ?? 0,
328
+ refused: retrieval.refused ?? 0,
329
+ hitRate: retrieval.total > 0 ? Math.round(((retrieval.hits ?? 0) / retrieval.total) * 1000) / 1000 : null,
330
+ },
331
+ }
332
+ }
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { ChatClient } from './llm.js'
15
15
  import { LLMExtractor, RuleExtractor } from './extract.js'
16
+ import { LLMKnowledgeExtractor, RuleKnowledgeExtractor } from './knowledge.js'
16
17
  import { resolveEmbedder, findEnvFile, readEnvFile } from './env.js'
17
18
  import { shapeProduced } from '../extract.js'
18
19
  import { remember } from './write.js'
@@ -38,17 +39,25 @@ export function buildPipeline({ projectDir = '', dbPath = '', env = process.env
38
39
  }
39
40
  const requested = String(merged.MEMVAULT_EXTRACTOR ?? '').toLowerCase()
40
41
  const useLlm = requested === 'rule' ? false : Boolean(merged.OPENAI_API_KEY)
41
- const extractor = useLlm
42
- ? new LLMExtractor(new ChatClient({
42
+ // One client, two prompts. The fact extractor and the knowledge extractor ask
43
+ // different questions of the same transcript, so they share transport and
44
+ // differ in instructions — sharing the client keeps timeouts and endpoints in
45
+ // one place.
46
+ const client = useLlm
47
+ ? new ChatClient({
43
48
  baseUrl: merged.OPENAI_BASE_URL || 'https://api.openai.com/v1',
44
49
  apiKey: merged.OPENAI_API_KEY,
45
50
  model: merged.OPENAI_CHAT_MODEL || 'gpt-4o-mini',
46
51
  timeoutMs: Number(merged.MEMVAULT_EXTRACT_TIMEOUT_MS ?? 60_000),
47
52
  extraBody,
48
- }))
49
- : new RuleExtractor()
53
+ })
54
+ : null
55
+ const extractor = client ? new LLMExtractor(client) : new RuleExtractor()
50
56
  return {
51
57
  extractor,
58
+ // The six-class channel: separate prompt, separate budget, separate tables.
59
+ // Using the fact extractor for this produced "智能体运行在 DSH 上" (DEVLOG §46).
60
+ knowledgeExtractor: client ? new LLMKnowledgeExtractor(client) : new RuleKnowledgeExtractor(),
52
61
  embedder: resolveEmbedder({ projectDir, dbPath, env: merged }),
53
62
  usesModel: useLlm,
54
63
  }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Promotion: from a retrieved piece of knowledge to a proposal for the core block.
3
+ *
4
+ * This is the last link of the flywheel, and the only one that ends at the human:
5
+ * meeting every threshold here produces a **proposal**, never a block write. The
6
+ * distinction is the whole design — an automatic promotion would let the extractor
7
+ * rewrite the always-injected text without anyone reading it.
8
+ *
9
+ * Only two classes can ever be promoted. Rationale, failure, solution and
10
+ * dependency entries are long, situational, and useful exactly when retrieved;
11
+ * putting them in every prompt would spend the budget on rules that rarely apply.
12
+ */
13
+ import { PROMOTABLE_KINDS } from './knowledge.js'
14
+ import { propose } from './proposals.js'
15
+
16
+ /**
17
+ * Thresholds.
18
+ *
19
+ * Each answers a concrete question, and each is deliberately hard to satisfy on a
20
+ * fresh install: a new store needs weeks before its first promotion, which is the
21
+ * correct behaviour for "stable rule" — the cost of a wrong one is permanent.
22
+ */
23
+ export const PROMOTION_LIMITS = {
24
+ /** Statistically extracted knowledge below this is a guess. */
25
+ minConfidence: 0.8,
26
+ /** Two independent signals, not two quotes from the same sentence. */
27
+ minEvidence: 2,
28
+ minSessions: 2,
29
+ /** It has to have been retrieved and used before it earns permanent space. */
30
+ minUsed: 3,
31
+ /** Any refutation sends it back to the retrieval layer. */
32
+ maxRefuted: 0,
33
+ /** At most this many proposals per extraction run, so a backlog cannot flood the queue. */
34
+ perRun: 3,
35
+ /** One block per class keeps the core list readable. */
36
+ labelPrefix: 'learned-',
37
+ /** Cap on the accumulated block; the writer's own limit is 8000, this leaves headroom. */
38
+ maxBlockChars: 6000,
39
+ }
40
+
41
+ /**
42
+ * Candidates that satisfy every threshold.
43
+ *
44
+ * Grouped through evidence so "two signals" means two evidence rows, and counted
45
+ * over distinct sessions so the same conversation cannot vote twice.
46
+ */
47
+ export function findPromotionCandidates(store, limits = {}) {
48
+ const config = { ...PROMOTION_LIMITS, ...limits }
49
+ const kinds = (config.kinds ?? PROMOTABLE_KINDS).filter((kind) => PROMOTABLE_KINDS.includes(kind))
50
+ if (kinds.length === 0) return []
51
+ return store.db.prepare(`
52
+ SELECT k.memory_id, k.kind, k.confidence, k.used_count, k.refuted_count,
53
+ m.text AS text,
54
+ COUNT(e.id) AS evidence_count,
55
+ COUNT(DISTINCT NULLIF(e.session_id, '')) AS session_count
56
+ FROM knowledge k
57
+ JOIN memories m ON m.id = k.memory_id
58
+ LEFT JOIN knowledge_evidence e ON e.memory_id = k.memory_id
59
+ WHERE k.status = 'active'
60
+ AND k.promoted_at IS NULL
61
+ AND k.refuted_count <= ?
62
+ AND k.confidence >= ?
63
+ AND k.used_count >= ?
64
+ AND k.kind IN (${kinds.map(() => '?').join(',')})
65
+ GROUP BY k.memory_id
66
+ HAVING evidence_count >= ? AND session_count >= ?
67
+ ORDER BY k.confidence DESC, k.used_count DESC
68
+ LIMIT ?
69
+ `).all(
70
+ config.maxRefuted, config.minConfidence, config.minUsed, ...kinds,
71
+ config.minEvidence, config.minSessions, config.perRun,
72
+ )
73
+ }
74
+
75
+ /**
76
+ * Turn candidates into proposals.
77
+ *
78
+ * The block text accumulates one bullet per promotion, so approving twice does not
79
+ * produce two competing blocks. If the current block already contains the sentence,
80
+ * the candidate is marked promoted without a proposal — the idea is already in the
81
+ * prompt, and re-proposing it is noise.
82
+ *
83
+ * @returns `{ ok, created, skipped, candidates, errors }`.
84
+ */
85
+ export function promoteKnowledge(store, {
86
+ target = {},
87
+ limits = {},
88
+ now = new Date(),
89
+ proposeImpl = propose,
90
+ } = {}) {
91
+ const config = { ...PROMOTION_LIMITS, ...limits }
92
+ const at = (now instanceof Date ? now : new Date(now)).toISOString()
93
+ const scopeType = String(target.scopeType ?? 'user')
94
+ const scopeId = String(target.scopeId ?? '').trim()
95
+ const out = { ok: true, created: [], skipped: [], candidates: 0, errors: [] }
96
+ if (!scopeId) {
97
+ out.ok = false
98
+ out.errors.push('promotion needs a target scope id (the user/agent the block belongs to)')
99
+ return out
100
+ }
101
+
102
+ const candidates = findPromotionCandidates(store, config)
103
+ out.candidates = candidates.length
104
+
105
+ for (const candidate of candidates) {
106
+ const label = `${config.labelPrefix}${candidate.kind}`
107
+ const existing = store.getBlock({ scopeType, scopeId, label }) ?? null
108
+ const existingText = existing?.value ?? ''
109
+ const bullet = `- ${candidate.text}`
110
+ if (existingText.includes(candidate.text)) {
111
+ // Already in the prompt: record that this one is done rather than proposing it
112
+ // again on every run.
113
+ store.db.prepare('UPDATE knowledge SET promoted_at = ? WHERE memory_id = ?').run(at, candidate.memory_id)
114
+ out.skipped.push({ memoryId: candidate.memory_id, reason: 'already in the block' })
115
+ continue
116
+ }
117
+ const nextValue = existingText ? `${existingText}\n${bullet}` : bullet
118
+ if (nextValue.length > config.maxBlockChars) {
119
+ out.skipped.push({ memoryId: candidate.memory_id, reason: `the block would exceed ${config.maxBlockChars} characters` })
120
+ continue
121
+ }
122
+
123
+ let result
124
+ try {
125
+ result = proposeImpl(store, {
126
+ scope_type: scopeType,
127
+ scope_id: scopeId,
128
+ label,
129
+ change_kind: existing ? 'rewrite' : 'create',
130
+ value: nextValue,
131
+ confidence: candidate.confidence,
132
+ proposer: 'extract',
133
+ evidence: [{
134
+ sessionId: String(candidate.session_id ?? ''),
135
+ quote: String(candidate.text ?? '').slice(0, 280),
136
+ }],
137
+ }, { now: now instanceof Date ? now : new Date(now) })
138
+ } catch (error) {
139
+ out.errors.push(`${candidate.memory_id}: ${error?.message ?? String(error)}`)
140
+ continue
141
+ }
142
+
143
+ if (!result?.ok) {
144
+ // A rate limit or a duplicate is not an error: the queue is full, or this was
145
+ // already proposed. Recording the reason keeps the panel honest.
146
+ out.skipped.push({ memoryId: candidate.memory_id, reason: result?.error ?? 'proposal rejected' })
147
+ continue
148
+ }
149
+
150
+ store.db.prepare('UPDATE knowledge SET promoted_at = ?, proposal_id = ? WHERE memory_id = ?')
151
+ .run(at, result.id, candidate.memory_id)
152
+ out.created.push({ memoryId: candidate.memory_id, proposalId: result.id, label, kind: candidate.kind })
153
+ }
154
+ return out
155
+ }