@aiwayds/dsh-topics-memory 0.18.2 → 0.19.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/README.md +78 -1
- package/README.zh.md +69 -1
- package/lib/commands.js +3 -0
- package/lib/config.d.ts +44 -1
- package/lib/config.js +33 -2
- package/lib/consolidate.d.ts +39 -1
- package/lib/consolidate.js +195 -1
- package/lib/index.d.ts +10 -0
- package/lib/index.js +53 -2
- package/lib/jev/backends.d.ts +31 -0
- package/lib/jev/backends.js +46 -0
- package/lib/jev/client.d.ts +91 -0
- package/lib/jev/client.js +211 -0
- package/lib/jev/gate.d.ts +50 -0
- package/lib/jev/gate.js +125 -0
- package/lib/jev/log.d.ts +65 -0
- package/lib/jev/log.js +119 -0
- package/lib/jev/thresholds.d.ts +21 -0
- package/lib/jev/thresholds.js +27 -0
- package/lib/quality.d.ts +60 -2
- package/lib/quality.js +230 -11
- package/package.json +2 -2
- package/src/commands.ts +2 -0
- package/src/config.ts +41 -2
- package/src/consolidate.ts +238 -1
- package/src/index.ts +61 -2
- package/src/jev/backends.ts +66 -0
- package/src/jev/client.ts +318 -0
- package/src/jev/gate.ts +151 -0
- package/src/jev/log.ts +184 -0
- package/src/jev/thresholds.ts +31 -0
- package/src/quality.ts +269 -11
package/src/quality.ts
CHANGED
|
@@ -5,8 +5,12 @@
|
|
|
5
5
|
* 1. intent-query build over the observer's last-K ring buffer — kills
|
|
6
6
|
* verbatim priming at the root (the query is what the model needs, not
|
|
7
7
|
* what the user typed);
|
|
8
|
-
* 2. lexical candidate band (hits + near-misses, recall-oriented) then
|
|
9
|
-
*
|
|
8
|
+
* 2. lexical candidate band (hits + near-misses, recall-oriented) then a
|
|
9
|
+
* rerank that releases 0-2 picks, each with a one-line why. With
|
|
10
|
+
* `jevEnabled` on (design 2026-09-25 §2) the rerank is a batched System
|
|
11
|
+
* One noul request, probability-band gated; any failure fails open to the
|
|
12
|
+
* legacy LLM rerank below. The same trigger also runs the fastgate
|
|
13
|
+
* SHADOW (zero behavior, decisions.jsonl only).
|
|
10
14
|
*
|
|
11
15
|
* Picks rest in a per-session pending slot and inject at the NEXT spliced
|
|
12
16
|
* (steer message), then the slot is gone (消费即清). Hard bounds: per-call
|
|
@@ -23,6 +27,13 @@ import type { ModelCaller } from './distill.ts'
|
|
|
23
27
|
import { searchTopics } from './retrieval.ts'
|
|
24
28
|
import type { RingEntry } from './observer.ts'
|
|
25
29
|
import type { QueryBuildShape } from './ilog.ts'
|
|
30
|
+
import type { TopicsConfigValue } from './config.ts'
|
|
31
|
+
import { jevAsk } from './jev/client.ts'
|
|
32
|
+
import type { JevAskConfig, JevQuestion } from './jev/client.ts'
|
|
33
|
+
import { band as jevBand } from './jev/thresholds.ts'
|
|
34
|
+
import type { JevBand } from './jev/thresholds.ts'
|
|
35
|
+
import { digestFor, logVerdicts } from './jev/log.ts'
|
|
36
|
+
import type { JevVerdictRecord } from './jev/log.ts'
|
|
26
37
|
|
|
27
38
|
export const PENDING_TTL_MS = 10 * 60_000
|
|
28
39
|
/** Hard drift bound: a pending older than this many turn-ends expires. */
|
|
@@ -38,6 +49,8 @@ const RING_CHARS = 6000
|
|
|
38
49
|
const CANDIDATE_LIMIT = 6
|
|
39
50
|
/** Over-fetch before the exclude filter, so excluded slugs don't thin the band. */
|
|
40
51
|
const CANDIDATE_OVERFETCH = 6
|
|
52
|
+
/** Fastgate shadow cap (design §2 row 3): topK hits + near-misses, ≤8 questions. */
|
|
53
|
+
export const FASTGATE_MAX_QUESTIONS = 8
|
|
41
54
|
|
|
42
55
|
export const QUERY_BUILD_PROMPT = [
|
|
43
56
|
'你是检索查询构建器。输入是最近几轮对话。任务:判断「模型此刻需要什么背景知识」,输出一个用于关键词检索的 query。',
|
|
@@ -57,6 +70,90 @@ export const RERANK_PROMPT = [
|
|
|
57
70
|
'- slug 必须逐字取自候选列表,禁止编造。',
|
|
58
71
|
].join('\n')
|
|
59
72
|
|
|
73
|
+
// ---- jev (System One) decision branch, design 2026-09-25 §2 rows 1+3 ----
|
|
74
|
+
//
|
|
75
|
+
// When jevEnabled is on, the rerank step asks the decision model instead of
|
|
76
|
+
// the generative LLM: one batched noul request over the candidate band, the
|
|
77
|
+
// calibrated bands (jev/thresholds: adopt ≥ 0.60 / record 0.10–0.60 / veto
|
|
78
|
+
// < 0.10) decide the picks, and every candidate lands in decisions.jsonl.
|
|
79
|
+
// Any failure falls open to the RERANK_PROMPT path below (red line ②).
|
|
80
|
+
// The fastgate shadow audits the fast lane's OWN lexical disposition from the
|
|
81
|
+
// same sampled turn-end trigger — zero behavior, decisions.jsonl only.
|
|
82
|
+
|
|
83
|
+
/** The candidate slice the jev questions see (content-bearing metadata). */
|
|
84
|
+
interface JevCandidate {
|
|
85
|
+
slug: string
|
|
86
|
+
title: string
|
|
87
|
+
status: string
|
|
88
|
+
tags?: readonly string[]
|
|
89
|
+
description?: string
|
|
90
|
+
conclusion: string
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* §6.2 state for one batch: the round's query plus the task frame. Shared by
|
|
95
|
+
* the rerank and the fastgate shadow so both seams speak ONE batch protocol —
|
|
96
|
+
* the calibrated bands are protocol-bound (design §5), a second state shape
|
|
97
|
+
* would need its own sweep.
|
|
98
|
+
*/
|
|
99
|
+
export function jevState(query: string): string {
|
|
100
|
+
return `检索 query:${query}\n任务背景:模型正在推进当前会话的工作,需要判断哪些长期记忆 topic 值得注入上下文作参考。`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Per-candidate question: full candidate inline (title/tags/conclusion
|
|
104
|
+
* excerpt), RERANK_PROMPT's rendering style but compact. */
|
|
105
|
+
function candidateInstructions(c: JevCandidate): string {
|
|
106
|
+
const tags = c.tags !== undefined && c.tags.length > 0 ? `,标签: ${c.tags.join('/')}` : ''
|
|
107
|
+
const desc = c.description !== undefined && c.description.trim() !== '' ? ` ${c.description.trim().slice(0, 80)}` : ''
|
|
108
|
+
return `候选 topic「${c.title}」(slug: ${c.slug},状态: ${c.status}${tags})。${desc}结论摘录:${c.conclusion.slice(0, 160)}。该候选与当前 query 对应的工作真的相关、值得注入模型上下文吗?`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Two-sided criteria built from the candidate content (calibration protocol:
|
|
112
|
+
* single-sided instructions measurably degrade). */
|
|
113
|
+
function candidateCriteria(c: JevCandidate): { true: string; false: string } {
|
|
114
|
+
return {
|
|
115
|
+
true: `相关——「${c.title}」的记忆对当前工作有实质帮助,应该注入作参考`,
|
|
116
|
+
false: `无关——「${c.title}」与当前工作没有实质交集,注入只是噪音,不应该注入`,
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The noul probability of one answer; undefined when the answer is not a
|
|
121
|
+
* usable number in [0,1] (a 坏答案 — fail-open for the caller). */
|
|
122
|
+
function noulProbability(answer: unknown): number | undefined {
|
|
123
|
+
if (answer === null || typeof answer !== 'object') return undefined
|
|
124
|
+
const p = (answer as { noul?: unknown }).noul
|
|
125
|
+
return typeof p === 'number' && Number.isFinite(p) && p >= 0 && p <= 1 ? p : undefined
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The config slice jevAsk needs, tolerating bare harnesses (§4: consumers
|
|
129
|
+
* treat undefined as the documented default). */
|
|
130
|
+
function jevConfigOf(cfg: TopicsConfigValue): JevAskConfig {
|
|
131
|
+
return {
|
|
132
|
+
jevBackend: cfg.jevBackend ?? 'zen',
|
|
133
|
+
jevModel: cfg.jevModel ?? '',
|
|
134
|
+
jevTimeoutMs: typeof cfg.jevTimeoutMs === 'number' && cfg.jevTimeoutMs > 0 ? cfg.jevTimeoutMs : 3000,
|
|
135
|
+
jevSecretFile: cfg.jevSecretFile ?? '',
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The lexical disposition the fast lane recorded for one candidate — the
|
|
140
|
+
* agree-reconciliation key (§6.2; retrieval.ts hits/nearMisses split). */
|
|
141
|
+
export type FastGateDisposition = 'hit' | 'nearFloor' | 'gate-blocked'
|
|
142
|
+
|
|
143
|
+
export interface FastGateCandidate {
|
|
144
|
+
slug: string
|
|
145
|
+
disposition: FastGateDisposition
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface FastGateShadowInput {
|
|
149
|
+
/** The fast-lane round's query (the claimed text), captured at spliced. */
|
|
150
|
+
query: string
|
|
151
|
+
/** hits + near-misses of that round, with their lexical dispositions. */
|
|
152
|
+
candidates: readonly FastGateCandidate[]
|
|
153
|
+
/** Observer turn count at the trigger — the sampled-cadence clock. */
|
|
154
|
+
turnId: number
|
|
155
|
+
}
|
|
156
|
+
|
|
60
157
|
export interface PendingInjection {
|
|
61
158
|
items: { slug: string; why: string }[]
|
|
62
159
|
computedAt: string
|
|
@@ -141,6 +238,8 @@ export function parseJsonObject(raw: string): Record<string, unknown> {
|
|
|
141
238
|
export class SlowLane {
|
|
142
239
|
private pending = new Map<string, PendingInjection>()
|
|
143
240
|
private inFlight = new Map<string, Promise<void>>()
|
|
241
|
+
/** Same-session shadow serialization — a second trigger never overlaps. */
|
|
242
|
+
private shadowInFlight = new Map<string, Promise<void>>()
|
|
144
243
|
private readonly service: TopicsService
|
|
145
244
|
private readonly caller: ModelCaller | undefined
|
|
146
245
|
/**
|
|
@@ -171,6 +270,87 @@ export class SlowLane {
|
|
|
171
270
|
/** Drop the pending slot (session teardown, restore boundary). */
|
|
172
271
|
clear(sessionId: string): void {
|
|
173
272
|
this.pending.delete(sessionId)
|
|
273
|
+
this.shadowInFlight.delete(sessionId)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Fastgate shadow (design §2 row 3): fire-and-forget on the SAME sampled
|
|
278
|
+
* turn-end trigger as the slow lane, zero behavior — verdicts land only in
|
|
279
|
+
* decisions.jsonl, reconciled against the lexical disposition. Needs no LLM
|
|
280
|
+
* caller, so it also runs on turns where the slow lane itself yields (distill
|
|
281
|
+
* in flight, no model configured). `dispatch()`'s own guards (lane mode,
|
|
282
|
+
* sampled cadence) are mirrored here so both seams share one cadence.
|
|
283
|
+
*/
|
|
284
|
+
dispatchFastGateShadow(sessionId: string, input: FastGateShadowInput): void {
|
|
285
|
+
try {
|
|
286
|
+
const cfg = this.service.cfg
|
|
287
|
+
if (cfg.jevEnabled !== true) return
|
|
288
|
+
if (cfg.qualityLane !== 'sampled' && cfg.qualityLane !== 'always') return
|
|
289
|
+
if (cfg.qualityLane === 'sampled' && input.turnId % SAMPLED_EVERY !== 0) return
|
|
290
|
+
if (input.query.trim() === '' || input.candidates.length === 0) return
|
|
291
|
+
if (this.shadowInFlight.has(sessionId)) return // never overlap shadows
|
|
292
|
+
// Serialize behind a same-session produce pipeline (rerank 完成后);
|
|
293
|
+
// standalone when no pipeline is running (无慢道任务时独立跑).
|
|
294
|
+
const prior = this.inFlight.get(sessionId) ?? Promise.resolve()
|
|
295
|
+
const run = prior.then(() => this.fastGateShadow(input)).finally(() => {
|
|
296
|
+
this.shadowInFlight.delete(sessionId)
|
|
297
|
+
})
|
|
298
|
+
this.shadowInFlight.set(sessionId, run)
|
|
299
|
+
void run.catch(() => undefined)
|
|
300
|
+
} catch {
|
|
301
|
+
// contained — the shadow must never break the event handler
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Shadow body: resolve candidate content from the roster, one batched noul
|
|
306
|
+
* request, verdict rows only. A jevAsk failure leaves just its auto-written
|
|
307
|
+
* call row — there is no legacy path to fall back to, and nothing to gate. */
|
|
308
|
+
private async fastGateShadow(input: FastGateShadowInput): Promise<void> {
|
|
309
|
+
const roster = await this.service.roster().catch(() => [])
|
|
310
|
+
const bySlug = new Map(roster.map((r) => [r.slug, r]))
|
|
311
|
+
const state = jevState(input.query)
|
|
312
|
+
const questions: Record<string, JevQuestion> = {}
|
|
313
|
+
const metas: { qid: string; slug: string; instructions: string; disposition: FastGateDisposition }[] = []
|
|
314
|
+
for (const cand of input.candidates.slice(0, FASTGATE_MAX_QUESTIONS)) {
|
|
315
|
+
const meta = bySlug.get(cand.slug)
|
|
316
|
+
if (meta === undefined) continue // vanished between retrieval and the shadow
|
|
317
|
+
const qid = `c${metas.length + 1}`
|
|
318
|
+
const instructions = candidateInstructions(meta)
|
|
319
|
+
questions[qid] = { type: 'noul', instructions, criteria: candidateCriteria(meta) }
|
|
320
|
+
metas.push({ qid, slug: cand.slug, instructions, disposition: cand.disposition })
|
|
321
|
+
}
|
|
322
|
+
if (metas.length === 0) return
|
|
323
|
+
const result = await jevAsk({
|
|
324
|
+
state,
|
|
325
|
+
questions,
|
|
326
|
+
config: jevConfigOf(this.service.cfg),
|
|
327
|
+
lane: 'fastgate-shadow',
|
|
328
|
+
fallback: false, // pure shadow — no behavior to fall back
|
|
329
|
+
})
|
|
330
|
+
if (!result.ok) return
|
|
331
|
+
const at = new Date().toISOString()
|
|
332
|
+
const recs: JevVerdictRecord[] = []
|
|
333
|
+
for (const m of metas) {
|
|
334
|
+
const probability = noulProbability(result.answers[m.qid])
|
|
335
|
+
if (probability === undefined) continue // unparseable answer: no fabricated row
|
|
336
|
+
const b = jevBand(probability, 'rerank')
|
|
337
|
+
// agree reconciliation (§6.2): the ilog disposition, with wouldBlock for
|
|
338
|
+
// the reverse disagreement (lexical let it through, jev lands in the veto
|
|
339
|
+
// band — the other half of the calibration goldmine).
|
|
340
|
+
const agree: JevVerdictRecord['agree'] = m.disposition === 'hit' && b === 'fallback' ? 'wouldBlock' : m.disposition
|
|
341
|
+
recs.push({
|
|
342
|
+
at,
|
|
343
|
+
lane: 'fastgate-shadow',
|
|
344
|
+
questionId: m.qid,
|
|
345
|
+
qtype: 'noul',
|
|
346
|
+
ref: `slug:${m.slug}`,
|
|
347
|
+
digest: digestFor(state, m.qid, m.instructions),
|
|
348
|
+
probability,
|
|
349
|
+
band: b,
|
|
350
|
+
agree,
|
|
351
|
+
})
|
|
352
|
+
}
|
|
353
|
+
await logVerdicts(recs)
|
|
174
354
|
}
|
|
175
355
|
|
|
176
356
|
/**
|
|
@@ -270,6 +450,18 @@ export class SlowLane {
|
|
|
270
450
|
]
|
|
271
451
|
})
|
|
272
452
|
if (payload.length === 0) return
|
|
453
|
+
// ---- jev batch rerank (design §2 row 1) — replaces the LLM rerank ----
|
|
454
|
+
// One batched noul request over the whole band; the calibrated bands
|
|
455
|
+
// decide the picks. A settled jev round is FINAL here (picks or none) —
|
|
456
|
+
// only a jev FAILURE (jevRerank → undefined) falls open to the legacy
|
|
457
|
+
// LLM rerank below (§3.2: 本轮回退旧 LLM rerank, picks 照常产出).
|
|
458
|
+
if (this.service.cfg.jevEnabled === true) {
|
|
459
|
+
const jevItems = await this.jevRerank(query, payload)
|
|
460
|
+
if (jevItems !== undefined) {
|
|
461
|
+
if (jevItems.length > 0) this.settlePending(sessionId, input, jevItems, queryBuild, started)
|
|
462
|
+
return
|
|
463
|
+
}
|
|
464
|
+
}
|
|
273
465
|
const rerankRaw = await withTimeout(
|
|
274
466
|
caller({
|
|
275
467
|
system: RERANK_PROMPT,
|
|
@@ -309,15 +501,7 @@ export class SlowLane {
|
|
|
309
501
|
if (items.length >= 2) break
|
|
310
502
|
}
|
|
311
503
|
if (items.length === 0) return
|
|
312
|
-
|
|
313
|
-
this.pending.set(sessionId, {
|
|
314
|
-
items,
|
|
315
|
-
computedAt: new Date().toISOString(),
|
|
316
|
-
turnId: input.turnId,
|
|
317
|
-
queryBuild,
|
|
318
|
-
model: `${route.distillProvider}/${route.distillModel}`,
|
|
319
|
-
ms: Date.now() - started,
|
|
320
|
-
})
|
|
504
|
+
this.settlePending(sessionId, input, items, queryBuild, started)
|
|
321
505
|
} catch {
|
|
322
506
|
// timeouts, aborts, model errors — I3: the async product is simply absent
|
|
323
507
|
} finally {
|
|
@@ -325,6 +509,80 @@ export class SlowLane {
|
|
|
325
509
|
}
|
|
326
510
|
}
|
|
327
511
|
|
|
512
|
+
/** One pending slot per settled pipeline (the 0-2 picks + lane metadata). */
|
|
513
|
+
private settlePending(sessionId: string, input: DispatchInput, items: { slug: string; why: string }[], queryBuild: QueryBuildShape, started: number): void {
|
|
514
|
+
const route = this.service.cfg
|
|
515
|
+
this.pending.set(sessionId, {
|
|
516
|
+
items,
|
|
517
|
+
computedAt: new Date().toISOString(),
|
|
518
|
+
turnId: input.turnId,
|
|
519
|
+
queryBuild,
|
|
520
|
+
model: `${route.distillProvider}/${route.distillModel}`,
|
|
521
|
+
ms: Date.now() - started,
|
|
522
|
+
})
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* The jev rerank (design §2 row 1): one batched noul request over the whole
|
|
527
|
+
* candidate band; per-candidate verdict rows (agree: 'n/a' — no lexical
|
|
528
|
+
* disposition applies on this seam). Gate: adopt band (≥ 0.60) ranked by
|
|
529
|
+
* probability, top 2 (the 0-2 picks semantics); record band only logs;
|
|
530
|
+
* fallback band (< 0.10) is a hard veto.
|
|
531
|
+
*
|
|
532
|
+
* Returns undefined on ANY failure — jevAsk !ok (timeout / network / gate /
|
|
533
|
+
* bad shape) or an unparseable probability (坏答案) — so the caller fails
|
|
534
|
+
* open to the legacy LLM rerank (red line ②; the call-layer row already
|
|
535
|
+
* carries fallback=true via jevAsk's flag).
|
|
536
|
+
*/
|
|
537
|
+
private async jevRerank(query: string, payload: JevCandidate[]): Promise<{ slug: string; why: string }[] | undefined> {
|
|
538
|
+
const state = jevState(query)
|
|
539
|
+
const questions: Record<string, JevQuestion> = {}
|
|
540
|
+
const metas: { qid: string; slug: string; instructions: string }[] = []
|
|
541
|
+
for (const [i, c] of payload.entries()) {
|
|
542
|
+
const qid = `c${i + 1}`
|
|
543
|
+
const instructions = candidateInstructions(c)
|
|
544
|
+
questions[qid] = { type: 'noul', instructions, criteria: candidateCriteria(c) }
|
|
545
|
+
metas.push({ qid, slug: c.slug, instructions })
|
|
546
|
+
}
|
|
547
|
+
const result = await jevAsk({
|
|
548
|
+
state,
|
|
549
|
+
questions,
|
|
550
|
+
config: jevConfigOf(this.service.cfg),
|
|
551
|
+
lane: 'slowlane-rerank',
|
|
552
|
+
fallback: false,
|
|
553
|
+
// fallback stays FALSE here: jevAsk writes the row before the caller
|
|
554
|
+
// knows the outcome, so a constant true would poison the rollback-rate
|
|
555
|
+
// stat. Fail-open occurrence = outcome !== 'ok' (this lane's fallback
|
|
556
|
+
// to the legacy LLM rerank is deterministic per ADR 0018).
|
|
557
|
+
})
|
|
558
|
+
if (!result.ok) return undefined
|
|
559
|
+
const scored: { qid: string; slug: string; instructions: string; probability: number; band: JevBand }[] = []
|
|
560
|
+
for (const m of metas) {
|
|
561
|
+
const probability = noulProbability(result.answers[m.qid])
|
|
562
|
+
if (probability === undefined) return undefined // 坏答案 → fail-open (§1)
|
|
563
|
+
scored.push({ ...m, probability, band: jevBand(probability, 'rerank') })
|
|
564
|
+
}
|
|
565
|
+
const at = new Date().toISOString()
|
|
566
|
+
await logVerdicts(
|
|
567
|
+
scored.map((m) => ({
|
|
568
|
+
at,
|
|
569
|
+
lane: 'slowlane-rerank' as const,
|
|
570
|
+
questionId: m.qid,
|
|
571
|
+
qtype: 'noul' as const,
|
|
572
|
+
ref: `slug:${m.slug}`,
|
|
573
|
+
digest: digestFor(state, m.qid, m.instructions),
|
|
574
|
+
probability: m.probability,
|
|
575
|
+
band: m.band,
|
|
576
|
+
agree: 'n/a' as const,
|
|
577
|
+
})),
|
|
578
|
+
)
|
|
579
|
+
return scored
|
|
580
|
+
.filter((m) => m.band === 'adopt')
|
|
581
|
+
.sort((a, b) => b.probability - a.probability)
|
|
582
|
+
.slice(0, 2)
|
|
583
|
+
.map((m) => ({ slug: m.slug, why: `jev 判定相关(p=${m.probability.toFixed(2)})` }))
|
|
584
|
+
}
|
|
585
|
+
|
|
328
586
|
/**
|
|
329
587
|
* Consumption point (the next spliced). Returns the pending exactly once
|
|
330
588
|
* (消费即清) or an expiry reason; `turnId` is the CURRENT observer turn
|