@jjh32456/longlive 2.0.0 → 2.2.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.
@@ -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
- const loaded = getCards();
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 (cfg.links.enabled && lastUserText !== '' && linksStore
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
- let result = chooseRecall(recallInput);
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 = chooseRecall({ ...recallInput, cards: loaded });
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;
@@ -1042,6 +1258,7 @@ export function apply(ctx, config = {}) {
1042
1258
  let zeroRendered = null;
1043
1259
  let zeroLane = null;
1044
1260
  let zeroProcedures = 0;
1261
+ let zeroProcedureList = [];
1045
1262
  if (hardgatePending) {
1046
1263
  let procedures = [];
1047
1264
  try {
@@ -1050,6 +1267,7 @@ export function apply(ctx, config = {}) {
1050
1267
  warn('HARDGATE_PROCEDURES_FAILED', error?.code ?? error?.message ?? error);
1051
1268
  }
1052
1269
  zeroProcedures = procedures.length;
1270
+ zeroProcedureList = procedures;
1053
1271
  zeroRendered = renderPendingBlock({
1054
1272
  pending: hardgatePending,
1055
1273
  items: [],
@@ -1116,6 +1334,8 @@ export function apply(ctx, config = {}) {
1116
1334
  factory: zeroFactory,
1117
1335
  items: 0,
1118
1336
  procedures: zeroProcedures,
1337
+ procedureNames: zeroProcedureList.map((item) => String(item?.name ?? '')),
1338
+ procedurePaths: zeroProcedureList.map((item) => String(item?.path ?? '')),
1119
1339
  scanned: result.hits.eligible,
1120
1340
  extra: zeroBudget === null ? [] : [zeroBudget.evidence],
1121
1341
  metrics: zeroMetrics,
@@ -1139,6 +1359,7 @@ export function apply(ctx, config = {}) {
1139
1359
  // 当前线都在块里,capBlock 保证 ≤ budget。
1140
1360
  let hardgateHit = null;
1141
1361
  let hardgateProcedures = 0;
1362
+ let hardgateProcedureList = [];
1142
1363
  if (hardgatePending && !fromArchive) {
1143
1364
  let procedures = [];
1144
1365
  try {
@@ -1150,6 +1371,7 @@ export function apply(ctx, config = {}) {
1150
1371
  finalText = rendered.block;
1151
1372
  hardgateHit = rendered.hit;
1152
1373
  hardgateProcedures = procedures.length;
1374
+ hardgateProcedureList = procedures;
1153
1375
  }
1154
1376
  // B3 C6/C4:最终块(硬门块或 legacy 块)统一过 990 字车道并产出注入度量;
1155
1377
  // 该度量写进 recall-log(injectedChars/injectedTokens)与 gate-log(B1/C1)。
@@ -1214,7 +1436,7 @@ export function apply(ctx, config = {}) {
1214
1436
  turn,
1215
1437
  messageText: lastUserText,
1216
1438
  injected: logItems,
1217
- cards: loaded,
1439
+ cards: directMode ? fastpathCards : loaded,
1218
1440
  edges: linksStore?.edges ?? [],
1219
1441
  now: Date.now(),
1220
1442
  config: cfg.links,
@@ -1264,6 +1486,8 @@ export function apply(ctx, config = {}) {
1264
1486
  hit: fromArchive ? true : hardgateHit === true,
1265
1487
  items: fromArchive ? archiveItems.length : result.items.length,
1266
1488
  procedures: fromArchive ? 0 : hardgateProcedures,
1489
+ procedureNames: fromArchive ? [] : hardgateProcedureList.map((item) => String(item?.name ?? '')),
1490
+ procedurePaths: fromArchive ? [] : hardgateProcedureList.map((item) => String(item?.path ?? '')),
1267
1491
  scanned: result.hits.eligible,
1268
1492
  extra: [turnBudget.evidence],
1269
1493
  metrics: laneMetrics,
@@ -1307,6 +1531,116 @@ export function apply(ctx, config = {}) {
1307
1531
  }
1308
1532
  }, { prepend: false });
1309
1533
 
1534
+ // 2.1.0(集成 lane)volatile 连续性:外层包装监听器(prepend:true,在 identity-router 之外)。
1535
+ // - 有宿主哨兵:每步在 next() 后的 decision 上挂 volatileMessages(不写 session、不改 kind),
1536
+ // step1 ≤990 / step>1 ≤400 / 子代理 ≤250(lane-core 模块经字符硬断言保证)。
1537
+ // - 无哨兵:enabled:'auto' 不注入(2.0.0 行为);显式 true 或 fallbackToPersistent:true 才回落 v0.2 持久块。
1538
+ // - 审计:每轮聚合一行 continuity.jsonl + 一行 gate:'continuity' gate-log(evidence 带 cont 片段)。
1539
+ const continuityRows = new Map(); // `${sessionId}\u0000${turn}` → record[]
1540
+ const flushContinuity = (mapKey) => {
1541
+ const records = continuityRows.get(mapKey);
1542
+ if (!records || records.length === 0) return null;
1543
+ continuityRows.delete(mapKey);
1544
+ const sep = mapKey.lastIndexOf('\u0000');
1545
+ const sessionId = sep >= 0 ? mapKey.slice(0, sep) : 'unknown';
1546
+ const turn = sep >= 0 ? Number(mapKey.slice(sep + 1)) : 0;
1547
+ if (typeof cfg.memoryRoot !== 'string' || cfg.memoryRoot === '') return null;
1548
+ let row = null;
1549
+ try {
1550
+ row = writeTurnRow(cfg.memoryRoot, records, { turn })?.row ?? null;
1551
+ } catch (error) {
1552
+ warn('CONTINUITY_LOG_FAILED', error?.code ?? error?.message ?? error);
1553
+ return null;
1554
+ }
1555
+ if (row) {
1556
+ try {
1557
+ appendGateLog(cfg.memoryRoot, {
1558
+ sessionId,
1559
+ turn: Number.isFinite(turn) ? turn : 0,
1560
+ gate: 'continuity',
1561
+ decision: row.mode === 'volatile' ? 'ok' : row.mode === 'fail' ? 'fail' : 'warn',
1562
+ reason: String(row.mode ?? 'off'),
1563
+ evidence: [continuityEvidence(row)],
1564
+ });
1565
+ } catch (error) {
1566
+ warn('CONTINUITY_GATE_LOG_FAILED', error?.code ?? error?.message ?? error);
1567
+ }
1568
+ }
1569
+ return row;
1570
+ };
1571
+ let continuity = null;
1572
+ const getContinuity = async () => {
1573
+ if (continuity) return continuity;
1574
+ const factory = await getCreateUserMessage();
1575
+ const readCards = async ({ maxCards, maxCardChars } = {}) => {
1576
+ const limit = Number.isFinite(Number(maxCards)) ? Math.max(1, Number(maxCards)) : cfg.continuity.maxCards;
1577
+ const cap = Number.isFinite(Number(maxCardChars)) ? Math.max(120, Number(maxCardChars)) : cfg.continuity.maxCardChars;
1578
+ const list = getCards();
1579
+ const picked = [];
1580
+ let dropped = 0;
1581
+ for (const card of list) {
1582
+ if (picked.length >= limit) break;
1583
+ if (!card || card.localOnly === true || typeof card.body !== 'string' || card.body.trim() === '') { dropped += 1; continue; }
1584
+ let privacy = null;
1585
+ try { privacy = privacyScan(`${card.title ?? ''}\n${card.body}`); } catch { privacy = null; }
1586
+ if (privacy?.verdict === 'local_only') { dropped += 1; continue; }
1587
+ picked.push({
1588
+ title: card.title,
1589
+ text: card.body.length <= cap ? card.body : `${card.body.slice(0, Math.max(1, cap - 1))}…`,
1590
+ maxChars: cap,
1591
+ });
1592
+ }
1593
+ return { cards: picked, dropped, source: 'memory-reader' };
1594
+ };
1595
+ continuity = createContinuityVolatile({
1596
+ enabled: cfg.continuity.enabled !== false,
1597
+ memoryRoot: cfg.memoryRoot,
1598
+ createUserMessage: factory,
1599
+ readCards,
1600
+ personaHeader: cfg.continuity.personaHeader,
1601
+ subagentIdentity: cfg.continuity.subagentIdentity,
1602
+ maxCards: cfg.continuity.maxCards,
1603
+ maxCardChars: cfg.continuity.maxCardChars,
1604
+ });
1605
+ return continuity;
1606
+ };
1607
+ // 2.1.0 裁定:无哨兵 + enabled:'auto' 时不注册包装监听器 → 2.0.0 的钩子数量保持不变
1608
+ // (rc.4/rc.5 的「only the always-on hardgate handler」计数回归依赖这一点)。
1609
+ const continuityActive = cfg.continuity.enabled === true
1610
+ || (cfg.continuity.enabled !== false
1611
+ && (probeVolatileHost() === true || cfg.continuity.fallbackToPersistent === true));
1612
+ const registerContinuityWrapper = () => ctx.on('agent/pre-step', async (payload, next) => {
1613
+ const decision = await next();
1614
+ try {
1615
+ if (!decision || decision.kind === 'reject') return decision;
1616
+ const mode = cfg.continuity.enabled;
1617
+ if (mode === false) return decision;
1618
+ const hostVolatile = probeVolatileHost() === true;
1619
+ if (!hostVolatile && mode !== true && cfg.continuity.fallbackToPersistent !== true) return decision;
1620
+ const sessionId = sessionIdOf(payload);
1621
+ const turn = Number.isFinite(Number(payload?.turn)) ? Math.max(0, Number(payload.turn)) : 0;
1622
+ // turn 切换时先把上一轮聚合行落盘(turn/end 事件顺序由宿主决定,双保险)。
1623
+ for (const mapKey of [...continuityRows.keys()]) {
1624
+ const sep = mapKey.lastIndexOf('\u0000');
1625
+ const otherTurn = sep >= 0 ? Number(mapKey.slice(sep + 1)) : NaN;
1626
+ if (!Number.isFinite(otherTurn) || otherTurn !== turn) flushContinuity(mapKey);
1627
+ }
1628
+ const cont = await getContinuity();
1629
+ const out = await cont.inject(payload, decision);
1630
+ if (out?.continuity) {
1631
+ const mapKey = `${sessionId}\u0000${turn}`;
1632
+ const list = continuityRows.get(mapKey) ?? [];
1633
+ list.push(out.continuity);
1634
+ continuityRows.set(mapKey, list);
1635
+ }
1636
+ return out ?? decision;
1637
+ } catch (error) {
1638
+ warn('CONTINUITY_INJECT_FAILED', error?.code ?? error?.message ?? error);
1639
+ return decision;
1640
+ }
1641
+ }, { prepend: true });
1642
+ if (continuityActive) registerContinuityWrapper();
1643
+
1310
1644
  // 首条用户消息 + 轮数 + 压缩标记
1311
1645
  ctx.on('session/event', (session, event) => {
1312
1646
  try {
@@ -1324,6 +1658,13 @@ export function apply(ctx, config = {}) {
1324
1658
  if (event?.type === 'turn/end') {
1325
1659
  const t = Number(event?.data?.turn);
1326
1660
  st.turn = Number.isFinite(t) ? Math.max(st.turn, t) : st.turn + 1;
1661
+ // 2.1.0:一轮结束落盘 continuity 审计行(每轮一行,聚合全部 step 记录)。
1662
+ // 按 turn 匹配而非 sessionId:payload 里未必带 session,记录里的 sessionId 可能是 unknown。
1663
+ for (const mapKey of [...continuityRows.keys()]) {
1664
+ const sep = mapKey.lastIndexOf('\u0000');
1665
+ const rowTurn = sep >= 0 ? Number(mapKey.slice(sep + 1)) : NaN;
1666
+ if (Number.isFinite(t) ? rowTurn === t : rowTurn === st.turn) flushContinuity(mapKey);
1667
+ }
1327
1668
  }
1328
1669
  if (/compaction/i.test(String(event?.type ?? ''))) st.compacted = true; // 上线前先核事件名(WIRING §8)
1329
1670
  } catch (error) {