@jjh32456/longlive 2.0.0 → 2.1.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/CHANGELOG.md +30 -4
- package/QUICKSTART.md +4 -4
- package/README.en.md +4 -4
- package/README.md +33 -21
- package/SPEC.md +2 -2
- package/build-info.json +62 -42
- package/docs/ANSWER-GUARD.md +1 -1
- package/docs/ARCHITECTURE.md +3 -3
- package/docs/AUTO-RECALL-WIRING.md +5 -3
- package/docs/AUTO-RECALL.md +9 -3
- package/docs/CONFIG.md +6 -3
- package/docs/ERRORS.md +1 -1
- package/docs/FAQ.md +5 -5
- package/docs/FEATURES.md +14 -11
- package/docs/OPERATIONS.md +3 -3
- package/docs/PRIVACY.md +1 -1
- package/docs/QUICKSTART.md +4 -4
- package/docs/README.en.md +3 -3
- package/docs/TOOLS.md +1 -1
- package/docs/TROUBLESHOOTING.md +2 -2
- package/package.json +1 -1
- package/src/features.js +4 -0
- package/src/index.js +2 -2
- package/src/memory/memory-reader.mjs +1003 -0
- package/src/recall/continuity-log.mjs +435 -0
- package/src/recall/continuity-volatile.mjs +1001 -0
- package/src/recall/index.js +341 -8
- package/src/recall/link-fastpath.mjs +662 -0
- package/src/recall/recall-core.mjs +27 -0
package/src/recall/index.js
CHANGED
|
@@ -30,7 +30,7 @@ import { resolveAnaphora, expandQueryWithAnaphora } from './anaphora.mjs';
|
|
|
30
30
|
import { appendAuditRecord } from '../memory/audit-records.js';
|
|
31
31
|
import { buildEvidencePackage, writeEvidencePackage } from '../memory/evidence.js';
|
|
32
32
|
import { fastAnswerFromRecallItems } from '../memory/recall-v2.js';
|
|
33
|
-
import { buildQueryText, chooseRecall, decideTrigger, estimateTokens, renderInjection } from './recall-core.mjs';
|
|
33
|
+
import { buildQueryText, chooseRecall, decideTrigger, emptyRecallResult, estimateTokens, renderInjection } from './recall-core.mjs';
|
|
34
34
|
import { buildRecallLogRecord } from './explain.mjs';
|
|
35
35
|
// B3 C6:召回车道字符账(990 = 头 60 + 卡区 750 + 程序卡 120 + 当前线 60)。
|
|
36
36
|
import {
|
|
@@ -84,17 +84,40 @@ import {
|
|
|
84
84
|
import { applyClaimGuard } from '../answer/claim-guard.mjs';
|
|
85
85
|
// 2.0.0 W3b(M32):冷档不可用 + 有检索需求时写唯一一行 hg.d19.fail(A6 五码族,行内带 code)。
|
|
86
86
|
import { appendGateLog } from './gate-log.mjs';
|
|
87
|
-
import { appendFileSync, mkdirSync, readdirSync, statSync } from 'node:fs';
|
|
87
|
+
import { appendFileSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
88
88
|
import { dirname, join } from 'node:path';
|
|
89
89
|
import { dshHome } from '../home.js';
|
|
90
90
|
import { DEFAULT_MEMORY_DIRNAME } from '../memory/paths.js';
|
|
91
91
|
import { lifecycleRank, readCardLifecycle } from '../memory/lifecycle.js';
|
|
92
92
|
import { startPrestepPhase, notePrestepDegrade, setPrestepMeta } from '../metrics/prestep-latency.mjs';
|
|
93
93
|
import { sampleContentHash } from '../memory/auto-cards.js';
|
|
94
|
+
// 2.1.0(集成 lane):volatile 连续性快照(lane-core 模块)/ 链路直连 / MemoryReader 索引读取。
|
|
95
|
+
import { createHash } from 'node:crypto';
|
|
96
|
+
import { tmpdir } from 'node:os';
|
|
97
|
+
import { MemoryReader } from '../memory/memory-reader.mjs';
|
|
98
|
+
import { LinkFastPath, readHits } from './link-fastpath.mjs';
|
|
99
|
+
import { createContinuityVolatile, probeVolatileHost, sessionIdOf } from './continuity-volatile.mjs';
|
|
100
|
+
import { continuityEvidence, writeTurnRow } from './continuity-log.mjs';
|
|
94
101
|
|
|
95
102
|
export const name = 'dsh-auto-recall';
|
|
96
103
|
export const inject = [];
|
|
97
104
|
|
|
105
|
+
// 2.1.0(集成 lane):链路直连的可复算调用计数。只做观测,不参与任何决策;测试用
|
|
106
|
+
// resetLaneCounters() + 断言 getCardsCalls/embeddingEnsureCalls/chooseRecallCalls==0
|
|
107
|
+
// 来证明「fastpath 命中即直连」确实跳过了全量召回(而不是靠日志推断)。
|
|
108
|
+
export const laneCounters = {
|
|
109
|
+
getCardsCalls: 0,
|
|
110
|
+
embeddingEnsureCalls: 0,
|
|
111
|
+
chooseRecallCalls: 0,
|
|
112
|
+
fastpathHits: 0,
|
|
113
|
+
fastpathMisses: 0,
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** 归零 laneCounters(测试用;运行时不需要调用)。 */
|
|
117
|
+
export function resetLaneCounters() {
|
|
118
|
+
for (const key of Object.keys(laneCounters)) laneCounters[key] = 0;
|
|
119
|
+
}
|
|
120
|
+
|
|
98
121
|
/** Env names shared with src/memory/paths.js (single naming scheme). */
|
|
99
122
|
const MEMORY_ROOT_ENV = 'DSH_LONGLIVE_MEMORY_ROOT';
|
|
100
123
|
const LEGACY_MEMORY_ROOT_ENV = 'DSH_MEM';
|
|
@@ -131,6 +154,10 @@ const DEFAULTS = Object.freeze({
|
|
|
131
154
|
forceOnUserMessage: true,
|
|
132
155
|
// 1.8.8 M2:链路直连 + 在线学习(默认开;关闭后不读、不写、不学 links.jsonl)。
|
|
133
156
|
links: { ...LINKS_DEFAULTS },
|
|
157
|
+
// 2.1.0:连续性 volatile 快照('auto' = 有宿主哨兵才启用;false = 全关)。
|
|
158
|
+
continuity: { enabled: 'auto', fallbackToPersistent: false, maxCards: 3, maxCardChars: 600 },
|
|
159
|
+
// 2.1.0:MemoryReader 索引读取(默认关:索引模式补读正文,先显式开关;旧 loadCards 作回落)。
|
|
160
|
+
readGate: { index: false },
|
|
134
161
|
});
|
|
135
162
|
|
|
136
163
|
function normalize(config = {}) {
|
|
@@ -150,6 +177,27 @@ function normalize(config = {}) {
|
|
|
150
177
|
cfg.links = normalizeLinksConfig(config.links);
|
|
151
178
|
// 测试/嵌入时可注入消息工厂,避免依赖 @deepseek-ai/dsh-llm 的解析环境。
|
|
152
179
|
cfg.createUserMessage = typeof config.createUserMessage === 'function' ? config.createUserMessage : null;
|
|
180
|
+
// 2.1.0(用户裁定 2026-12-05):linkSupplement **默认 false** = 链路命中即直连
|
|
181
|
+
// (readHits 正文 → 跳过 getCards/embedding/chooseRecall),0 命中才回落原链路;
|
|
182
|
+
// 显式 true = opt-in 保留 2.0.0「链路命中 + 文本召回合并」补漏模式。
|
|
183
|
+
cfg.links.linkSupplement = Boolean(config.links && typeof config.links === 'object' && config.links.linkSupplement === true);
|
|
184
|
+
// 连续性 volatile 快照:'auto'(默认)= 有宿主哨兵才注入;true = 强制(无哨兵走 v0.2 持久块回落);
|
|
185
|
+
// false = 全关。默认 auto 保证未装宿主补丁时 2.0.0 行为不变。
|
|
186
|
+
const rawContinuity = config.continuity && typeof config.continuity === 'object' ? config.continuity : {};
|
|
187
|
+
cfg.continuity = {
|
|
188
|
+
enabled: rawContinuity.enabled === false ? false : rawContinuity.enabled === true ? true : 'auto',
|
|
189
|
+
fallbackToPersistent: rawContinuity.fallbackToPersistent === true,
|
|
190
|
+
maxCards: Math.max(1, Math.min(10, Number(rawContinuity.maxCards) || 3)),
|
|
191
|
+
maxCardChars: Math.max(120, Math.min(4000, Number(rawContinuity.maxCardChars) || 600)),
|
|
192
|
+
personaHeader: typeof rawContinuity.personaHeader === 'string' ? rawContinuity.personaHeader : '',
|
|
193
|
+
subagentIdentity: typeof rawContinuity.subagentIdentity === 'string' ? rawContinuity.subagentIdentity : '子代理',
|
|
194
|
+
};
|
|
195
|
+
// MemoryReader 索引读取:默认关;readGate.index:true 时 getCards 走索引,旧路径作回落。
|
|
196
|
+
const rawReadGate = config.readGate && typeof config.readGate === 'object' ? config.readGate : {};
|
|
197
|
+
cfg.readGate = {
|
|
198
|
+
index: rawReadGate.index === true,
|
|
199
|
+
indexPath: typeof rawReadGate.indexPath === 'string' && rawReadGate.indexPath.trim() !== '' ? rawReadGate.indexPath.trim() : '',
|
|
200
|
+
};
|
|
153
201
|
// embedding 由 embedding.mjs 自己归一化(enabled 默认 false、modelPath 必填)。
|
|
154
202
|
cfg.embedding = config.embedding && typeof config.embedding === 'object' ? { ...config.embedding } : { enabled: true };
|
|
155
203
|
cfg.evidencePackage = cfg.evidencePackage !== false;
|
|
@@ -355,10 +403,21 @@ export function apply(ctx, config = {}) {
|
|
|
355
403
|
let cards = null;
|
|
356
404
|
let cardsSignature = '';
|
|
357
405
|
const getCards = () => {
|
|
406
|
+
laneCounters.getCardsCalls += 1;
|
|
358
407
|
const signature = cardSignature();
|
|
359
408
|
if (cards && signature === cardsSignature) return cards;
|
|
360
409
|
cardsSignature = signature;
|
|
361
410
|
cards = null;
|
|
411
|
+
// 2.1.0:readGate.index:true 走 MemoryReader 索引读取;失败回落旧 loadCards(索引绝不挡召回)。
|
|
412
|
+
if (cfg.readGate.index) {
|
|
413
|
+
try {
|
|
414
|
+
cards = loadCardsFromIndex();
|
|
415
|
+
return cards;
|
|
416
|
+
} catch (error) {
|
|
417
|
+
warn('READER_INDEX_FAILED', error?.code ?? error?.message ?? error);
|
|
418
|
+
cards = null;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
362
421
|
try {
|
|
363
422
|
cards = loadCards(cfg.memoryRoot, { dirs: cfg.dirs });
|
|
364
423
|
} catch (error) {
|
|
@@ -390,6 +449,83 @@ export function apply(ctx, config = {}) {
|
|
|
390
449
|
return createUserMessage;
|
|
391
450
|
};
|
|
392
451
|
|
|
452
|
+
// 2.1.0(集成 lane):MemoryReader 单例。索引默认写系统临时目录(memoryRoot 只读契约不破)。
|
|
453
|
+
const readerIndexPath = (() => {
|
|
454
|
+
if (cfg.readGate.indexPath !== '') return cfg.readGate.indexPath;
|
|
455
|
+
const digest = createHash('sha256').update(cfg.memoryRoot).digest('hex').slice(0, 16);
|
|
456
|
+
return join(tmpdir(), 'dsh-longlive-reader', `${digest}.idx.json`);
|
|
457
|
+
})();
|
|
458
|
+
let memoryReader = null;
|
|
459
|
+
let memoryReaderBroken = false;
|
|
460
|
+
const getReader = () => {
|
|
461
|
+
if (memoryReader || memoryReaderBroken) return memoryReader;
|
|
462
|
+
try {
|
|
463
|
+
memoryReader = new MemoryReader(cfg.memoryRoot, { indexPath: readerIndexPath });
|
|
464
|
+
} catch (error) {
|
|
465
|
+
memoryReaderBroken = true;
|
|
466
|
+
memoryReader = null;
|
|
467
|
+
warn('READER_INIT_FAILED', error?.code ?? error?.message ?? error);
|
|
468
|
+
}
|
|
469
|
+
return memoryReader;
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
/** readGate.index:true:MemoryReader 索引 → 召回卡形状(四类卡,正文按 getCard 补读)。 */
|
|
473
|
+
const loadCardsFromIndex = () => {
|
|
474
|
+
const reader = getReader();
|
|
475
|
+
if (!reader) throw new Error('READER_UNAVAILABLE');
|
|
476
|
+
reader.ensureIndex();
|
|
477
|
+
const doc = JSON.parse(readFileSync(reader.indexPath, 'utf8'));
|
|
478
|
+
const entries = Array.isArray(doc?.entries) ? doc.entries : [];
|
|
479
|
+
const wanted = new Set(cfg.dirs);
|
|
480
|
+
const out = [];
|
|
481
|
+
for (const entry of entries) {
|
|
482
|
+
const relPath = String(entry?.path ?? '').replace(/\\/g, '/');
|
|
483
|
+
if (relPath === '') continue;
|
|
484
|
+
const top = relPath.split('/')[0];
|
|
485
|
+
if (wanted.size > 0 && !wanted.has(top)) continue;
|
|
486
|
+
let card;
|
|
487
|
+
try { card = reader.getCard(relPath); } catch { continue; }
|
|
488
|
+
if (!card || card.blocked === true || typeof card.body !== 'string' || card.body === '') continue;
|
|
489
|
+
const fields = card.frontmatter?.fields ?? {};
|
|
490
|
+
const listOf = (value) => (Array.isArray(value) ? value.map(String) : typeof value === 'string' && value !== '' ? [value] : []);
|
|
491
|
+
out.push({
|
|
492
|
+
path: card.path,
|
|
493
|
+
title: card.title,
|
|
494
|
+
body: card.body,
|
|
495
|
+
dir: top,
|
|
496
|
+
scopeIn: listOf(fields.scope_in ?? fields.scopeIn),
|
|
497
|
+
scopeOut: listOf(fields.scope_out ?? fields.scopeOut),
|
|
498
|
+
aliases: listOf(card.aliases),
|
|
499
|
+
localOnly: card.localOnly === true,
|
|
500
|
+
salience: Number.isFinite(Number(fields.salience)) ? Number(fields.salience) : null,
|
|
501
|
+
strength: Number.isFinite(Number(fields.strength)) ? Number(fields.strength) : null,
|
|
502
|
+
date: typeof fields.date === 'string' ? fields.date : null,
|
|
503
|
+
hasFrontmatter: card.frontmatter?.hasFrontmatter === true,
|
|
504
|
+
warnings: [],
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
return out;
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
// 2.1.0(集成 lane):链路 fastpath 单例(term→卡 字面直连,不扫全索引)。
|
|
511
|
+
let linkFastPath = null;
|
|
512
|
+
let linkFastPathBroken = false;
|
|
513
|
+
const getLinkFastPath = () => {
|
|
514
|
+
if (linkFastPath || linkFastPathBroken) return linkFastPath;
|
|
515
|
+
try {
|
|
516
|
+
linkFastPath = new LinkFastPath(cfg.memoryRoot, {
|
|
517
|
+
minWeight: cfg.links.minWeight,
|
|
518
|
+
maxCardsPerTerm: cfg.links.maxCardsPerTerm,
|
|
519
|
+
maxCardsPerTurn: Math.min(5, Math.max(1, cfg.links.maxCardsPerTurn)),
|
|
520
|
+
});
|
|
521
|
+
} catch (error) {
|
|
522
|
+
linkFastPathBroken = true;
|
|
523
|
+
linkFastPath = null;
|
|
524
|
+
warn('LINK_FASTPATH_INIT_FAILED', error?.code ?? error?.message ?? error);
|
|
525
|
+
}
|
|
526
|
+
return linkFastPath;
|
|
527
|
+
};
|
|
528
|
+
|
|
393
529
|
// 1.8.8 M2:链路表 = <memoryRoot>/.longlive/recall/links.jsonl(种子 + 学习边)。
|
|
394
530
|
// 按 mtime/size 缓存;读失败/坏文件一律 fail-open:本轮不直连,但绝不抛出。
|
|
395
531
|
const linksCache = {};
|
|
@@ -551,6 +687,65 @@ export function apply(ctx, config = {}) {
|
|
|
551
687
|
warn('LINKS_FEEDBACK_FAILED', error?.code ?? error?.message ?? error);
|
|
552
688
|
}
|
|
553
689
|
}
|
|
690
|
+
// 2.1.0(集成 lane)链路直连:强路径先跑 term→卡 快路径。命中 → readHits 直接拿正文,
|
|
691
|
+
// 本轮不再跑 getCards / embedding / 边扩展;0 命中 / 不可用 → 回落原链路。
|
|
692
|
+
let fastpathHit = false;
|
|
693
|
+
let fastpathItems = [];
|
|
694
|
+
let fastpathCards = [];
|
|
695
|
+
let fastpathStats = null;
|
|
696
|
+
let fastpathMatchedTerms = [];
|
|
697
|
+
if (cfg.links.enabled && lastUserText !== '') {
|
|
698
|
+
try {
|
|
699
|
+
const fastpath = getLinkFastPath();
|
|
700
|
+
if (fastpath) {
|
|
701
|
+
const matched = fastpath.match(lastUserText, { privacyHook: privacyScan });
|
|
702
|
+
if (matched.loaded === true && matched.unavailable !== true
|
|
703
|
+
&& Array.isArray(matched.items) && matched.items.length > 0) {
|
|
704
|
+
const rows = readHits(matched.items, { reader: getReader() });
|
|
705
|
+
const seenFast = new Set(st.seen);
|
|
706
|
+
const items = [];
|
|
707
|
+
const cardsOut = [];
|
|
708
|
+
for (let index = 0; index < matched.items.length; index += 1) {
|
|
709
|
+
const source = matched.items[index];
|
|
710
|
+
const row = rows[index];
|
|
711
|
+
if (!row || typeof row !== 'object' || row.error || row.blocked === true) continue;
|
|
712
|
+
const relPath = typeof row.path === 'string' ? row.path : '';
|
|
713
|
+
const body = typeof row.body === 'string' ? row.body : '';
|
|
714
|
+
if (relPath === '' || body.trim() === '' || seenFast.has(relPath)) continue;
|
|
715
|
+
seenFast.add(relPath);
|
|
716
|
+
const title = typeof row.title === 'string' && row.title !== '' ? row.title : relPath;
|
|
717
|
+
items.push({
|
|
718
|
+
path: relPath,
|
|
719
|
+
title,
|
|
720
|
+
score: Number.isFinite(Number(source?.score)) ? Number(source.score) : 0,
|
|
721
|
+
reason: 'link',
|
|
722
|
+
source: 'link',
|
|
723
|
+
excerpt: body.length <= 240 ? body : `${body.slice(0, 239)}…`,
|
|
724
|
+
link: {
|
|
725
|
+
weight: Number.isFinite(Number(source?.weight)) ? Number(source.weight) : 0,
|
|
726
|
+
terms: String(source?.term ?? ''),
|
|
727
|
+
},
|
|
728
|
+
});
|
|
729
|
+
cardsOut.push({ path: relPath, title, body });
|
|
730
|
+
}
|
|
731
|
+
if (items.length > 0) {
|
|
732
|
+
fastpathHit = true;
|
|
733
|
+
fastpathItems = items;
|
|
734
|
+
fastpathCards = cardsOut;
|
|
735
|
+
fastpathMatchedTerms = Array.isArray(matched.matchedTerms) ? matched.matchedTerms : [];
|
|
736
|
+
fastpathStats = { ...(matched.stats ?? {}), catalogScan: false, fastpath: true };
|
|
737
|
+
laneCounters.fastpathHits += 1;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
} catch (error) {
|
|
742
|
+
warn('LINK_FASTPATH_FAILED', error?.code ?? error?.message ?? error);
|
|
743
|
+
}
|
|
744
|
+
if (!fastpathHit) laneCounters.fastpathMisses += 1;
|
|
745
|
+
}
|
|
746
|
+
// 2.1.0:直连判定(用户裁定:默认 linkSupplement=false);true 才退回 2.0.0 补漏模式。
|
|
747
|
+
const directMode = fastpathHit && cfg.links.linkSupplement !== true;
|
|
748
|
+
|
|
554
749
|
// M2-C R1–R6: shared visibility block is injected on the FIRST turn only.
|
|
555
750
|
const rawSharedNow = payload?.at ?? payload?.eventTime ?? payload?.now ?? null;
|
|
556
751
|
const sharedNow = rawSharedNow === null || rawSharedNow === undefined
|
|
@@ -647,7 +842,8 @@ export function apply(ctx, config = {}) {
|
|
|
647
842
|
gateInfo = gate;
|
|
648
843
|
}
|
|
649
844
|
|
|
650
|
-
|
|
845
|
+
// 2.1.0:直连模式命中时不再整树扫卡(loaded=[]);0 命中/补漏模式照旧 getCards。
|
|
846
|
+
const loaded = directMode ? [] : getCards();
|
|
651
847
|
// 1.8.2 D2: auto-cards are no longer read as recall candidates.
|
|
652
848
|
const loadedForRecall = loaded;
|
|
653
849
|
// 路径级排除:identity-router 本轮已经注入过的卡,不再注入第二遍。
|
|
@@ -661,7 +857,15 @@ export function apply(ctx, config = {}) {
|
|
|
661
857
|
// 命中即注入(日志 source:'link')。隐私(整卡丢弃)/去重/预算/卡片存在性都在
|
|
662
858
|
// selectLinkItems 内部处理;这里的任何异常都只让链路静默失效,不影响常规检索。
|
|
663
859
|
let linkResolution = { items: [], matchedTerms: [], tokens: 0, stats: null };
|
|
664
|
-
if (
|
|
860
|
+
if (fastpathHit) {
|
|
861
|
+
// 2.1.0:命中即用 readHits 正文构造 link item;catalogScan:false = 未扫全索引。
|
|
862
|
+
linkResolution = {
|
|
863
|
+
items: fastpathItems,
|
|
864
|
+
matchedTerms: fastpathMatchedTerms,
|
|
865
|
+
tokens: estimateTokens(renderInjection({ items: fastpathItems }, { privacyScan })),
|
|
866
|
+
stats: fastpathStats,
|
|
867
|
+
};
|
|
868
|
+
} else if (cfg.links.enabled && lastUserText !== '' && linksStore
|
|
665
869
|
&& Array.isArray(linksStore.edges) && linksStore.edges.length > 0) {
|
|
666
870
|
try {
|
|
667
871
|
linkResolution = selectLinkItems({
|
|
@@ -693,8 +897,9 @@ export function apply(ctx, config = {}) {
|
|
|
693
897
|
// (模型缺失、onnxruntime-node 没装、tokenizer 坏)都静默退回纯关键词。
|
|
694
898
|
let queryVector = null;
|
|
695
899
|
let vectors = null;
|
|
696
|
-
if (embedding.enabled) {
|
|
900
|
+
if (embedding.enabled && !directMode) {
|
|
697
901
|
try {
|
|
902
|
+
laneCounters.embeddingEnsureCalls += 1;
|
|
698
903
|
const ready = await embedding.ensure(loaded, { signature: cardsSignature });
|
|
699
904
|
if (ready.ok) {
|
|
700
905
|
queryVector = await embedding.embedQuery(queryText);
|
|
@@ -716,6 +921,10 @@ export function apply(ctx, config = {}) {
|
|
|
716
921
|
}
|
|
717
922
|
|
|
718
923
|
// B3: budget phase = ranking + budget trimming inside chooseRecall.
|
|
924
|
+
const chooseRecallStep = (input) => {
|
|
925
|
+
laneCounters.chooseRecallCalls += 1;
|
|
926
|
+
return chooseRecall(input);
|
|
927
|
+
};
|
|
719
928
|
const budgetPhase = startPrestepPhase(key, turn, 'budget');
|
|
720
929
|
const recallInput = {
|
|
721
930
|
queryText: expandedQuery,
|
|
@@ -742,7 +951,11 @@ export function apply(ctx, config = {}) {
|
|
|
742
951
|
},
|
|
743
952
|
},
|
|
744
953
|
};
|
|
745
|
-
|
|
954
|
+
// 2.1.0:直连模式跳过 chooseRecall(不扫候选、不算分),用同形状零结果占位,
|
|
955
|
+
// 下游审计/预算记账字段(hits.eligible 等)保持齐全。
|
|
956
|
+
let result = directMode
|
|
957
|
+
? emptyRecallResult({ contextBoosted: queryTimeRefs.length > 0 || aliases.present === true })
|
|
958
|
+
: chooseRecallStep(recallInput);
|
|
746
959
|
budgetPhase.end();
|
|
747
960
|
// 1.8.0 two-layer quota: at most 2 curated cards + 1 AutoCard per turn;
|
|
748
961
|
// curated hits always render first (tier weight 1.12 only affects order
|
|
@@ -754,7 +967,7 @@ export function apply(ctx, config = {}) {
|
|
|
754
967
|
const eventItems = result.items.filter(isAuto).slice(0, 1);
|
|
755
968
|
// Curated floor: event cards may never squeeze curated cards out.
|
|
756
969
|
if (curatedItems.length === 0 && loaded.length > 0) {
|
|
757
|
-
const curatedOnly =
|
|
970
|
+
const curatedOnly = chooseRecallStep({ ...recallInput, cards: loaded });
|
|
758
971
|
if (curatedOnly.items.length > 0) {
|
|
759
972
|
result = curatedOnly;
|
|
760
973
|
curatedItems = curatedOnly.items.slice().sort((a, b) => (b.score * 1.12) - (a.score * 1.12));
|
|
@@ -984,6 +1197,9 @@ export function apply(ctx, config = {}) {
|
|
|
984
1197
|
matchedTerms: Array.isArray(linkResolution.matchedTerms) ? linkResolution.matchedTerms : [],
|
|
985
1198
|
injectedCount: linkItems.length,
|
|
986
1199
|
tokens: linkTokens,
|
|
1200
|
+
// 2.1.0:链路直连命中时 catalogScan=false(没扫全索引),供 gate-log/recall-log 取证。
|
|
1201
|
+
catalogScan: linkResolution.stats?.catalogScan === false ? false : null,
|
|
1202
|
+
fastpath: fastpathHit === true,
|
|
987
1203
|
};
|
|
988
1204
|
let archiveUnavailable = false;
|
|
989
1205
|
let archiveBlock = null;
|
|
@@ -1214,7 +1430,7 @@ export function apply(ctx, config = {}) {
|
|
|
1214
1430
|
turn,
|
|
1215
1431
|
messageText: lastUserText,
|
|
1216
1432
|
injected: logItems,
|
|
1217
|
-
cards: loaded,
|
|
1433
|
+
cards: directMode ? fastpathCards : loaded,
|
|
1218
1434
|
edges: linksStore?.edges ?? [],
|
|
1219
1435
|
now: Date.now(),
|
|
1220
1436
|
config: cfg.links,
|
|
@@ -1307,6 +1523,116 @@ export function apply(ctx, config = {}) {
|
|
|
1307
1523
|
}
|
|
1308
1524
|
}, { prepend: false });
|
|
1309
1525
|
|
|
1526
|
+
// 2.1.0(集成 lane)volatile 连续性:外层包装监听器(prepend:true,在 identity-router 之外)。
|
|
1527
|
+
// - 有宿主哨兵:每步在 next() 后的 decision 上挂 volatileMessages(不写 session、不改 kind),
|
|
1528
|
+
// step1 ≤990 / step>1 ≤400 / 子代理 ≤250(lane-core 模块经字符硬断言保证)。
|
|
1529
|
+
// - 无哨兵:enabled:'auto' 不注入(2.0.0 行为);显式 true 或 fallbackToPersistent:true 才回落 v0.2 持久块。
|
|
1530
|
+
// - 审计:每轮聚合一行 continuity.jsonl + 一行 gate:'continuity' gate-log(evidence 带 cont 片段)。
|
|
1531
|
+
const continuityRows = new Map(); // `${sessionId}\u0000${turn}` → record[]
|
|
1532
|
+
const flushContinuity = (mapKey) => {
|
|
1533
|
+
const records = continuityRows.get(mapKey);
|
|
1534
|
+
if (!records || records.length === 0) return null;
|
|
1535
|
+
continuityRows.delete(mapKey);
|
|
1536
|
+
const sep = mapKey.lastIndexOf('\u0000');
|
|
1537
|
+
const sessionId = sep >= 0 ? mapKey.slice(0, sep) : 'unknown';
|
|
1538
|
+
const turn = sep >= 0 ? Number(mapKey.slice(sep + 1)) : 0;
|
|
1539
|
+
if (typeof cfg.memoryRoot !== 'string' || cfg.memoryRoot === '') return null;
|
|
1540
|
+
let row = null;
|
|
1541
|
+
try {
|
|
1542
|
+
row = writeTurnRow(cfg.memoryRoot, records, { turn })?.row ?? null;
|
|
1543
|
+
} catch (error) {
|
|
1544
|
+
warn('CONTINUITY_LOG_FAILED', error?.code ?? error?.message ?? error);
|
|
1545
|
+
return null;
|
|
1546
|
+
}
|
|
1547
|
+
if (row) {
|
|
1548
|
+
try {
|
|
1549
|
+
appendGateLog(cfg.memoryRoot, {
|
|
1550
|
+
sessionId,
|
|
1551
|
+
turn: Number.isFinite(turn) ? turn : 0,
|
|
1552
|
+
gate: 'continuity',
|
|
1553
|
+
decision: row.mode === 'volatile' ? 'ok' : row.mode === 'fail' ? 'fail' : 'warn',
|
|
1554
|
+
reason: String(row.mode ?? 'off'),
|
|
1555
|
+
evidence: [continuityEvidence(row)],
|
|
1556
|
+
});
|
|
1557
|
+
} catch (error) {
|
|
1558
|
+
warn('CONTINUITY_GATE_LOG_FAILED', error?.code ?? error?.message ?? error);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
return row;
|
|
1562
|
+
};
|
|
1563
|
+
let continuity = null;
|
|
1564
|
+
const getContinuity = async () => {
|
|
1565
|
+
if (continuity) return continuity;
|
|
1566
|
+
const factory = await getCreateUserMessage();
|
|
1567
|
+
const readCards = async ({ maxCards, maxCardChars } = {}) => {
|
|
1568
|
+
const limit = Number.isFinite(Number(maxCards)) ? Math.max(1, Number(maxCards)) : cfg.continuity.maxCards;
|
|
1569
|
+
const cap = Number.isFinite(Number(maxCardChars)) ? Math.max(120, Number(maxCardChars)) : cfg.continuity.maxCardChars;
|
|
1570
|
+
const list = getCards();
|
|
1571
|
+
const picked = [];
|
|
1572
|
+
let dropped = 0;
|
|
1573
|
+
for (const card of list) {
|
|
1574
|
+
if (picked.length >= limit) break;
|
|
1575
|
+
if (!card || card.localOnly === true || typeof card.body !== 'string' || card.body.trim() === '') { dropped += 1; continue; }
|
|
1576
|
+
let privacy = null;
|
|
1577
|
+
try { privacy = privacyScan(`${card.title ?? ''}\n${card.body}`); } catch { privacy = null; }
|
|
1578
|
+
if (privacy?.verdict === 'local_only') { dropped += 1; continue; }
|
|
1579
|
+
picked.push({
|
|
1580
|
+
title: card.title,
|
|
1581
|
+
text: card.body.length <= cap ? card.body : `${card.body.slice(0, Math.max(1, cap - 1))}…`,
|
|
1582
|
+
maxChars: cap,
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
return { cards: picked, dropped, source: 'memory-reader' };
|
|
1586
|
+
};
|
|
1587
|
+
continuity = createContinuityVolatile({
|
|
1588
|
+
enabled: cfg.continuity.enabled !== false,
|
|
1589
|
+
memoryRoot: cfg.memoryRoot,
|
|
1590
|
+
createUserMessage: factory,
|
|
1591
|
+
readCards,
|
|
1592
|
+
personaHeader: cfg.continuity.personaHeader,
|
|
1593
|
+
subagentIdentity: cfg.continuity.subagentIdentity,
|
|
1594
|
+
maxCards: cfg.continuity.maxCards,
|
|
1595
|
+
maxCardChars: cfg.continuity.maxCardChars,
|
|
1596
|
+
});
|
|
1597
|
+
return continuity;
|
|
1598
|
+
};
|
|
1599
|
+
// 2.1.0 裁定:无哨兵 + enabled:'auto' 时不注册包装监听器 → 2.0.0 的钩子数量保持不变
|
|
1600
|
+
// (rc.4/rc.5 的「only the always-on hardgate handler」计数回归依赖这一点)。
|
|
1601
|
+
const continuityActive = cfg.continuity.enabled === true
|
|
1602
|
+
|| (cfg.continuity.enabled !== false
|
|
1603
|
+
&& (probeVolatileHost() === true || cfg.continuity.fallbackToPersistent === true));
|
|
1604
|
+
const registerContinuityWrapper = () => ctx.on('agent/pre-step', async (payload, next) => {
|
|
1605
|
+
const decision = await next();
|
|
1606
|
+
try {
|
|
1607
|
+
if (!decision || decision.kind === 'reject') return decision;
|
|
1608
|
+
const mode = cfg.continuity.enabled;
|
|
1609
|
+
if (mode === false) return decision;
|
|
1610
|
+
const hostVolatile = probeVolatileHost() === true;
|
|
1611
|
+
if (!hostVolatile && mode !== true && cfg.continuity.fallbackToPersistent !== true) return decision;
|
|
1612
|
+
const sessionId = sessionIdOf(payload);
|
|
1613
|
+
const turn = Number.isFinite(Number(payload?.turn)) ? Math.max(0, Number(payload.turn)) : 0;
|
|
1614
|
+
// turn 切换时先把上一轮聚合行落盘(turn/end 事件顺序由宿主决定,双保险)。
|
|
1615
|
+
for (const mapKey of [...continuityRows.keys()]) {
|
|
1616
|
+
const sep = mapKey.lastIndexOf('\u0000');
|
|
1617
|
+
const otherTurn = sep >= 0 ? Number(mapKey.slice(sep + 1)) : NaN;
|
|
1618
|
+
if (!Number.isFinite(otherTurn) || otherTurn !== turn) flushContinuity(mapKey);
|
|
1619
|
+
}
|
|
1620
|
+
const cont = await getContinuity();
|
|
1621
|
+
const out = await cont.inject(payload, decision);
|
|
1622
|
+
if (out?.continuity) {
|
|
1623
|
+
const mapKey = `${sessionId}\u0000${turn}`;
|
|
1624
|
+
const list = continuityRows.get(mapKey) ?? [];
|
|
1625
|
+
list.push(out.continuity);
|
|
1626
|
+
continuityRows.set(mapKey, list);
|
|
1627
|
+
}
|
|
1628
|
+
return out ?? decision;
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
warn('CONTINUITY_INJECT_FAILED', error?.code ?? error?.message ?? error);
|
|
1631
|
+
return decision;
|
|
1632
|
+
}
|
|
1633
|
+
}, { prepend: true });
|
|
1634
|
+
if (continuityActive) registerContinuityWrapper();
|
|
1635
|
+
|
|
1310
1636
|
// 首条用户消息 + 轮数 + 压缩标记
|
|
1311
1637
|
ctx.on('session/event', (session, event) => {
|
|
1312
1638
|
try {
|
|
@@ -1324,6 +1650,13 @@ export function apply(ctx, config = {}) {
|
|
|
1324
1650
|
if (event?.type === 'turn/end') {
|
|
1325
1651
|
const t = Number(event?.data?.turn);
|
|
1326
1652
|
st.turn = Number.isFinite(t) ? Math.max(st.turn, t) : st.turn + 1;
|
|
1653
|
+
// 2.1.0:一轮结束落盘 continuity 审计行(每轮一行,聚合全部 step 记录)。
|
|
1654
|
+
// 按 turn 匹配而非 sessionId:payload 里未必带 session,记录里的 sessionId 可能是 unknown。
|
|
1655
|
+
for (const mapKey of [...continuityRows.keys()]) {
|
|
1656
|
+
const sep = mapKey.lastIndexOf('\u0000');
|
|
1657
|
+
const rowTurn = sep >= 0 ? Number(mapKey.slice(sep + 1)) : NaN;
|
|
1658
|
+
if (Number.isFinite(t) ? rowTurn === t : rowTurn === st.turn) flushContinuity(mapKey);
|
|
1659
|
+
}
|
|
1327
1660
|
}
|
|
1328
1661
|
if (/compaction/i.test(String(event?.type ?? ''))) st.compacted = true; // 上线前先核事件名(WIRING §8)
|
|
1329
1662
|
} catch (error) {
|