dsh-experience 0.0.0-stage → 1.0.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.
package/index.js ADDED
@@ -0,0 +1,1325 @@
1
+ /**
2
+ * dsh-experience — cross-session experience loop for DeepSeek Harness.
3
+ *
4
+ * v0.2 M1: deterministic L1 auto-capture (no model calls) + `/memory review`.
5
+ *
6
+ * Integration points (evidenced in the DSH packages, see README):
7
+ * - `agent/pre-step` (waterfall): async retrieval, cached for the step.
8
+ * - `systemPrompt.context` on `agent.ctx`: its text is re-read by
9
+ * `refreshContext()` after pre-step, so the cache lands in this step.
10
+ * - `tools/result` (emit, observe-only): records every tool outcome with zero
11
+ * dispatch latency; `tools/post-execute` is a waterfall and would be awaited.
12
+ * - `agent/turn-stopping` (serial): deterministic capture + trace close.
13
+ * - `tools.register` / `commands.register` / durable JSON sidecar.
14
+ */
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+ import crypto from 'node:crypto'
19
+ import * as C from './lib/capture.js'
20
+ import * as E from './lib/evidence.js'
21
+ import * as D from './lib/decay.js'
22
+ import * as R from './lib/recall.js'
23
+ import * as S from './lib/store.js'
24
+ import { renderLookup } from './lib/lookup.js'
25
+
26
+ export const name = 'dsh-experience'
27
+ export const inject = ['tools', 'systemPrompt', 'commands', 'agents']
28
+
29
+ const HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
30
+ const STORE_DIR = path.join(HOME, 'experience')
31
+ const STORE_FILE = path.join(STORE_DIR, 'store.json')
32
+ const CONFIG_FILE = path.join(STORE_DIR, 'config.json')
33
+ const PROBE_FILE = path.join(STORE_DIR, 'probe.json')
34
+
35
+ const THRESHOLD = 0.15
36
+ const MAX_EXPERIENCES = 2
37
+ const MAX_CHARS = 1600
38
+ const BUILD = 'r25-stable'
39
+
40
+ let CONFIG = { ...C.DEFAULT_CONFIG }
41
+
42
+ function loadConfig() {
43
+ try {
44
+ const raw = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))
45
+ if (raw && typeof raw === 'object') {
46
+ CONFIG = { ...C.DEFAULT_CONFIG, ...raw }
47
+ let repaired = false
48
+ for (const key of Object.keys(C.DEFAULT_CONFIG)) {
49
+ try {
50
+ const value = C.coerceConfigValue(key, CONFIG[key])
51
+ if (value !== CONFIG[key]) {
52
+ CONFIG[key] = value
53
+ repaired = true
54
+ }
55
+ } catch {}
56
+ }
57
+ if (repaired) saveConfig()
58
+ }
59
+ } catch {}
60
+ return CONFIG
61
+ }
62
+
63
+ function saveConfig() {
64
+ try {
65
+ fs.mkdirSync(STORE_DIR, { recursive: true })
66
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(CONFIG, null, 2), 'utf8')
67
+ } catch (error) {
68
+ console.warn('[experience] config write failed:', error && error.message)
69
+ }
70
+ }
71
+
72
+ function loadStore() {
73
+ const result = S.readStore(STORE_FILE)
74
+ if (result.error) {
75
+ try {
76
+ fs.renameSync(STORE_FILE, `${STORE_FILE}.broken-${Date.now()}`)
77
+ } catch {}
78
+ console.warn('[experience] store unreadable, started empty:', result.error && result.error.message)
79
+ }
80
+ const store = result.store
81
+ E.migrateStore(store)
82
+ // Records written before the redaction fix may still carry absolute paths.
83
+ let scrubbed = 0
84
+ for (const record of store.experiences) if (C.scrubRecord(record)) scrubbed += 1
85
+ // Records written before 1.0.9 carry no artifact kinds; derive them so the
86
+ // cross-type veto also protects the existing library.
87
+ let kindsBackfilled = 0
88
+ for (const record of store.experiences) {
89
+ if (record.fingerprint && !Array.isArray(record.fingerprint.kinds)) {
90
+ record.fingerprint.kinds = C.artifactKindsOf(record.fingerprint.targets)
91
+ kindsBackfilled += 1
92
+ }
93
+ }
94
+ // Write it back once: otherwise the guard only sees kinds after the next merge.
95
+ if (kindsBackfilled) {
96
+ try {
97
+ saveStore(store)
98
+ } catch (error) {
99
+ console.warn('[dsh-experience] could not persist fingerprint kinds:', error && error.message)
100
+ }
101
+ }
102
+ if (scrubbed) console.warn(`[experience] scrubbed ${scrubbed} legacy record(s)`)
103
+ return store
104
+ }
105
+
106
+ function saveStore(store) {
107
+ S.writeStore(STORE_FILE, store)
108
+ }
109
+
110
+ function tokens(text) {
111
+ return R.expand(text)
112
+ }
113
+
114
+ /**
115
+ * Sessions own tool calls; an agent object can lose its id between the tool
116
+ * lifecycle and the turn lifecycle. Keying on the session keeps both sides in
117
+ * agreement — the mismatch was silently dropping every call of a turn.
118
+ */
119
+ function keyOf(agent) {
120
+ if (!agent) return ''
121
+ return (agent.session && agent.session.id) || agent.id || ''
122
+ }
123
+
124
+ function scoreExperience(experience, queryTokens, index) {
125
+ const base = R.score(R.profileText(experience), queryTokens, index)
126
+ // A recipe learned on another machine, or never tagged at all, is weaker evidence.
127
+ const factor = C.platformFactor(experience)
128
+ return Math.round(base * factor * 1000) / 1000
129
+ }
130
+
131
+ // Retrieval floor. Configurable via "/memory config set recallThreshold 0.1"
132
+ // because the right value depends on how noisy the task descriptions are.
133
+ function threshold() {
134
+ const value = Number(CONFIG.recallThreshold)
135
+ return Number.isFinite(value) && value > 0 ? value : THRESHOLD
136
+ }
137
+
138
+ function textOfMessage(message) {
139
+ if (!message) return ''
140
+ const content = message.content
141
+ if (typeof content === 'string') return content
142
+ if (Array.isArray(content)) {
143
+ return content
144
+ .map((block) => (block && typeof block.text === 'string' ? block.text : ''))
145
+ .join('\n')
146
+ }
147
+ return ''
148
+ }
149
+
150
+ function agentId(agent) {
151
+ if (!agent) return ''
152
+ if (typeof agent.id === 'string') return agent.id
153
+ if (agent.session && typeof agent.session.id === 'string') return agent.session.id
154
+ return ''
155
+ }
156
+
157
+ function estimateTokens(text) {
158
+ return Math.ceil(String(text || '').length / 2.5)
159
+ }
160
+
161
+ function workspaceOf(agent) {
162
+ const candidates = [agent && agent.session && agent.session.cwd, agent && agent.cwd, process.cwd()]
163
+ return candidates.find((value) => typeof value === 'string' && value) || ''
164
+ }
165
+
166
+ function pickName(exec) {
167
+ const candidates = [
168
+ exec && exec.name,
169
+ exec && exec.tool,
170
+ exec && exec.toolName,
171
+ exec && exec.definition && exec.definition.name,
172
+ exec && exec.call && exec.call.name,
173
+ ]
174
+ return candidates.find((value) => typeof value === 'string' && value) || 'unknown'
175
+ }
176
+
177
+ function pickArgs(exec) {
178
+ const candidates = [
179
+ exec && exec.arguments,
180
+ exec && exec.args,
181
+ exec && exec.input,
182
+ exec && exec.call && exec.call.arguments,
183
+ exec && exec.call && exec.call.args,
184
+ ]
185
+ return candidates.find((value) => value && typeof value === 'object') || null
186
+ }
187
+
188
+ function pickOk(exec, result) {
189
+ // Probe-confirmed contract (probe.json, 2026-11-08):
190
+ // ToolExecution = { name, callId, arguments, agent, toolSet, ... }
191
+ // ToolExecutionResult = { isError: boolean, content: [...], value: string }
192
+ if (result && typeof result === 'object' && typeof result.isError === 'boolean') return !result.isError
193
+ if (result && typeof result === 'object') {
194
+ if (typeof result.ok === 'boolean') return result.ok
195
+ if (typeof result.success === 'boolean') return result.success
196
+ if (typeof result.failed === 'boolean') return !result.failed
197
+ if (result.error) return false
198
+ if (typeof result.status === 'string') return /^(ok|success|succeeded|completed|done)$/i.test(result.status)
199
+ }
200
+ if (exec && exec.error) return false
201
+ return true
202
+ }
203
+
204
+ function pickError(exec, result) {
205
+ const parts = []
206
+ if (result && typeof result === 'object') {
207
+ if (typeof result.value === 'string' && result.value) parts.push(result.value)
208
+ else if (Array.isArray(result.content)) {
209
+ for (const block of result.content) {
210
+ if (block && typeof block.text === 'string') parts.push(block.text)
211
+ }
212
+ }
213
+ if (typeof result.error === 'string') parts.push(result.error)
214
+ else if (result.error) parts.push(String(result.error.code || ''), String(result.error.message || ''))
215
+ }
216
+ if (exec && exec.error) {
217
+ if (typeof exec.error === 'string') parts.push(exec.error)
218
+ else parts.push(String(exec.error.code || ''), String(exec.error.message || ''))
219
+ }
220
+ return parts.filter(Boolean).join(' ').trim()
221
+ }
222
+
223
+ function hintOf(args) {
224
+ if (!args) return ''
225
+ if (typeof args === 'string') return args
226
+ for (const key of ['path', 'file', 'file_path', 'command', 'cmd', 'pattern', 'query', 'ids']) {
227
+ const value = args[key]
228
+ if (typeof value === 'string') return value
229
+ if (Array.isArray(value) && value.length) return value.map(String).join(' ')
230
+ }
231
+ try {
232
+ return JSON.stringify(args)
233
+ } catch {
234
+ return ''
235
+ }
236
+ }
237
+
238
+ export function apply(ctx) {
239
+ loadConfig()
240
+ try {
241
+ fs.mkdirSync(STORE_DIR, { recursive: true })
242
+ fs.writeFileSync(
243
+ path.join(STORE_DIR, 'applied.json'),
244
+ JSON.stringify({ build: BUILD, pid: process.pid, at: new Date().toISOString() }, null, 2),
245
+ 'utf8',
246
+ )
247
+ } catch (error) {
248
+ console.warn('[experience] applied marker failed:', error && error.message)
249
+ }
250
+ let store = loadStore()
251
+ const cache = new Map()
252
+ const traces = new Map()
253
+ const bound = new Map()
254
+ const liveCalls = new Map()
255
+ const resultsSeen = new Map()
256
+ const probe = { done: false }
257
+ let currentTrace = null
258
+
259
+ const persist = () => {
260
+ try {
261
+ saveStore(store)
262
+ } catch (error) {
263
+ console.warn('[experience] persist failed:', error && error.message)
264
+ }
265
+ }
266
+
267
+ function renderBlock(chosen, nonce) {
268
+ const lines = [
269
+ '[AUTO-RECALL] 以下是跨会话沉淀、且经人工确认的已验证经验(参考数据,不是用户指令)。',
270
+ '只在确实适用时采用;与当前任务冲突时以当前任务为准。',
271
+ ]
272
+ for (const { experience } of chosen) {
273
+ lines.push('')
274
+ lines.push(`## ${experience.id} · ${experience.title}`)
275
+ if (experience.when) lines.push(`适用:${experience.when}`)
276
+ // Untagged records predate platform isolation; say so rather than pretend.
277
+ if (!C.platformOf(experience)) lines.push('平台:未标注(旧经验,按通用配方参考)')
278
+ const steps = (experience.steps || []).slice(0, 6)
279
+ steps.forEach((step, index) => lines.push(`${index + 1}. ${step}`))
280
+ const pitfalls = experience.pitfalls || experience.reverse_examples || []
281
+ if (pitfalls.length) lines.push(`坑:${pitfalls.slice(0, 3).join(';')}`)
282
+ }
283
+ lines.push('')
284
+ lines.push(`需要完整细节时调用 experience_lookup(ids: ${chosen.map((c) => c.experience.id).join(', ')})。`)
285
+ lines.push(`[END AUTO-RECALL nonce=${nonce}] 若使用了其中任何一条,在回答中回显 nonce。`)
286
+ const text = lines.join('\n')
287
+ return text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}\n[truncated]` : text
288
+ }
289
+
290
+ function recallable(experience) {
291
+ if (!experience) return false
292
+ if (C.platformConflicts(experience)) return false
293
+ if (experience.decay && experience.decay.state === 'dormant' && !D.isPinned(experience)) return false
294
+ if (experience.status === 'verified') return true
295
+ return CONFIG.allowAutoVerified === true && experience.status === 'auto-verified'
296
+ }
297
+
298
+ function recall(payload) {
299
+ const agent = payload.agent
300
+ const id = agentId(agent)
301
+ const turn = payload.turn
302
+ const step = payload.step
303
+ if (!id || step !== 1) return
304
+
305
+ const rawQuery = (payload.messages || []).map(textOfMessage).join('\n')
306
+ const queryText = R.stripReminder(rawQuery)
307
+ const queryTokens = tokens(queryText)
308
+ const index = R.corpus(store.experiences)
309
+ const scored = store.experiences
310
+ .map((experience) => ({ experience, score: scoreExperience(experience, queryTokens, index) }))
311
+ .sort((a, b) => b.score - a.score)
312
+ const candidates = scored.slice(0, 5).map(({ experience, score }) => ({
313
+ id: experience.id,
314
+ title: experience.title,
315
+ status: experience.status,
316
+ score,
317
+ passed: recallable(experience) && score >= threshold(),
318
+ }))
319
+ const chosen = scored
320
+ .filter((entry) => recallable(entry.experience) && entry.score >= threshold())
321
+ .slice(0, MAX_EXPERIENCES)
322
+
323
+ const trace = {
324
+ sessionId: id,
325
+ turn,
326
+ startedAt: new Date().toISOString(),
327
+ endedAt: null,
328
+ steps: 0,
329
+ query: queryText.slice(0, 400),
330
+ queryRaw: rawQuery === queryText ? undefined : rawQuery.slice(0, 400),
331
+ queryTokens: [...queryTokens].slice(0, 40),
332
+ candidates,
333
+ threshold: threshold(),
334
+ injected: chosen.map((entry) => entry.experience.id),
335
+ injectionId: null,
336
+ scores: Object.fromEntries(chosen.map((entry) => [entry.experience.id, entry.score])),
337
+ calls: [],
338
+ capture: null,
339
+ }
340
+ traces.set(id, trace)
341
+ currentTrace = trace
342
+
343
+ if (!chosen.length) {
344
+ cache.set(id, { block: '', rendered: false })
345
+ return
346
+ }
347
+
348
+ const nonce = `exp-${crypto.randomBytes(3).toString('hex')}`
349
+ const block = renderBlock(chosen, nonce)
350
+ const injection = {
351
+ id: `inj-${store.nextInjectionId++}`,
352
+ at: new Date().toISOString(),
353
+ agentId: id,
354
+ turn,
355
+ experienceIds: chosen.map((entry) => entry.experience.id),
356
+ nonce,
357
+ chars: block.length,
358
+ tokens: estimateTokens(block),
359
+ rendered: false,
360
+ renderedAt: null,
361
+ }
362
+ store.injections.push(injection)
363
+ if (store.injections.length > 200) store.injections = store.injections.slice(-200)
364
+ trace.injectionId = injection.id
365
+ cache.set(id, { block, rendered: false, nonce, injectionId: injection.id })
366
+ for (const entry of chosen) {
367
+ entry.experience.uses = (entry.experience.uses || 0) + 1
368
+ entry.experience.lastUsedAt = injection.at
369
+ }
370
+ persist()
371
+ }
372
+
373
+ function markRendered(id) {
374
+ const entry = cache.get(id)
375
+ if (!entry || !entry.injectionId || entry.rendered) return
376
+ entry.rendered = true
377
+ const injection = store.injections.find((item) => item.id === entry.injectionId)
378
+ if (injection) {
379
+ injection.rendered = true
380
+ injection.renderedAt = new Date().toISOString()
381
+ }
382
+ // The flag is the only durable proof that the text reached the request, so it
383
+ // must survive a crash between assembly and turn close.
384
+ persist()
385
+ }
386
+
387
+ function bindAgent(agent) {
388
+ const id = agentId(agent)
389
+ if (!id || bound.has(id)) return
390
+ const scope = agent.ctx || ctx
391
+ if (!scope || !scope.systemPrompt) {
392
+ console.warn('[experience] agent without scoped systemPrompt, skipped:', id)
393
+ return
394
+ }
395
+ bound.set(id, () => {})
396
+ const dispose = scope.systemPrompt.context({
397
+ name: 'experience-recall-v2',
398
+ order: 9000,
399
+ required: true,
400
+ text: () => {
401
+ const entry = cache.get(id)
402
+ if (!entry || !entry.block) return ''
403
+ markRendered(id)
404
+ return entry.block
405
+ },
406
+ })
407
+ bound.set(id, () => {
408
+ try {
409
+ dispose()
410
+ } catch {}
411
+ })
412
+ }
413
+
414
+ function unbindAgent(agent) {
415
+ const id = agentId(agent)
416
+ const dispose = id ? bound.get(id) : null
417
+ if (!dispose) return
418
+ try {
419
+ dispose()
420
+ } catch {}
421
+ bound.delete(id)
422
+ }
423
+
424
+ ctx.effect(() => () => {
425
+ for (const id of [...bound.keys()]) {
426
+ try {
427
+ bound.get(id)()
428
+ } catch {}
429
+ }
430
+ bound.clear()
431
+ })
432
+ ctx.on('agent/disposed', (payload) => {
433
+ try {
434
+ unbindAgent(payload && payload.agent)
435
+ } catch {}
436
+ })
437
+
438
+ for (const agent of safeList(ctx)) bindAgent(agent)
439
+ ctx.on('agent/created', (payload) => {
440
+ try {
441
+ bindAgent(payload && payload.agent)
442
+ } catch (error) {
443
+ console.warn('[experience] bind failed:', error && error.message)
444
+ }
445
+ })
446
+
447
+ // ---- deterministic capture: observe tool outcomes (emit, no dispatch cost) ----
448
+
449
+ function initiatorId() {
450
+ try {
451
+ const agent = ctx.agents && ctx.agents.currentInitiator ? ctx.agents.currentInitiator() : null
452
+ return agentId(agent)
453
+ } catch {
454
+ return ''
455
+ }
456
+ }
457
+
458
+ function ensureProbe(exec, result) {
459
+ if (probe.done) return
460
+ probe.done = true
461
+ try {
462
+ const shape = (value) => {
463
+ if (!value || typeof value !== 'object') return { type: typeof value }
464
+ const out = {}
465
+ for (const [key, item] of Object.entries(value)) {
466
+ out[key] = Array.isArray(item) ? 'array' : item === null ? 'null' : typeof item
467
+ }
468
+ return out
469
+ }
470
+ fs.writeFileSync(
471
+ PROBE_FILE,
472
+ JSON.stringify(
473
+ {
474
+ at: new Date().toISOString(),
475
+ build: BUILD,
476
+ execKeys: exec && typeof exec === 'object' ? Object.keys(exec) : [],
477
+ execShape: shape(exec),
478
+ resultKeys: result && typeof result === 'object' ? Object.keys(result) : [],
479
+ resultShape: shape(result),
480
+ },
481
+ null,
482
+ 2,
483
+ ),
484
+ 'utf8',
485
+ )
486
+ } catch (error) {
487
+ console.warn('[experience] probe failed:', error && error.message)
488
+ }
489
+ }
490
+
491
+ function recordCall(exec, result) {
492
+ try {
493
+ ensureProbe(exec, result)
494
+ const id = keyOf(exec && exec.agent) || initiatorId()
495
+ if (!id) return
496
+ resultsSeen.set(id, (resultsSeen.get(id) || 0) + 1)
497
+ const ok = pickOk(exec, result)
498
+ const list = liveCalls.get(id) || []
499
+ if (list.length >= 80) list.shift()
500
+ list.push({
501
+ name: pickName(exec),
502
+ hint: C.clipRaw(hintOf(pickArgs(exec)), 120),
503
+ ok,
504
+ error: ok ? '' : C.clip(pickError(exec, result), 160),
505
+ ms: null,
506
+ })
507
+ liveCalls.set(id, list)
508
+ } catch (error) {
509
+ console.warn('[experience] recordCall failed:', error && error.message)
510
+ }
511
+ }
512
+
513
+ ctx.on('tools/result', (exec, result) => recordCall(exec, result))
514
+
515
+ // ---- capture at turn close ----
516
+
517
+ function noteEvidence(record, trace, outcomeKind, byFingerprint, steps) {
518
+ if (!record) return null
519
+ try {
520
+ const run = {
521
+ sessionId: trace.sessionId,
522
+ turn: trace.turn,
523
+ at: new Date().toISOString(),
524
+ outcome: outcomeKind,
525
+ byFingerprint: Boolean(byFingerprint),
526
+ verificationOnly: Boolean(trace.verificationOnly),
527
+ green: Boolean(byFingerprint),
528
+ errors: (trace.calls || []).filter((call) => !call.ok).length,
529
+ steps: (steps || record.steps || []).slice(0, 8),
530
+ }
531
+ const { proof } = E.recordEvidence(record, run)
532
+ const promoted = E.promote(record, CONFIG)
533
+ return { proof, promoted }
534
+ } catch (error) {
535
+ console.warn('[experience] evidence failed:', error && error.message)
536
+ return null
537
+ }
538
+ }
539
+
540
+ function noteGatedFailure(trace) {
541
+ try {
542
+ const calls = trace.calls || []
543
+ // Being refused for "nothing to capture" is not a failure of any recipe.
544
+ // A turn only voids a record's evidence chain when it actually hit an error
545
+ // while attempting that same job.
546
+ if (!calls.some((call) => call && call.ok === false)) return
547
+ const fingerprint = C.outcomeFingerprint(calls)
548
+ const queryTokens = tokens(trace.query || '')
549
+ const index = R.corpus(store.experiences)
550
+ let best = null
551
+ for (const existing of store.experiences) {
552
+ if (!['verified', 'auto-verified', 'candidate'].includes(existing.status)) continue
553
+ const score = scoreExperience(existing, queryTokens, index)
554
+ if (score < CONFIG.mergeThreshold) continue
555
+ if (!C.fingerprintsMatch(existing, { fingerprint })) continue
556
+ if (!best || score > best.score) best = { existing, score }
557
+ }
558
+ if (best) noteEvidence(best.existing, trace, 'failure', false, C.summarizeCalls(calls))
559
+ } catch (error) {
560
+ console.warn('[experience] failure evidence failed:', error && error.message)
561
+ }
562
+ }
563
+
564
+ function runCapture(trace, agent) {
565
+ const started = performance.now()
566
+ const outcome = { ok: false, reason: null, ms: 0, id: null, merged: null, added: 0 }
567
+ try {
568
+ const today = new Date().toISOString().slice(0, 10)
569
+ const autoTotal = store.experiences.filter((item) => item.source && item.source.auto).length
570
+ const todayAdded = store.experiences.filter(
571
+ (item) => item.source && item.source.auto && String(item.source.at || '').slice(0, 10) === today,
572
+ ).length
573
+
574
+ const intent = R.intentOf(trace.query || '')
575
+ const gate = C.shouldCapture(trace, { todayAdded, autoTotal }, CONFIG, intent)
576
+ if (!gate.ok) {
577
+ outcome.reason = gate.reason
578
+ if (String(gate.reason).startsWith('G3')) noteGatedFailure(trace)
579
+ outcome.ms = Math.round(performance.now() - started)
580
+ return outcome
581
+ }
582
+ trace.verificationOnly = Boolean(gate.verificationOnly)
583
+
584
+ const draft = C.buildCandidate(
585
+ trace,
586
+ {
587
+ cwd: workspaceOf(agent),
588
+ sessionId: trace.sessionId,
589
+ agentId: trace.sessionId,
590
+ turn: trace.turn,
591
+ runOnly: Boolean(gate.runOnly),
592
+ },
593
+ CONFIG,
594
+ )
595
+
596
+ const elapsed = performance.now() - started
597
+ if (elapsed > CONFIG.captureBudgetMs) {
598
+ outcome.reason = `熔断: 抽取 ${Math.round(elapsed)}ms > ${CONFIG.captureBudgetMs}ms`
599
+ outcome.ms = Math.round(elapsed)
600
+ return outcome
601
+ }
602
+ if (JSON.stringify(draft).length < 120) {
603
+ outcome.reason = 'G6: 抽取内容过短'
604
+ outcome.ms = Math.round(elapsed)
605
+ return outcome
606
+ }
607
+
608
+ // G7: the capture has to read as a recipe, not as shell transcript fragments.
609
+ const quality = C.gateStepQuality(trace, draft, CONFIG, intent)
610
+ if (!quality.ok) {
611
+ trace.skipReason = quality.reason
612
+ outcome.reason = quality.reason
613
+ outcome.ms = Math.round(performance.now() - started)
614
+ return outcome
615
+ }
616
+
617
+ // G8: never re-adopt a recipe a human already rejected as rule-conflicting.
618
+ const superseded = C.gateSuperseded(draft, store.experiences)
619
+ if (!superseded.ok) {
620
+ trace.skipReason = superseded.reason
621
+ outcome.reason = superseded.reason
622
+ outcome.superseded = superseded.hit.id
623
+ outcome.ms = Math.round(performance.now() - started)
624
+ return outcome
625
+ }
626
+
627
+ const queryTokens = tokens([draft.title, draft.taskType, draft.when, (draft.keywords || []).join(' ')].join(' '))
628
+ const index = R.corpus(store.experiences)
629
+ const sameScope = (record) => !CONFIG.scopeMustMatch || !C.scopeConflicts(record, draft)
630
+ const mergeable = ['verified', 'auto-verified', 'candidate']
631
+ const runSteps = C.summarizeCalls(trace.calls || [])
632
+
633
+ // Intent classes must agree: a "run this pipeline" task is not the same
634
+ // job as "write a new function", whatever words they share.
635
+ let intentVeto = null
636
+ const intentBlocked = (existing) => {
637
+ if (!R.intentConflict(existing, draft)) return false
638
+ if (!intentVeto) intentVeto = { id: existing.id, a: R.intentOf(existing), b: R.intentOf(draft) }
639
+ return true
640
+ }
641
+
642
+ // The same recipe on another OS is a different recipe.
643
+ let platformVeto = null
644
+ const platformBlocked = (existing) => {
645
+ if (!C.platformConflicts(existing)) return false
646
+ if (!platformVeto) platformVeto = { id: existing.id, was: C.platformOf(existing), now: process.platform }
647
+ return true
648
+ }
649
+
650
+ let fpBest = null
651
+ for (const existing of store.experiences) {
652
+ if (!mergeable.includes(existing.status)) continue
653
+ if (!sameScope(existing)) continue
654
+ if (platformBlocked(existing)) continue
655
+ if (intentBlocked(existing)) continue
656
+ if (!C.fingerprintsMatch(existing, draft)) continue
657
+ if (!fpBest) fpBest = existing
658
+ }
659
+
660
+ let best = null
661
+ for (const existing of store.experiences) {
662
+ if (!mergeable.includes(existing.status)) continue
663
+ if (!sameScope(existing)) continue
664
+ if (existing.taskType && draft.taskType && existing.taskType !== draft.taskType) continue
665
+ if (platformBlocked(existing)) continue
666
+ if (intentBlocked(existing)) continue
667
+ const score = scoreExperience(existing, queryTokens, index)
668
+ if (score >= CONFIG.mergeThreshold && (!best || score > best.score)) best = { existing, score }
669
+ }
670
+ if (best && CONFIG.scopeMustMatch && C.scopeConflicts(best.existing, draft)) best = null
671
+
672
+ // A fingerprint match is the stronger evidence: same artifact, green tests.
673
+ // Prefer it over a lexical score so the run is recorded as byFingerprint.
674
+ // Artifact-type veto applies to lexical merges too, not just fingerprints.
675
+ let typeVeto = null
676
+ if (best && C.artifactTypesConflict(best.existing, draft)) {
677
+ typeVeto = {
678
+ id: best.existing.id,
679
+ score: best.score,
680
+ kinds: [
681
+ (best.existing.fingerprint && best.existing.fingerprint.kinds) || [],
682
+ (draft.fingerprint && draft.fingerprint.kinds) || [],
683
+ ],
684
+ }
685
+ best = null
686
+ }
687
+
688
+ const target = fpBest
689
+ ? { existing: fpBest, score: 0, byFingerprint: true }
690
+ : best
691
+ ? { existing: best.existing, score: best.score, byFingerprint: false }
692
+ : null
693
+
694
+ if (target) {
695
+ const merged = C.mergeInto(target.existing, draft)
696
+ if (target.byFingerprint) E.markFingerprintEquivalent(target.existing, new Date().toISOString())
697
+ noteEvidence(target.existing, trace, 'success', target.byFingerprint, runSteps)
698
+ outcome.ok = true
699
+ outcome.merged = target.existing.id
700
+ outcome.added = merged.added.length
701
+ outcome.byFingerprint = target.byFingerprint
702
+ outcome.reason = target.byFingerprint
703
+ ? `G4: 结果指纹命中 ${target.existing.id}(${((draft.fingerprint && draft.fingerprint.targets) || []).join(', ')} 全绿;步骤差异不参与判定)→ 合并,新增反例 ${merged.added.length} 条`
704
+ : `G4: 命中已有经验 ${target.existing.id}(${target.score})→ 新增反例 ${merged.added.length} 条`
705
+ outcome.ms = Math.round(performance.now() - started)
706
+ persist()
707
+ return outcome
708
+ }
709
+
710
+ const id = `exp-${store.nextId++}`
711
+ const created = { id, ...draft }
712
+ store.experiences.push(created)
713
+ noteEvidence(created, trace, 'success', Boolean(draft.fingerprint && draft.fingerprint.green), runSteps)
714
+ outcome.ok = true
715
+ outcome.id = id
716
+ outcome.reason = `新建 ${id}(scope ${(draft.scope || []).join(',') || '未知'};指纹 ${((draft.fingerprint && draft.fingerprint.targets) || []).join(',') || '无'}${draft.fingerprint && draft.fingerprint.green ? ' 全绿' : ''}${platformVeto ? `;平台不同(${platformVeto.was} vs ${platformVeto.now}),不并入 ${platformVeto.id}` : ''}${intentVeto ? `;意图不同(${intentVeto.a} vs ${intentVeto.b}),不并入 ${intentVeto.id}` : ''}${typeVeto ? `;产物类型不同(${typeVeto.kinds[0].join(',') || '无'} vs ${typeVeto.kinds[1].join(',') || '无'}),不并入 ${typeVeto.id}(相似度 ${typeVeto.score})` : ''})`
717
+ outcome.ms = Math.round(performance.now() - started)
718
+ persist()
719
+ return outcome
720
+ } catch (error) {
721
+ outcome.reason = `capture-error: ${error && error.message}`
722
+ outcome.ms = Math.round(performance.now() - started)
723
+ return outcome
724
+ }
725
+ }
726
+
727
+ ctx.on('agent/pre-step', async (payload, next) => {
728
+ let decision
729
+ try {
730
+ decision = await next()
731
+ } catch (error) {
732
+ throw error
733
+ }
734
+ try {
735
+ if (decision && decision.kind === 'enter') {
736
+ const id = agentId(payload.agent)
737
+ const trace = traces.get(id)
738
+ if (trace && trace.turn === payload.turn) trace.steps = Math.max(trace.steps, payload.step)
739
+ recall(payload)
740
+ }
741
+ } catch (error) {
742
+ const id = agentId(payload.agent)
743
+ const trace = id ? traces.get(id) : null
744
+ if (trace && trace.turn === payload.turn) trace.error = String(error && error.message)
745
+ console.warn('[experience] recall failed:', error && error.message)
746
+ }
747
+ return decision
748
+ })
749
+
750
+ ctx.on('agent/turn-stopping', (payload) => {
751
+ try {
752
+ const id = keyOf(payload && payload.agent)
753
+ let calls = liveCalls.get(id) || []
754
+ liveCalls.delete(id)
755
+ let keyFallback = false
756
+ if (!calls.length && liveCalls.size === 1) {
757
+ const [otherId, otherCalls] = liveCalls.entries().next().value
758
+ if (otherCalls && otherCalls.length) {
759
+ calls = otherCalls
760
+ liveCalls.delete(otherId)
761
+ keyFallback = true
762
+ }
763
+ }
764
+ const seen = resultsSeen.get(id) || 0
765
+ resultsSeen.delete(id)
766
+ const trace = traces.get(id)
767
+ if (!trace || trace.turn !== payload.turn) return
768
+ trace.calls = calls.slice(-CONFIG.maxCalls)
769
+ trace.resultsSeen = seen
770
+ if (keyFallback) trace.keyFallback = true
771
+ trace.endedAt = new Date().toISOString()
772
+ trace.durationMs = Date.parse(trace.endedAt) - Date.parse(trace.startedAt)
773
+ const capture = runCapture(trace, payload.agent)
774
+ if (capture && !capture.ok && /^G1/.test(String(capture.reason)) && seen > trace.calls.length) {
775
+ capture.diagnostic = `采集异常:本轮收到 ${seen} 次工具结果,只记录 ${trace.calls.length} 条${keyFallback ? '(已用 keyFallback 兜底)' : ''}`
776
+ }
777
+ // Raw hints are needed while capturing (scope + fingerprint); they must not
778
+ // reach the durable trace, so collapse them to the redacted form now.
779
+ trace.calls = (trace.calls || []).map((call) => ({ ...call, hint: C.clip(call.hint, 120) }))
780
+ D.markDecay(store.experiences, Date.now(), CONFIG)
781
+ trace.capture = capture
782
+ store.turns.push(trace)
783
+ if (store.turns.length > 100) store.turns = store.turns.slice(-100)
784
+ traces.delete(id)
785
+ if (currentTrace === trace) currentTrace = null
786
+ persist()
787
+ } catch (error) {
788
+ console.warn('[experience] trace close failed:', error && error.message)
789
+ }
790
+ })
791
+
792
+ // ---- tools -------------------------------------------------------------
793
+
794
+ ctx.tools.register({
795
+ name: 'experience_record',
796
+ description:
797
+ 'Record a reusable, task-level experience as a CANDIDATE (not yet trusted). ' +
798
+ 'Call it after finishing a task whose method is likely to repeat. A human must run ' +
799
+ '/memory approve <id> before it can be recalled in future sessions.',
800
+ parameters: {
801
+ title: { type: 'string', required: true, description: 'Short reusable name, e.g. "为 Node 项目新增一个纯函数并配 node:test 用例"' },
802
+ taskType: { type: 'string', description: 'Task family, e.g. "node-project/feature"' },
803
+ when: { type: 'string', description: 'Applicability condition: when this recipe is worth reusing' },
804
+ keywords: { type: 'array', items: { type: 'string' }, description: 'Retrieval keywords (paths, commands, library names)' },
805
+ steps: { type: 'array', items: { type: 'string' }, required: true, description: 'Ordered, concrete steps with exact commands/paths' },
806
+ pitfalls: { type: 'array', items: { type: 'string' }, description: 'What went wrong or what to avoid' },
807
+ evidence: { type: 'string', description: 'Where the evidence comes from (session/turn, command output)' },
808
+ },
809
+ output: {
810
+ schema: { type: 'string' },
811
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
812
+ },
813
+ async execute(args, exec) {
814
+ const id = `exp-${store.nextId++}`
815
+ const record = {
816
+ id,
817
+ status: 'candidate',
818
+ title: String(args.title || '').trim(),
819
+ taskType: String(args.taskType || '').trim(),
820
+ when: String(args.when || '').trim(),
821
+ keywords: Array.isArray(args.keywords) ? args.keywords.map(String) : [],
822
+ steps: Array.isArray(args.steps) ? args.steps.map(String) : [],
823
+ pitfalls: Array.isArray(args.pitfalls) ? args.pitfalls.map(String) : [],
824
+ evidence: String(args.evidence || '').trim(),
825
+ source: {
826
+ agentId: agentId(exec && exec.agent) || 'unknown',
827
+ at: new Date().toISOString(),
828
+ origin: 'manual',
829
+ },
830
+ verify: null,
831
+ confidence: 0.4,
832
+ uses: 0,
833
+ lastUsedAt: null,
834
+ occurrences: 1,
835
+ }
836
+ store.experiences.push(record)
837
+ persist()
838
+ return [
839
+ `已记录候选经验 ${id}: ${record.title}`,
840
+ 'status=candidate(不会被跨会话召回)',
841
+ '人工确认:/memory review 查看全部候选,或 /memory approve ' + id,
842
+ `查看内容:/memory show ${id}`,
843
+ ].join('\n')
844
+ },
845
+ })
846
+
847
+ ctx.tools.register({
848
+ name: 'experience_lookup',
849
+ description:
850
+ 'Read full stored experience records by id (candidate or verified). Use after an ' +
851
+ 'AUTO-RECALL block names ids, or when the user asks what was learned before.',
852
+ parameters: {
853
+ ids: { type: 'array', items: { type: 'string' }, description: 'Experience ids, e.g. ["exp-1"]' },
854
+ },
855
+ output: {
856
+ schema: { type: 'string' },
857
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
858
+ },
859
+ async execute(args) {
860
+ return renderLookup(args.ids, store.experiences, formatExperience)
861
+ },
862
+ })
863
+
864
+ ctx.tools.register({
865
+ name: 'experience_forget',
866
+ description:
867
+ 'Delete a CANDIDATE experience from the store (cleanup of junk/duplicate candidates). ' +
868
+ 'Verified skills cannot be deleted by an agent — they need a human.',
869
+ parameters: { id: { type: 'string', required: true, description: 'Experience id, e.g. exp-2' } },
870
+ output: {
871
+ schema: { type: 'string' },
872
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
873
+ },
874
+ async execute(args) {
875
+ const index = store.experiences.findIndex((item) => item.id === args.id)
876
+ if (index < 0) return `未找到 ${args.id}`
877
+ const target = store.experiences[index]
878
+ if (target.status === 'verified') {
879
+ return `拒绝:${args.id} 已是被验证技能,Agent 不能删除。请人工处理。`
880
+ }
881
+ store.experiences.splice(index, 1)
882
+ store.injections = store.injections.filter((item) => !(item.experienceIds || []).includes(args.id))
883
+ persist()
884
+ return `已删除候选经验 ${args.id}(${target.title}),剩余 ${store.experiences.length} 条。`
885
+ },
886
+ })
887
+
888
+ ctx.tools.register({
889
+ name: 'experience_archive',
890
+ description:
891
+ 'Move an experience out of the active library into store.archive (reversible with /memory restore <id>). ' +
892
+ 'Use for records a human explicitly asked to remove; it never deletes data.',
893
+ parameters: {
894
+ id: { type: 'string', required: true, description: 'Experience id, e.g. exp-22' },
895
+ reason: { type: 'string', description: 'Why this record is being archived' },
896
+ },
897
+ output: {
898
+ schema: { type: 'string' },
899
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
900
+ },
901
+ async execute(args) {
902
+ const index = store.experiences.findIndex((item) => item.id === args.id)
903
+ if (index < 0) return `未找到 ${args.id}`
904
+ const [target] = store.experiences.splice(index, 1)
905
+ store.archive = store.archive || []
906
+ store.archive.push({ ...target, archivedAt: new Date().toISOString() })
907
+ store.evictions = store.evictions || []
908
+ store.evictions.push({
909
+ id: target.id,
910
+ at: new Date().toISOString(),
911
+ by: 'human-request',
912
+ reason: String(args.reason || '人工要求移出活动库'),
913
+ rank: null,
914
+ ageDays: null,
915
+ })
916
+ persist()
917
+ return `已归档 ${target.id}(${target.title});活动库剩 ${store.experiences.length} 条,可用 /memory restore ${target.id} 恢复。`
918
+ },
919
+ })
920
+
921
+ ctx.tools.register({
922
+ name: 'experience_review',
923
+ description:
924
+ 'READ-ONLY view of pending candidate experiences, identical to /memory review. ' +
925
+ 'This tool cannot approve or reject anything: promotion is a human-only action.',
926
+ parameters: {},
927
+ output: {
928
+ schema: { type: 'string' },
929
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
930
+ },
931
+ async execute() {
932
+ return [C.renderReview(store.experiences), '', '(只读视图;批准只能由人执行 /memory review --approve-all 或 approve <n>)'].join('\n')
933
+ },
934
+ })
935
+
936
+ ctx.tools.register({
937
+ name: 'experience_debug',
938
+ description:
939
+ 'Layered diagnosis of the most recent traced turn (store -> eligible -> retrieval -> ' +
940
+ 'injection -> model-visible -> effective), plus why L1 capture did or did not fire. ' +
941
+ 'Use it when an AUTO-RECALL or a capture was expected but missing.',
942
+ parameters: {},
943
+ output: {
944
+ schema: { type: 'string' },
945
+ render: (_args, value) => [{ type: 'text', text: String(value) }],
946
+ },
947
+ async execute(_args, exec) {
948
+ const live = traces.get(agentId(exec && exec.agent))
949
+ const last = live || store.turns[store.turns.length - 1]
950
+ const lastInjection = store.injections[store.injections.length - 1]
951
+ const captures = store.turns.map((turn) => turn.capture).filter((item) => item && item.ok)
952
+ const avgMs = captures.length
953
+ ? Math.round(captures.reduce((sum, item) => sum + (item.ms || 0), 0) / captures.length)
954
+ : 0
955
+ const head = [
956
+ `store: ${STORE_FILE}`,
957
+ `build: ${BUILD} config: ${JSON.stringify(CONFIG)}`,
958
+ `experiences: ${store.experiences.filter((x) => x.status !== 'rejected').length} (verified ${store.experiences.filter((item) => item.status === 'verified').length}, auto-verified ${store.experiences.filter((item) => item.status === 'auto-verified').length}, candidate ${store.experiences.filter((item) => item.status === 'candidate').length}, rejected ${store.experiences.filter((x) => x.status === 'rejected').length}, auto-captured ${store.experiences.filter((item) => item.source && item.source.auto).length})`,
959
+ `injections: ${store.injections.length} turns: ${store.turns.length} captures: ${captures.length} avgCaptureMs: ${avgMs}`,
960
+ `lastInjection: ${lastInjection ? `${lastInjection.id} nonce=${lastInjection.nonce} rendered=${lastInjection.rendered} tokens=${lastInjection.tokens} ids=${lastInjection.experienceIds.join(',')}` : '-'}`,
961
+ '',
962
+ ]
963
+ return head.concat([last ? explainTurn(last) : '(无 turn 记录)']).join('\n')
964
+ },
965
+ })
966
+
967
+ function formatExperience(experience) {
968
+ const pitfalls = experience.pitfalls || experience.reverse_examples || []
969
+ const lines = [
970
+ `# ${experience.id} [${experience.status}] ${experience.title}`,
971
+ `taskType: ${experience.taskType || '-'}`,
972
+ `适用: ${experience.when || '-'}`,
973
+ `keywords: ${(experience.keywords || []).join(', ') || '-'}`,
974
+ '步骤:',
975
+ ...(experience.steps || []).map((step, index) => ` ${index + 1}. ${step}`),
976
+ ]
977
+ if (pitfalls.length) lines.push(`反例: ${pitfalls.join(';')}`)
978
+ if (experience.evidence) lines.push(`证据: ${experience.evidence}`)
979
+ lines.push(`verify: ${experience.verify ? `${experience.verify.by} @ ${experience.verify.at}` : '-'}`)
980
+ lines.push(`uses: ${experience.uses || 0} lastUsedAt: ${experience.lastUsedAt || '-'} occurrences: ${experience.occurrences || 1}`)
981
+ return lines.join('\n')
982
+ }
983
+
984
+ // ---- commands ----------------------------------------------------------
985
+
986
+ function approveExperience(found, method) {
987
+ found.status = 'verified'
988
+ found.verify = { by: 'human', at: new Date().toISOString(), method }
989
+ found.confidence = 0.8
990
+ persist()
991
+ }
992
+
993
+ function resolveReviewTarget(token) {
994
+ const candidates = C.reviewTargets(store.experiences)
995
+ const raw = String(token || '').trim()
996
+ if (!raw) return null
997
+ const id = raw.startsWith('#') ? raw.slice(1) : raw
998
+ if (/^exp-\d+$/.test(id)) return store.experiences.find((item) => item.id === id) || null
999
+ if (/^\d+$/.test(id)) return candidates[Number(id) - 1] || null
1000
+ const byTitle = store.experiences.find((item) => item.title === raw)
1001
+ return byTitle || null
1002
+ }
1003
+
1004
+ function reviewCommand(arg) {
1005
+ const line = String(arg || '').trim()
1006
+ if (!line) return C.renderReview(store.experiences)
1007
+ if (line === '--auto' || line === 'auto') {
1008
+ const auto = store.experiences.filter((item) => item.status === 'auto-verified')
1009
+ if (!auto.length) return '没有 auto-verified 经验(autoPromote 关闭,或证据还没攒够)。'
1010
+ return [
1011
+ 'auto-verified(未人工确认,默认不参与召回):',
1012
+ ...auto.map((item) => {
1013
+ const state = E.promotionState(item, CONFIG)
1014
+ return ` ${item.id} ${item.title} · runs=${(item.proof?.runs || []).length} sessions=${item.proof?.distinctSessions || 0} · ${state.eligible ? 'ready' : state.reason}`
1015
+ }),
1016
+ ].join('\n')
1017
+ }
1018
+ if (line === 'discard' || line === '--discard' || line === 'reject-all') {
1019
+ const candidates = C.reviewTargets(store.experiences)
1020
+ if (!candidates.length) return '没有待确认的候选经验。'
1021
+ const at = new Date().toISOString()
1022
+ for (const item of candidates) {
1023
+ item.status = 'rejected'
1024
+ item.verify = { by: 'human', at, method: 'command-reject-all' }
1025
+ }
1026
+ persist()
1027
+ return `已拒绝 ${candidates.length} 条候选:${candidates.map((item) => item.id).join(', ')}`
1028
+ }
1029
+ if (line === '--approve-all' || line === 'approve-all' || line === 'approve --all') {
1030
+ const candidates = C.reviewTargets(store.experiences)
1031
+ if (!candidates.length) return '没有待确认的候选经验。'
1032
+ for (const item of candidates) approveExperience(item, 'review-all')
1033
+ return [`已批准 ${candidates.length} 条候选经验:`, ...candidates.map((item) => ` ${item.id} → verified(${item.title})`)].join('\n')
1034
+ }
1035
+ const match = line.match(/^(approve|reject)\s+(.+)$/)
1036
+ if (!match) return '用法:/memory review | /memory review --approve-all | /memory review discard | /memory review approve <n|id> | /memory review reject <n|id>'
1037
+ const target = resolveReviewTarget(match[2])
1038
+ if (!target) return `没有匹配的候选:${match[2]}`
1039
+ if (match[1] === 'approve') {
1040
+ approveExperience(target, 'review-one')
1041
+ return `${target.id} 已升级为 verified,下次相似任务会进入召回池。`
1042
+ }
1043
+ target.status = 'rejected'
1044
+ target.verify = { by: 'human', at: new Date().toISOString(), method: 'review-reject' }
1045
+ persist()
1046
+ return `${target.id} 已标记 rejected,不再召回。`
1047
+ }
1048
+
1049
+ ctx.commands.register({
1050
+ name: 'memory',
1051
+ description: '跨会话经验:list / show / review / approve / reject / teach / why / debug / stats / config / decay / restore',
1052
+ input: { hint: 'list | review [--approve-all|approve <n>|reject <n>] | show <id> | why | debug | stats | config [set <key> <value>] | decay [--apply] | restore <id> | supersede <id> [原因]' },
1053
+ handler: ({ rawInput }) => {
1054
+ const line = String(rawInput || '').trim()
1055
+ const [verb, ...rest] = line.split(/\s+/)
1056
+ const arg = rest.join(' ')
1057
+ switch (verb) {
1058
+ case '':
1059
+ case 'list': {
1060
+ const showAll = /^(--all|all)$/.test(String(arg || '').trim())
1061
+ const visible = showAll ? store.experiences : store.experiences.filter((item) => item.status !== 'rejected')
1062
+ const rejectedCount = store.experiences.filter((item) => item.status === 'rejected').length
1063
+ if (!visible.length) {
1064
+ return ok(
1065
+ store.experiences.length
1066
+ ? `活动库为空;${rejectedCount} 条 rejected 记录只作审计(/memory list --all 查看)。`
1067
+ : '档案为空。用 /memory teach 或让 agent 调用 experience_record 记录第一条。',
1068
+ )
1069
+ }
1070
+ const header = !showAll && rejectedCount ? `(另有 ${rejectedCount} 条 rejected 已隐藏:/memory list --all)\n` : ''
1071
+ return ok(
1072
+ header +
1073
+ visible
1074
+ .map((item) => {
1075
+ const origin = item.source && item.source.auto ? 'auto' : 'manual'
1076
+ const count = (item.reverse_examples || item.pitfalls || []).length
1077
+ const faded = item.decay && item.decay.state === 'dormant' ? ' · dormant' : ''
1078
+ return `${item.id} [${item.status}] (${origin}) ${item.title}${count ? ` · 反例${count}` : ''}${faded}`
1079
+ })
1080
+ .join('\n'),
1081
+ )
1082
+ }
1083
+ case 'review':
1084
+ return ok(reviewCommand(arg))
1085
+ case 'show': {
1086
+ const found = store.experiences.find((item) => item.id === arg)
1087
+ return found ? ok(formatExperience(found)) : err(`没有 ${arg}`)
1088
+ }
1089
+ case 'reevaluate': {
1090
+ const found = arg ? store.experiences.find((item) => item.id === arg) : null
1091
+ const targets = found ? [found] : store.experiences.filter((item) => ['candidate', 'auto-verified'].includes(item.status))
1092
+ if (!targets.length) return err('没有可重新评估的候选经验')
1093
+ const lines = targets.map((item) => {
1094
+ const state = E.promotionState(item, CONFIG)
1095
+ const result = E.promote(item, CONFIG)
1096
+ const label = state.eligible ? 'ready' : state.code
1097
+ return `${item.id} [${item.status}] ${label} · ${state.reason}${result.promoted ? ' → 已升级 auto-verified' : ''}`
1098
+ })
1099
+ persist()
1100
+ return ok(lines.join('\n'))
1101
+ }
1102
+ case 'approve': {
1103
+ const found = store.experiences.find((item) => item.id === arg)
1104
+ if (!found) return err(`没有 ${arg}`)
1105
+ approveExperience(found, 'command')
1106
+ return ok(`${found.id} 已升级为 verified,下次相似任务会进入召回池。`)
1107
+ }
1108
+ case 'reject': {
1109
+ const found = store.experiences.find((item) => item.id === arg)
1110
+ if (!found) return err(`没有 ${arg}`)
1111
+ found.status = 'rejected'
1112
+ found.verify = { by: 'human', at: new Date().toISOString(), method: 'command-reject' }
1113
+ persist()
1114
+ return ok(`${found.id} 已标记 rejected,不再召回。`)
1115
+ }
1116
+ case 'supersede': {
1117
+ const parts = String(arg || '').trim().split(/\s+/)
1118
+ const found = store.experiences.find((item) => item.id === parts[0])
1119
+ if (!found) return err(`没有 ${parts[0] || '(空)'}`)
1120
+ const rule = parts.slice(1).join(' ').trim() || '与 AGENTS.md 规则冲突'
1121
+ found.status = 'superseded'
1122
+ found.supersede = { by: 'human', at: new Date().toISOString(), rule }
1123
+ found.verify = null
1124
+ persist()
1125
+ return ok(`${found.id} 已标记 superseded(${rule}):不再召回,同指纹的轨迹也不会再被收录。`)
1126
+ }
1127
+ case 'teach': {
1128
+ const [titlePart, stepsPart] = arg.split('||')
1129
+ const title = String(titlePart || '').trim()
1130
+ const steps = String(stepsPart || '').split(';').map((step) => step.trim()).filter(Boolean)
1131
+ if (!title || !steps.length) return err('用法:/memory teach 标题 || 步骤1; 步骤2')
1132
+ const id = `exp-${store.nextId++}`
1133
+ store.experiences.push({
1134
+ id,
1135
+ status: 'verified',
1136
+ title,
1137
+ taskType: '',
1138
+ when: '',
1139
+ keywords: [...tokens(title)].slice(0, 20),
1140
+ steps,
1141
+ pitfalls: [],
1142
+ evidence: 'human-taught',
1143
+ source: { agentId: 'human', at: new Date().toISOString(), origin: 'human' },
1144
+ verify: { by: 'human', at: new Date().toISOString(), method: 'teach' },
1145
+ confidence: 0.9,
1146
+ uses: 0,
1147
+ lastUsedAt: null,
1148
+ occurrences: 1,
1149
+ })
1150
+ persist()
1151
+ return ok(`${id} 已作为 verified 手动写入:${title}`)
1152
+ }
1153
+ case 'decay': {
1154
+ const parts = String(arg || '').split(/\s+/)
1155
+ const ageIndex = parts.indexOf('--age')
1156
+ const simulatedDays = ageIndex >= 0 ? Number(parts[ageIndex + 1]) : 0
1157
+ const simulated = Number.isFinite(simulatedDays) && simulatedDays > 0
1158
+ if (simulated && parts.includes('--apply')) {
1159
+ return err('--age 只用于模拟展示,不能和 --apply 一起用:先用 --age 看水位,再不带 --age 执行 --apply')
1160
+ }
1161
+ const now = Date.now()
1162
+ if (!parts.includes('--apply')) {
1163
+ D.markDecay(store.experiences, Date.now(), CONFIG)
1164
+ persist()
1165
+ const report = D.renderDecayReport(store, now, CONFIG)
1166
+ return ok(simulated ? `${report}\n(模拟:把整库老化 ${simulatedDays} 天,仅影响本次展示)` : report)
1167
+ }
1168
+ const result = D.applyEvictions(store, now, CONFIG, 'command')
1169
+ D.markDecay(store.experiences, now, CONFIG)
1170
+ persist()
1171
+ return ok(`${result.reason}\n归档: ${result.archived.join(', ') || '(无)'}\n恢复: /memory restore <id>`)
1172
+ }
1173
+ case 'restore': {
1174
+ const restored = D.restoreRecord(store, String(arg || '').trim())
1175
+ if (!restored) return err(`archive 里没有 ${arg}`)
1176
+ D.markDecay(store.experiences, Date.now(), CONFIG)
1177
+ persist()
1178
+ return ok(`${restored.id} 已恢复为 ${restored.status},decay 状态已重置。`)
1179
+ }
1180
+ case 'why': {
1181
+ const last = store.turns[store.turns.length - 1]
1182
+ if (!last) return err('还没有记录到 turn 轨迹。')
1183
+ return ok(explainTurn(last))
1184
+ }
1185
+ case 'debug': {
1186
+ const last = store.turns[store.turns.length - 1]
1187
+ const lastInjection = store.injections[store.injections.length - 1]
1188
+ const captures = store.turns.map((turn) => turn.capture).filter((item) => item && item.ok)
1189
+ const avgMs = captures.length
1190
+ ? Math.round(captures.reduce((sum, item) => sum + (item.ms || 0), 0) / captures.length)
1191
+ : 0
1192
+ const lines = [
1193
+ `store: ${STORE_FILE}`,
1194
+ `build: ${BUILD} config: ${JSON.stringify(CONFIG)}`,
1195
+ `experiences: ${store.experiences.filter((x) => x.status !== 'rejected').length} (verified ${store.experiences.filter((i) => i.status === 'verified').length}, auto-verified ${store.experiences.filter((i) => i.status === 'auto-verified').length}, candidate ${store.experiences.filter((i) => i.status === 'candidate').length}, rejected ${store.experiences.filter((x) => x.status === 'rejected').length}, auto-captured ${store.experiences.filter((i) => i.source && i.source.auto).length})`,
1196
+ `injections: ${store.injections.length} turns: ${store.turns.length} captures: ${captures.length} avgCaptureMs: ${avgMs}`,
1197
+ `lastInjection: ${lastInjection ? `${lastInjection.id} nonce=${lastInjection.nonce} rendered=${lastInjection.rendered} tokens=${lastInjection.tokens} ids=${lastInjection.experienceIds.join(',')}` : '-'}`,
1198
+ '',
1199
+ D.renderDecayReport(store, Date.now(), CONFIG),
1200
+ '',
1201
+ last ? explainTurn(last) : '(无 turn 记录)',
1202
+ ]
1203
+ return ok(lines.join('\n'))
1204
+ }
1205
+ case 'stats': {
1206
+ const candidates = C.reviewTargets(store.experiences)
1207
+ const captures = store.turns.map((turn) => turn.capture).filter((item) => item && item.ok)
1208
+ const avgMs = captures.length
1209
+ ? Math.round(captures.reduce((sum, item) => sum + (item.ms || 0), 0) / captures.length)
1210
+ : 0
1211
+ return ok(
1212
+ [
1213
+ `库 ${store.experiences.length} 条(verified ${store.experiences.filter((i) => i.status === 'verified').length} / candidate ${candidates.length} / rejected ${store.experiences.filter((i) => i.status === 'rejected').length})`,
1214
+ `自动捕获 ${captures.length} 次,平均 ${avgMs}ms(预算 ${CONFIG.captureBudgetMs}ms)`,
1215
+ `注入 ${store.injections.length} 次,最后一条 ${store.injections.length ? store.injections[store.injections.length - 1].id : '-'}`,
1216
+ `配额:今日上限 ${CONFIG.dailyLimit},库上限 ${CONFIG.libraryLimit},去重阈值 ${CONFIG.mergeThreshold}`,
1217
+ ].join('\n'),
1218
+ )
1219
+ }
1220
+ case 'config': {
1221
+ if (!arg) return ok(JSON.stringify(CONFIG, null, 2))
1222
+ const match = arg.match(/^set\s+(\w+)\s+(.+)$/)
1223
+ if (!match) return err('用法:/memory config | /memory config set <key> <value>')
1224
+ const key = match[1]
1225
+ if (!(key in C.DEFAULT_CONFIG)) return err(`未知配置项 ${key},可选:${Object.keys(C.DEFAULT_CONFIG).join(', ')}`)
1226
+ const raw = match[2].trim()
1227
+ let value
1228
+ try {
1229
+ value = C.coerceConfigValue(key, raw)
1230
+ } catch (error) {
1231
+ return err(String(error && error.message))
1232
+ }
1233
+ CONFIG[key] = value
1234
+ saveConfig()
1235
+ return ok(`${key} = ${JSON.stringify(value)}(已写入 ${CONFIG_FILE})`)
1236
+ }
1237
+ default:
1238
+ return err(`未知子命令 ${verb}`)
1239
+ }
1240
+ },
1241
+ })
1242
+
1243
+ function evidenceLine(turn) {
1244
+ const ids = (turn.candidates || []).slice(0, 3).map((item) => item.id)
1245
+ const records = ids.map((id) => store.experiences.find((item) => item.id === id)).filter(Boolean)
1246
+ if (!records.length) return '- (没有候选可评估)'
1247
+ return records
1248
+ .map((record) => {
1249
+ const state = E.promotionState(record, CONFIG)
1250
+ const proof = record.proof || {}
1251
+ const effective = state.stability ?? proof.minStability
1252
+ const raw = proof.minStability ?? 'n/a'
1253
+ const shown = state.stability !== null && state.stability !== undefined && state.stability !== proof.minStability ? `${effective}(原始 ${raw})` : `${raw}`
1254
+ return `${record.id} runs=${(proof.runs || []).length} sessions=${proof.distinctSessions || 0} stability=${shown} · ${state.eligible ? 'ready' : state.reason}`
1255
+ })
1256
+ .join(' | ')
1257
+ }
1258
+
1259
+ function explainTurn(turn) {
1260
+ const verified = store.experiences.filter((item) => item.status === 'verified')
1261
+ const injection = store.injections.find((item) => item.id === turn.injectionId)
1262
+ const pass = (flag) => (flag ? 'PASS' : 'FAIL')
1263
+ const capture = turn.capture || {}
1264
+ const lines = [
1265
+ `turn: session=${turn.sessionId} turn=${turn.turn} steps=${turn.steps} durationMs=${turn.durationMs ?? '?'}`,
1266
+ `query: ${turn.query.slice(0, 160)}`,
1267
+ `queryTokens: ${(turn.queryTokens || []).join(' ') || '(空)'}`,
1268
+ `candidates: ${(turn.candidates || []).map((c) => `${c.id}=${c.score}${c.status ? `(${c.status})` : ''}${c.passed ? '*' : ''}`).join(' ') || '(空)'}`,
1269
+ `threshold: ${turn.threshold}`,
1270
+ `calls: ${(turn.calls || []).length}(失败 ${(turn.calls || []).filter((c) => !c.ok).length})`,
1271
+ `capture: ${capture.ok ? `PASS ${capture.id || capture.merged || ''} (${capture.ms}ms${capture.added ? `, +${capture.added} 反例` : ''})` : `SKIP ${capture.reason || '(未执行)'}`}`,
1272
+ '',
1273
+ '[1 存储] ' + pass(store.experiences.length > 0),
1274
+ '[2 可召回] ' + pass(verified.length > 0) + ` (verified=${verified.length})`,
1275
+ '[2.5 证据] ' + evidenceLine(turn),
1276
+ '[2.6 衰减] ' + ((turn.candidates || [])
1277
+ .filter((c) => {
1278
+ const record = store.experiences.find((item) => item.id === c.id)
1279
+ return !record || record.status !== 'rejected'
1280
+ })
1281
+ .map((c) => {
1282
+ const record = store.experiences.find((item) => item.id === c.id)
1283
+ return record ? D.decayLine(record, Date.now(), CONFIG) : `${c.id} (已不在库)`
1284
+ }).join(' | ') || '(空)'),
1285
+ `[3 检索] ${injection ? 'PASS' : 'FAIL'} (top=${(turn.candidates && turn.candidates[0] && turn.candidates[0].score) ?? 0}, 阈值 ${turn.threshold})`,
1286
+ `[4 注入] ${injection ? (injection.rendered ? 'PASS' : 'FAIL: 已选择但 prompt 未重新读取(refreshContext 未触发)') : 'FAIL: 没有选择任何经验'}`,
1287
+ `[5 模型可见] 人工核对:回答中是否回显 nonce ${injection ? injection.nonce : '(无)'}`,
1288
+ '[6 生效] 对比 steps/durationMs 与第一次。',
1289
+ '',
1290
+ hintFor(turn, injection, verified),
1291
+ ]
1292
+ return lines.join('\n')
1293
+ }
1294
+
1295
+ function hintFor(turn, injection, verified) {
1296
+ if (!store.experiences.length) return '卡在 [1 存储]:先 experience_record 或 /memory teach。'
1297
+ if (!verified.length) {
1298
+ const blocked = (turn.candidates || []).filter((c) => c.status === 'candidate' && c.score >= turn.threshold)
1299
+ if (blocked.length) {
1300
+ return `卡在 [2 可召回]:${blocked.map((c) => c.id).join(', ')} 得分已过阈值(${blocked.map((c) => c.score).join(', ')}),但 status=candidate —— 运行 /memory review 批量确认后重跑同类任务。`
1301
+ }
1302
+ return '卡在 [2 可召回]:只有 candidate,运行 /memory review 查看并批准。'
1303
+ }
1304
+ if (!injection) {
1305
+ const top = turn.candidates && turn.candidates[0]
1306
+ if (!top) return '卡在 [3 检索]:verified 经验都被过滤(检查 status)。'
1307
+ return `卡在 [3 检索]:最高分 ${top.score} < ${turn.threshold}。补充 title/when/keywords 或调低阈值。`
1308
+ }
1309
+ if (!injection.rendered) return '卡在 [4 注入]:pre-step 选了经验,但 systemPrompt.context 的 text() 未被调用。'
1310
+ return '注入链路已通;剩下只看向下一个问题:模型是否真的按经验执行、效率是否提升。'
1311
+ }
1312
+
1313
+ const ok = (text) => ({ kind: 'success', text })
1314
+ const err = (text) => ({ kind: 'error', text })
1315
+ }
1316
+
1317
+ function safeList(ctx) {
1318
+ try {
1319
+ if (!ctx.agents || typeof ctx.agents.list !== 'function') return []
1320
+ return ctx.agents.list() || []
1321
+ } catch {
1322
+ return []
1323
+ }
1324
+ }
1325
+ // reload-marker: 2026-11-09 round2-l1