@jjh32456/longlive 1.8.12 → 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.
Files changed (92) hide show
  1. package/CHANGELOG.md +258 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +61 -18
  5. package/SPEC.md +3 -3
  6. package/build-info.json +259 -129
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ANSWER-GUARD.md +1 -1
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +5 -3
  11. package/docs/AUTO-RECALL.md +10 -4
  12. package/docs/CONFIG.md +46 -11
  13. package/docs/ERRORS.md +1 -1
  14. package/docs/FAQ.md +9 -9
  15. package/docs/FEATURES.md +19 -16
  16. package/docs/OPERATIONS.md +3 -3
  17. package/docs/PANEL-INTEGRATION.md +1 -1
  18. package/docs/PRIVACY.md +6 -6
  19. package/docs/QUICKSTART.md +5 -5
  20. package/docs/README.en.md +5 -3
  21. package/docs/TOOLS.md +1 -1
  22. package/docs/TROUBLESHOOTING.md +4 -4
  23. package/package.json +6 -3
  24. package/runbook.md +3 -3
  25. package/scripts/migrate-200.mjs +8 -0
  26. package/scripts/migrate-lifecycle.mjs +2 -2
  27. package/src/answer/claim-guard.mjs +234 -0
  28. package/src/backup.js +165 -1
  29. package/src/config.js +18 -7
  30. package/src/features.js +132 -5
  31. package/src/handoff/index.js +133 -0
  32. package/src/handoff/model.js +48 -0
  33. package/src/identity/handover.js +203 -15
  34. package/src/identity/inject-position.js +3 -1
  35. package/src/index.js +2 -2
  36. package/src/memory/a1-migration.js +72 -6
  37. package/src/memory/archive-cold-state.mjs +794 -0
  38. package/src/memory/archive-staging.mjs +305 -0
  39. package/src/memory/archive.mjs +415 -0
  40. package/src/memory/capture-host.js +71 -2
  41. package/src/memory/capture.js +45 -6
  42. package/src/memory/catchup.mjs +534 -0
  43. package/src/memory/conclusion-distill.js +51 -2
  44. package/src/memory/conclusion-drafts.js +7 -3
  45. package/src/memory/conflicts.js +915 -2
  46. package/src/memory/consolidate.js +20 -1
  47. package/src/memory/forget-v2.js +272 -2
  48. package/src/memory/forget.js +20 -1
  49. package/src/memory/frames-activation.js +3 -1
  50. package/src/memory/fts-query.js +2 -2
  51. package/src/memory/index.js +80 -7
  52. package/src/memory/land.mjs +743 -0
  53. package/src/memory/lifecycle.js +128 -0
  54. package/src/memory/maintenance.js +386 -22
  55. package/src/memory/memory-health.mjs +607 -0
  56. package/src/memory/memory-reader.mjs +1003 -0
  57. package/src/memory/migrate-200.js +1681 -0
  58. package/src/memory/migrate-lifecycle.js +3 -3
  59. package/src/memory/procedure-candidate.mjs +377 -0
  60. package/src/memory/procedure.js +20 -1
  61. package/src/memory/prospective-memory.mjs +362 -0
  62. package/src/memory/recall-feedback.mjs +406 -0
  63. package/src/memory/recall-v2.js +13 -1
  64. package/src/memory/recall.js +102 -1
  65. package/src/memory/reinforce.js +138 -2
  66. package/src/memory/retention.js +34 -0
  67. package/src/memory/turn-budget.mjs +290 -0
  68. package/src/memory/wake-bridge.mjs +2999 -0
  69. package/src/memory/working-frame.js +271 -8
  70. package/src/metrics/classify.mjs +3 -1
  71. package/src/recall/archive-config.mjs +130 -0
  72. package/src/recall/archive-fallback.mjs +174 -19
  73. package/src/recall/archive-search.mjs +3 -0
  74. package/src/recall/archive-state.mjs +588 -0
  75. package/src/recall/brain.mjs +501 -0
  76. package/src/recall/continuity-log.mjs +435 -0
  77. package/src/recall/continuity-volatile.mjs +1001 -0
  78. package/src/recall/current-line.mjs +110 -0
  79. package/src/recall/edges.js +21 -2
  80. package/src/recall/explain.mjs +10 -0
  81. package/src/recall/gate-log.mjs +280 -0
  82. package/src/recall/gate-metrics.mjs +191 -0
  83. package/src/recall/index.js +663 -29
  84. package/src/recall/inject-order.mjs +3 -1
  85. package/src/recall/link-fastpath.mjs +662 -0
  86. package/src/recall/recall-core.mjs +74 -2
  87. package/src/recall/turn-budget-inject.mjs +154 -0
  88. package/src/retention/cold-gate.mjs +146 -0
  89. package/src/retention/config.js +58 -1
  90. package/src/retention/index.js +193 -35
  91. package/src/router/design-headings.json +10 -10
  92. package/src/tools.js +122 -6
@@ -30,8 +30,26 @@ 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
+ // B3 C6:召回车道字符账(990 = 头 60 + 卡区 750 + 程序卡 120 + 当前线 60)。
36
+ import {
37
+ applyRecallLaneBudget,
38
+ buildRecallLaneMetrics,
39
+ recallLaneCapChars,
40
+ resolveRecallInjectionDecision,
41
+ } from './turn-budget-inject.mjs';
42
+ // B3 九项预算接线(P1):每轮注入前把各车道**实际文本**合成一条 ≤2,000 字符的预算块(C1/C2/C6),
43
+ // 并把逐车道字符账写进 gate-log evidence;before 2.0.0 这些常量与组合器只在模块里、注入链没人调用。
44
+ import {
45
+ TURN_BUDGET_LANE_ORDER,
46
+ assertTurnBudgetMessage,
47
+ charLength,
48
+ composeTurnBlocks,
49
+ estimateTurnTokens,
50
+ getTurnBudgetCap,
51
+ } from '../memory/turn-budget.mjs';
52
+ import { finishPendingInjection, recordPendingFailure, recordPendingResult, renderPendingBlock, runHardGate, selectProcedures } from './brain.mjs';
35
53
  import { createEmbeddingRuntime } from './embedding.mjs';
36
54
  import { privacyScan } from './privacy.mjs';
37
55
  // 1.8.8 M2:强制触发 / 链路直连 / 在线学习 / 归档兜底。
@@ -61,17 +79,45 @@ import {
61
79
  isRealUserMessage,
62
80
  mergeInjectionOrder,
63
81
  } from './inject-order.mjs';
64
- import { appendFileSync, mkdirSync, readdirSync, statSync } from 'node:fs';
82
+ // 2.0.0 D22 防编(W4):只读复用 answer/guard.js 的判定,pre-step 扫上一轮 assistant 文本,
83
+ // 命中 requires-source 时生成 ≤50 字提醒块并写 hg.d22.fail;不阻断本轮召回/回答。
84
+ import { applyClaimGuard } from '../answer/claim-guard.mjs';
85
+ // 2.0.0 W3b(M32):冷档不可用 + 有检索需求时写唯一一行 hg.d19.fail(A6 五码族,行内带 code)。
86
+ import { appendGateLog } from './gate-log.mjs';
87
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
65
88
  import { dirname, join } from 'node:path';
66
89
  import { dshHome } from '../home.js';
67
90
  import { DEFAULT_MEMORY_DIRNAME } from '../memory/paths.js';
68
91
  import { lifecycleRank, readCardLifecycle } from '../memory/lifecycle.js';
69
92
  import { startPrestepPhase, notePrestepDegrade, setPrestepMeta } from '../metrics/prestep-latency.mjs';
70
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';
71
101
 
72
102
  export const name = 'dsh-auto-recall';
73
103
  export const inject = [];
74
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
+
75
121
  /** Env names shared with src/memory/paths.js (single naming scheme). */
76
122
  const MEMORY_ROOT_ENV = 'DSH_LONGLIVE_MEMORY_ROOT';
77
123
  const LEGACY_MEMORY_ROOT_ENV = 'DSH_MEM';
@@ -108,6 +154,10 @@ const DEFAULTS = Object.freeze({
108
154
  forceOnUserMessage: true,
109
155
  // 1.8.8 M2:链路直连 + 在线学习(默认开;关闭后不读、不写、不学 links.jsonl)。
110
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 },
111
161
  });
112
162
 
113
163
  function normalize(config = {}) {
@@ -127,6 +177,27 @@ function normalize(config = {}) {
127
177
  cfg.links = normalizeLinksConfig(config.links);
128
178
  // 测试/嵌入时可注入消息工厂,避免依赖 @deepseek-ai/dsh-llm 的解析环境。
129
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
+ };
130
201
  // embedding 由 embedding.mjs 自己归一化(enabled 默认 false、modelPath 必填)。
131
202
  cfg.embedding = config.embedding && typeof config.embedding === 'object' ? { ...config.embedding } : { enabled: true };
132
203
  cfg.evidencePackage = cfg.evidencePackage !== false;
@@ -165,9 +236,60 @@ function firstTextOf(data) {
165
236
  return typeof data?.text === 'string' ? data.text : null;
166
237
  }
167
238
 
239
+ /**
240
+ * B3 九项预算接线(P1):把本轮**实际要注入的文本**按 9 条车道合成一条 ≤2,000 字符的预算块。
241
+ *
242
+ * 数据源口径(只填真实文本,不伪造车道内容):
243
+ * - recall ← 本轮召回块(applyRecallLaneBudget 之后,≤990)
244
+ * - antiFabrication ← 防编提示(claim-guard 命中才非空;≤47 时并入本块承载,过长仍走独立消息)
245
+ * - working/prospective/review/conflict/activity/alert ← 由各自产生者提供(D12/D15/D17… 交付前如实为 0)
246
+ * - margin ← 预算保留(不塞文本;composeTurnBlocks 不参与拼装)
247
+ * 返回的 lanes 是 9 车道逐条字符账(0 也列出),evidence 进 gate-log evidence 供独立复算。
248
+ */
249
+ function composeInjectionTurnBudget({ recallText, claimGuardText = '', laneTexts = {} } = {}) {
250
+ const claim = typeof claimGuardText === 'string' ? claimGuardText : '';
251
+ // 车道 cap 是 50;【防编】前缀占 3 字符,只有 ≤47 的提示才能整条并入而不被裁剪。
252
+ const antiFabricationText = claim !== '' && charLength(claim) <= 47 ? `【防编】${claim}` : '';
253
+ const blocks = [];
254
+ if (typeof recallText === 'string' && recallText !== '') blocks.push({ lane: 'recall', text: recallText });
255
+ if (antiFabricationText !== '') blocks.push({ lane: 'antiFabrication', text: antiFabricationText });
256
+ for (const lane of TURN_BUDGET_LANE_ORDER) {
257
+ const text = laneTexts?.[lane];
258
+ const measured = lane !== 'recall' && lane !== 'antiFabrication' && lane !== 'margin'
259
+ && typeof text === 'string' && text !== '';
260
+ if (measured) blocks.push({ lane, text });
261
+ }
262
+ const composed = composeTurnBlocks(blocks);
263
+ // C2:整块 ≤2,000 字符;超了显式抛 E_HG_TURN_BUDGET_OVERFLOW,不静默吞掉整块。
264
+ assertTurnBudgetMessage(composed);
265
+ const lanes = {};
266
+ for (const lane of TURN_BUDGET_LANE_ORDER) {
267
+ const part = composed.parts.find((entry) => entry.lane === lane);
268
+ lanes[lane] = {
269
+ chars: part?.chars ?? 0,
270
+ cap: getTurnBudgetCap(lane),
271
+ rendered: part !== undefined,
272
+ };
273
+ }
274
+ const evidence = `budget=${composed.usedChars}/${composed.totalChars}`
275
+ + ` lanes=${TURN_BUDGET_LANE_ORDER.map((lane) => `${lane}:${lanes[lane].chars}`).join(',')}`;
276
+ return {
277
+ schema: 'turn-budget/v1',
278
+ text: composed.text,
279
+ lanes,
280
+ composed,
281
+ claimGuardFolded: antiFabricationText !== '',
282
+ usedChars: composed.usedChars,
283
+ totalChars: composed.totalChars,
284
+ trimmedLanes: composed.trimmedLanes,
285
+ evidence,
286
+ };
287
+ }
288
+
168
289
  export function apply(ctx, config = {}) {
169
290
  const cfg = normalize(config);
170
- if (cfg.autoRecall === false) return; // ← 总开关:autoRecall:false 时不注册任何钩子
291
+ // 2.0.0 硬门(M01/M04):handler 恒注册;autoRecall:false 不再「不挂钩子」,
292
+ // 而是走 killswitch 分支注入「硬门已被关闭(配置)」告警块并记 gate-log。
171
293
 
172
294
  const warn = (...a) => {
173
295
  if (cfg.log && ctx?.logger?.warn) ctx.logger.warn('[auto-recall]', ...a);
@@ -202,6 +324,9 @@ export function apply(ctx, config = {}) {
202
324
  // 是否真的注入了要看 injected / outcome,不看 why。
203
325
  query: explain.query ?? '',
204
326
  elapsedMs: explain.elapsedMs ?? null,
327
+ // B3 C5:注入块的实际字符/估算 token(字符车道口径,1 token ≈ 2 字符)。
328
+ injectedChars: explain.injectedChars ?? null,
329
+ injectedTokens: explain.injectedTokens ?? null,
205
330
  forced: explain.forced === true,
206
331
  why: explain.why ?? (explain.forced === true ? 'user-task' : null),
207
332
  trigger: explain.trigger ?? (explain.forced === true ? 'forced' : null),
@@ -278,10 +403,21 @@ export function apply(ctx, config = {}) {
278
403
  let cards = null;
279
404
  let cardsSignature = '';
280
405
  const getCards = () => {
406
+ laneCounters.getCardsCalls += 1;
281
407
  const signature = cardSignature();
282
408
  if (cards && signature === cardsSignature) return cards;
283
409
  cardsSignature = signature;
284
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
+ }
285
421
  try {
286
422
  cards = loadCards(cfg.memoryRoot, { dirs: cfg.dirs });
287
423
  } catch (error) {
@@ -313,6 +449,83 @@ export function apply(ctx, config = {}) {
313
449
  return createUserMessage;
314
450
  };
315
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
+
316
529
  // 1.8.8 M2:链路表 = <memoryRoot>/.longlive/recall/links.jsonl(种子 + 学习边)。
317
530
  // 按 mtime/size 缓存;读失败/坏文件一律 fail-open:本轮不直连,但绝不抛出。
318
531
  const linksCache = {};
@@ -358,12 +571,61 @@ export function apply(ctx, config = {}) {
358
571
  const decision = await next(); // waterfall:先让下游决定
359
572
  if (!decision || decision.kind === 'reject') return decision;
360
573
  if (Number(payload?.step) !== 1) return decision;
361
- if (cfg.skipSubagents && isSubagent(payload)) return decision;
362
574
 
363
575
  const key = sessionKey(payload?.agent);
364
576
  const st = stateFor(key);
365
577
  const messages = Array.isArray(decision.messages) ? decision.messages : [];
366
578
  const turn = Number.isFinite(Number(payload?.turn)) ? Number(payload.turn) : st.turn + 1;
579
+ // 2.0.0 硬门(M01/M04):step1 一律先过度单一入口(brain),四类 skip 与
580
+ // 命中/零命中/killswitch 都由它写 gate-log。新路径未绿之前旧链保留在下面
581
+ // (双路由):只有 brain 明确不接管(handled=false)才继续走旧逻辑。
582
+ // B3 C1/C6:每轮统一预算 2,000 字符;召回车道 ≤990 字符。硬门块(brain 的
583
+ // capBlock)也压到同一车道,避免旧 token 口径与字符口径混用。
584
+ const recallLaneChars = Math.max(200, Math.min(recallLaneCapChars(), Number(cfg.budget) || recallLaneCapChars()));
585
+ const hardgateCfg = { ...cfg, budget: recallLaneChars };
586
+ const hardgate = await runHardGate({ payload, cfg: hardgateCfg, decision, getCreateUserMessage, warn, startedAt: started });
587
+ if (hardgate?.handled) return hardgate.decision;
588
+ // 2.0.0 D22 防编(W4):扫上一轮 assistant 文本(decision.messages 里最后一条
589
+ // assistant),命中 requires-source 时生成 ≤50 字提醒块并写 hg.d22.fail;异常一律
590
+ // 吞掉(warn),绝不阻断本轮召回;硬门 handled 早返回路径不重复扫(R6 GAP)。
591
+ let claimGuard = null;
592
+ try {
593
+ const prevAssistant = [...messages].reverse().find((m) => (m?.kind === 'assistant' || m?.role === 'assistant') && !isRealUserMessage(m));
594
+ const prevText = prevAssistant ? (firstTextOf(prevAssistant) ?? '') : '';
595
+ if (prevText !== '') {
596
+ claimGuard = await applyClaimGuard({
597
+ memoryRoot: cfg.memoryRoot,
598
+ sessionId: payload?.agent?.session?.id ?? key,
599
+ turn: Math.max(0, turn - 1),
600
+ text: prevText,
601
+ warn,
602
+ });
603
+ }
604
+ } catch (error) {
605
+ warn('CLAIM_GUARD_FAILED', error?.code ?? error?.message ?? error);
606
+ }
607
+ // 把防编提醒块追加到最终 decision.messages;无提醒/无工厂/异常一律原样返回。
608
+ // composed=true 表示防编提示已并入 B3 九项预算块(同一注入消息),不再单独追加第二条。
609
+ const attachClaimGuard = async (value, { composed = false } = {}) => {
610
+ if (composed) return value;
611
+ if (!claimGuard || claimGuard.ok !== true || typeof claimGuard.injectText !== 'string' || claimGuard.injectText === '') return value;
612
+ try {
613
+ const claimFactory = await getCreateUserMessage();
614
+ if (!claimFactory) return value;
615
+ const claimMessage = assertInjectionMessage(claimFactory({
616
+ content: [{ type: 'text', text: `【防编】${claimGuard.injectText}` }],
617
+ source: injectionSource(),
618
+ }));
619
+ return { ...value, messages: mergeInjectionOrder(Array.isArray(value?.messages) ? value.messages : messages, claimMessage) };
620
+ } catch (error) {
621
+ warn('CLAIM_GUARD_INJECT_FAILED', error?.code ?? error?.message ?? error);
622
+ return value;
623
+ }
624
+ };
625
+ // brain 不接管时只产出一个 pending 描述;legacy 生产链继续跑(embedding/实体
626
+ // 扩展/证据包/audit/recall-log 的写入都保留),尾端再用 brain 渲染的新块替换
627
+ // 注入文本,并补写唯一一行 gate-log(recallId 三写:recall-log/evidence/gate-log)。
628
+ const hardgatePending = hardgate?.pending ?? null;
367
629
  // 1.8.8 M2:触发判据用「本轮最后一条真实用户消息」。取最后一条而不是字面
368
630
  // messages.at(-1),因为 identity-router 的开机卡会插在第一条真实 user 之后,
369
631
  // 首轮末尾可能是【开机卡】而不是用户的话;isRealUserMessage 已排除注入形态。
@@ -425,6 +687,65 @@ export function apply(ctx, config = {}) {
425
687
  warn('LINKS_FEEDBACK_FAILED', error?.code ?? error?.message ?? error);
426
688
  }
427
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
+
428
749
  // M2-C R1–R6: shared visibility block is injected on the FIRST turn only.
429
750
  const rawSharedNow = payload?.at ?? payload?.eventTime ?? payload?.now ?? null;
430
751
  const sharedNow = rawSharedNow === null || rawSharedNow === undefined
@@ -498,15 +819,31 @@ export function apply(ctx, config = {}) {
498
819
  options: { everyNTurns: cfg.everyNTurns },
499
820
  });
500
821
  }
822
+ // 2.0.0 硬门(M01):step1 的真实用户轮一律硬召回——不看 quiet/everyNTurns,
823
+ // 也不因纯应答退让;gate-log 的判定行由尾端 brain 补写(每轮恰好一行)。
824
+ if (hardgatePending) {
825
+ forced = true;
826
+ st.forcedTurn = turn;
827
+ gate = { recall: true, why: 'hard', everyNTurns: cfg.everyNTurns };
828
+ }
501
829
  gateInfo = gate;
830
+ // B3 C3:每个真实用户轮都必须注入。触发判据只决定「为什么召回」,不再允许
831
+ // gate.recall=false 写 gate-skip 后早返回——这里把任何非召回判决升为召回
832
+ // (why 保留原触发原因,面板仍能区分 quiet / every-n-turns / same-as-last)。
502
833
  if (!gate.recall) {
503
- notePrestepDegrade(key, turn, { kind: 'gate-skip', phase: 'recall', detail: gate.why });
504
- logRecall(key, turn, null, { gate, everyNTurns: cfg.everyNTurns, forced, query: lastUserText, elapsedMs: Date.now() - started });
505
- observe({ key, turn, why: gate.why, queryChars: queryText.length, tokens: 0, ms: Date.now() - started, forced });
506
- return attachShared(decision);
834
+ notePrestepDegrade(key, turn, { kind: 'gate-forced', phase: 'recall', detail: gate.why });
835
+ forced = true;
836
+ gate = {
837
+ ...gate,
838
+ recall: true,
839
+ why: typeof gate.why === 'string' && gate.why !== '' ? gate.why : 'forced',
840
+ everyNTurns: cfg.everyNTurns,
841
+ };
842
+ gateInfo = gate;
507
843
  }
508
844
 
509
- const loaded = getCards();
845
+ // 2.1.0:直连模式命中时不再整树扫卡(loaded=[]);0 命中/补漏模式照旧 getCards。
846
+ const loaded = directMode ? [] : getCards();
510
847
  // 1.8.2 D2: auto-cards are no longer read as recall candidates.
511
848
  const loadedForRecall = loaded;
512
849
  // 路径级排除:identity-router 本轮已经注入过的卡,不再注入第二遍。
@@ -520,7 +857,15 @@ export function apply(ctx, config = {}) {
520
857
  // 命中即注入(日志 source:'link')。隐私(整卡丢弃)/去重/预算/卡片存在性都在
521
858
  // selectLinkItems 内部处理;这里的任何异常都只让链路静默失效,不影响常规检索。
522
859
  let linkResolution = { items: [], matchedTerms: [], tokens: 0, stats: null };
523
- 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
524
869
  && Array.isArray(linksStore.edges) && linksStore.edges.length > 0) {
525
870
  try {
526
871
  linkResolution = selectLinkItems({
@@ -552,8 +897,9 @@ export function apply(ctx, config = {}) {
552
897
  // (模型缺失、onnxruntime-node 没装、tokenizer 坏)都静默退回纯关键词。
553
898
  let queryVector = null;
554
899
  let vectors = null;
555
- if (embedding.enabled) {
900
+ if (embedding.enabled && !directMode) {
556
901
  try {
902
+ laneCounters.embeddingEnsureCalls += 1;
557
903
  const ready = await embedding.ensure(loaded, { signature: cardsSignature });
558
904
  if (ready.ok) {
559
905
  queryVector = await embedding.embedQuery(queryText);
@@ -575,6 +921,10 @@ export function apply(ctx, config = {}) {
575
921
  }
576
922
 
577
923
  // B3: budget phase = ranking + budget trimming inside chooseRecall.
924
+ const chooseRecallStep = (input) => {
925
+ laneCounters.chooseRecallCalls += 1;
926
+ return chooseRecall(input);
927
+ };
578
928
  const budgetPhase = startPrestepPhase(key, turn, 'budget');
579
929
  const recallInput = {
580
930
  queryText: expandedQuery,
@@ -601,7 +951,11 @@ export function apply(ctx, config = {}) {
601
951
  },
602
952
  },
603
953
  };
604
- 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);
605
959
  budgetPhase.end();
606
960
  // 1.8.0 two-layer quota: at most 2 curated cards + 1 AutoCard per turn;
607
961
  // curated hits always render first (tier weight 1.12 only affects order
@@ -613,7 +967,7 @@ export function apply(ctx, config = {}) {
613
967
  const eventItems = result.items.filter(isAuto).slice(0, 1);
614
968
  // Curated floor: event cards may never squeeze curated cards out.
615
969
  if (curatedItems.length === 0 && loaded.length > 0) {
616
- const curatedOnly = chooseRecall({ ...recallInput, cards: loaded });
970
+ const curatedOnly = chooseRecallStep({ ...recallInput, cards: loaded });
617
971
  if (curatedOnly.items.length > 0) {
618
972
  result = curatedOnly;
619
973
  curatedItems = curatedOnly.items.slice().sort((a, b) => (b.score * 1.12) - (a.score * 1.12));
@@ -833,21 +1187,32 @@ export function apply(ctx, config = {}) {
833
1187
  });
834
1188
  } catch { /* recall auditing must never block injection */ }
835
1189
  // 1.8.8 M2 归档兜底:常规召回 + 链路命中合计为 0 时,才去历史会话归档里找线索。
836
- // 模块不存在 / 调用失败 → archiveUnavailable:true(静默回落,不算成功、不假报命中)。
1190
+ // 2.0.0 W3b(M32):冷档 fail-closed 门——显式 archiveRoot/archiveStatePath raw 透传,
1191
+ // offline/坏 state → throw E_HG_ARCHIVE_OFFLINE;manifest schema/index 不符 →
1192
+ // throw E_HG_ARCHIVE_MIGRATE_MISMATCH;READONLY/LOW_SPACE/WRONG_VOLUME 只降级不抛。
1193
+ // 抛错时:archiveUnavailable:true + notePrestepDegrade + 唯一一行 hg.d19.fail gate event,
1194
+ // 不注入卡正文(正文外只留一行 A6 告警给 logRecall/observe)。
837
1195
  const linkStat = {
838
1196
  enabled: cfg.links.enabled === true,
839
1197
  matchedTerms: Array.isArray(linkResolution.matchedTerms) ? linkResolution.matchedTerms : [],
840
1198
  injectedCount: linkItems.length,
841
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,
842
1203
  };
843
1204
  let archiveUnavailable = false;
844
1205
  let archiveBlock = null;
1206
+ let archiveCode = null;
845
1207
  if (result.items.length === 0) {
846
1208
  try {
847
1209
  const archive = await searchArchiveFallback({
848
1210
  memoryRoot: cfg.memoryRoot,
849
1211
  queryText: lastUserText || queryText,
850
1212
  limit: ARCHIVE_DEFAULTS.limit,
1213
+ archiveRoot: cfg.archiveRoot ?? '',
1214
+ archiveStatePath: cfg.archiveStatePath ?? '',
1215
+ failOpen: cfg.archiveFailOpen === true,
851
1216
  });
852
1217
  if (archive.ok === true) {
853
1218
  archiveBlock = renderArchiveBlock(archive.items, {
@@ -856,10 +1221,30 @@ export function apply(ctx, config = {}) {
856
1221
  });
857
1222
  } else {
858
1223
  archiveUnavailable = true;
1224
+ archiveCode = archive.code ?? null;
859
1225
  }
860
1226
  } catch (error) {
861
1227
  archiveUnavailable = true;
862
- warn('ARCHIVE_FALLBACK_FAILED', error?.code ?? error?.message ?? error);
1228
+ archiveCode = typeof error?.code === 'string' && error.code !== '' ? error.code : 'E_HG_ARCHIVE_OFFLINE';
1229
+ notePrestepDegrade(key, turn, {
1230
+ kind: 'archive-unavailable',
1231
+ phase: 'recall',
1232
+ detail: `${archiveCode}:${error?.reason ?? ''}`,
1233
+ });
1234
+ try {
1235
+ appendGateLog(cfg.memoryRoot, {
1236
+ sessionId: key,
1237
+ turn,
1238
+ gate: 'hg.d19.fail',
1239
+ decision: 'fail',
1240
+ reason: archiveCode,
1241
+ evidence: [String(error?.reason ?? ''), String(error?.manifestSha ?? '')],
1242
+ code: archiveCode,
1243
+ });
1244
+ } catch (gateError) {
1245
+ warn('ARCHIVE_GATE_EVENT_FAILED', gateError?.code ?? gateError?.message ?? gateError);
1246
+ }
1247
+ warn('ARCHIVE_UNAVAILABLE', `${archiveCode}${error?.reason ? `:${error.reason}` : ''}`);
863
1248
  }
864
1249
  }
865
1250
  const archiveItems = archiveBlock && archiveBlock.items.length > 0 ? archiveBlock.items : [];
@@ -867,6 +1252,48 @@ export function apply(ctx, config = {}) {
867
1252
  notePrestepDegrade(key, turn, { kind: 'zero-hit', phase: 'recall', detail: `eligible=${result.hits.eligible}` });
868
1253
  st.lastQuery = queryText;
869
1254
  st.compacted = false;
1255
+ // 2.0.0 硬门零命中:先渲染零命中兜底块(recallId 头 + 记忆里没有命中卡 +
1256
+ // scanned/dropped_by/zero-hit=1)。B3 C6 让它也走 990 字车道,度量同时进
1257
+ // recall-log(C5)与 gate-log(C4)。
1258
+ let zeroRendered = null;
1259
+ let zeroLane = null;
1260
+ let zeroProcedures = 0;
1261
+ if (hardgatePending) {
1262
+ let procedures = [];
1263
+ try {
1264
+ procedures = selectProcedures(cfg.memoryRoot, lastUserText || queryText, 2);
1265
+ } catch (error) {
1266
+ warn('HARDGATE_PROCEDURES_FAILED', error?.code ?? error?.message ?? error);
1267
+ }
1268
+ zeroProcedures = procedures.length;
1269
+ zeroRendered = renderPendingBlock({
1270
+ pending: hardgatePending,
1271
+ items: [],
1272
+ procedures,
1273
+ scanned: result.hits.eligible,
1274
+ droppedBy: {
1275
+ budget: result.hits.droppedByBudget,
1276
+ dedupe: result.hits.droppedByDedupe,
1277
+ seen: result.hits.droppedBySeen,
1278
+ localOnly: result.hits.droppedLocalOnly,
1279
+ privacy: result.hits.droppedByPrivacy,
1280
+ },
1281
+ });
1282
+ zeroLane = applyRecallLaneBudget(zeroRendered.block, { laneChars: recallLaneChars });
1283
+ }
1284
+ // B3 九项预算接线(P1):兜底块(+ 防编提示)合成 ≤2,000 字符预算块;990 字召回
1285
+ // 车道之外的车道这里如实带 0,逐车道字符账进 gate-log evidence。不注入时两者都为 null。
1286
+ const zeroBudget = zeroLane === null ? null : composeInjectionTurnBudget({
1287
+ recallText: zeroLane.text,
1288
+ claimGuardText: claimGuard?.ok === true ? claimGuard.injectText : '',
1289
+ });
1290
+ const zeroMetrics = zeroLane === null ? null : {
1291
+ ...buildRecallLaneMetrics(zeroLane, Date.now() - started),
1292
+ ...(zeroBudget === null ? {} : {
1293
+ injectedChars: zeroBudget.usedChars,
1294
+ injectedTokens: estimateTurnTokens(zeroBudget.usedChars),
1295
+ }),
1296
+ };
870
1297
  logRecall(key, turn, result, {
871
1298
  gate,
872
1299
  everyNTurns: cfg.everyNTurns,
@@ -876,13 +1303,16 @@ export function apply(ctx, config = {}) {
876
1303
  elapsedMs: Date.now() - started,
877
1304
  link: linkStat,
878
1305
  archiveUnavailable,
1306
+ archiveCode,
1307
+ injectedChars: zeroMetrics === null ? 0 : zeroMetrics.injectedChars,
1308
+ injectedTokens: zeroMetrics === null ? 0 : zeroMetrics.injectedTokens,
879
1309
  });
880
1310
  observe({
881
1311
  key, turn, why: gate.why, queryChars: queryText.length,
882
- eligible: result.hits.eligible, injected: [], tokens: 0, ms: Date.now() - started,
1312
+ eligible: result.hits.eligible, injected: [], tokens: zeroMetrics === null ? 0 : zeroMetrics.injectedTokens, ms: Date.now() - started,
883
1313
  forced,
884
1314
  link: { matchedTerms: linkStat.matchedTerms.length, injected: 0, tokens: 0 },
885
- archive: { unavailable: archiveUnavailable, injected: 0 },
1315
+ archive: { unavailable: archiveUnavailable, injected: 0, code: archiveCode },
886
1316
  dropped: {
887
1317
  budget: result.hits.droppedByBudget,
888
1318
  dedupe: result.hits.droppedByDedupe,
@@ -891,7 +1321,25 @@ export function apply(ctx, config = {}) {
891
1321
  privacy: result.hits.droppedByPrivacy,
892
1322
  },
893
1323
  });
894
- return attachShared(decision); // 无命中:什么都不注入(共享可见块仍可注入)
1324
+ if (hardgatePending && zeroRendered !== null && zeroLane !== null) {
1325
+ const zeroFactory = await getCreateUserMessage();
1326
+ const finished = finishPendingInjection({
1327
+ pending: hardgatePending,
1328
+ decision,
1329
+ messages: sharedMessage === null ? messages : mergeInjectionOrder(messages, sharedMessage),
1330
+ block: zeroBudget === null ? zeroLane.text : zeroBudget.text,
1331
+ hit: zeroRendered.hit,
1332
+ factory: zeroFactory,
1333
+ items: 0,
1334
+ procedures: zeroProcedures,
1335
+ scanned: result.hits.eligible,
1336
+ extra: zeroBudget === null ? [] : [zeroBudget.evidence],
1337
+ metrics: zeroMetrics,
1338
+ warn,
1339
+ });
1340
+ return attachClaimGuard(finished.decision, { composed: zeroBudget !== null && zeroBudget.claimGuardFolded });
1341
+ }
1342
+ return attachClaimGuard(attachShared(decision)); // 无命中:旧链什么都不注入(共享可见块仍可注入)
895
1343
  }
896
1344
 
897
1345
  // B3: inject phase = render + message factory + merge into decision.messages.
@@ -899,15 +1347,41 @@ export function apply(ctx, config = {}) {
899
1347
  const fromArchive = archiveItems.length > 0;
900
1348
  const logItems = fromArchive ? archiveToInjectedItems(archiveItems) : result.items;
901
1349
  let finalText = fromArchive ? archiveBlock.text : renderInjection(result, { privacyScan });
902
- // 硬顶预算:逐条从尾部裁到 ≤ budget(归档块自带 ≤800 tokens 上限,不再二次裁)。
903
- if (!fromArchive) {
904
- let trimResult = result;
905
- while (estimateTokens(finalText) > cfg.budget && trimResult.items.length > 1) {
906
- trimResult = { ...trimResult, items: trimResult.items.slice(0, -1) };
907
- finalText = renderInjection(trimResult, { privacyScan });
1350
+ // B3 C6:召回块 ≤990 字符(头 60 + 卡区 750 + 程序卡 120 + 当前线 60)。
1351
+ // 旧的 token 口径逐条裁剪删除——最终块的字符车道是唯一裁剪依据(下方统一应用),
1352
+ // 超限从尾裁且保留头部/防编/告警/余量;归档块同样受该车道约束。
1353
+ // 2.0.0 硬门:legacy 生产链据实选出候选(embedding/实体/证据包/audit 均已
1354
+ // 照常写入)后,注入文本改为 brain 的硬门块——recallId 头/卡列表/程序卡/
1355
+ // 当前线都在块里,capBlock 保证 ≤ budget。
1356
+ let hardgateHit = null;
1357
+ let hardgateProcedures = 0;
1358
+ if (hardgatePending && !fromArchive) {
1359
+ let procedures = [];
1360
+ try {
1361
+ procedures = selectProcedures(cfg.memoryRoot, lastUserText || queryText, 2);
1362
+ } catch (error) {
1363
+ warn('HARDGATE_PROCEDURES_FAILED', error?.code ?? error?.message ?? error);
908
1364
  }
909
- if (trimResult !== result) result = trimResult;
1365
+ const rendered = renderPendingBlock({ pending: hardgatePending, items: result.items, procedures });
1366
+ finalText = rendered.block;
1367
+ hardgateHit = rendered.hit;
1368
+ hardgateProcedures = procedures.length;
910
1369
  }
1370
+ // B3 C6/C4:最终块(硬门块或 legacy 块)统一过 990 字车道并产出注入度量;
1371
+ // 该度量写进 recall-log(injectedChars/injectedTokens)与 gate-log(B1/C1)。
1372
+ const recallLane = applyRecallLaneBudget(finalText, { laneChars: recallLaneChars });
1373
+ // B3 九项预算接线(P1):召回块(≤990)+ 防编提示合成 ≤2,000 字符预算块;
1374
+ // 9 条车道逐条字符账(含如实为 0 的车道)进 gate-log evidence,budget 总量进度量。
1375
+ const turnBudget = composeInjectionTurnBudget({
1376
+ recallText: recallLane.text,
1377
+ claimGuardText: claimGuard?.ok === true ? claimGuard.injectText : '',
1378
+ });
1379
+ finalText = turnBudget.text;
1380
+ const laneMetrics = {
1381
+ ...buildRecallLaneMetrics(recallLane, Date.now() - started),
1382
+ injectedChars: turnBudget.usedChars,
1383
+ injectedTokens: estimateTurnTokens(turnBudget.usedChars),
1384
+ };
911
1385
  const factory = await getCreateUserMessage();
912
1386
  if (!factory) {
913
1387
  injectPhase.end();
@@ -923,7 +1397,21 @@ export function apply(ctx, config = {}) {
923
1397
  elapsedMs: Date.now() - started,
924
1398
  link: linkStat,
925
1399
  archiveUnavailable,
1400
+ archiveCode,
1401
+ injectedChars: 0,
1402
+ injectedTokens: 0,
926
1403
  });
1404
+ if (hardgatePending) {
1405
+ // B3 P1 接线:失败判决/原因码统一由 resolveRecallInjectionDecision 给(noChannel → fail)。
1406
+ const noChannelVerdict = resolveRecallInjectionDecision({ noChannel: true });
1407
+ recordPendingFailure({
1408
+ pending: hardgatePending,
1409
+ reason: noChannelVerdict.reason,
1410
+ evidence: ['factoryUnavailable', turnBudget.evidence],
1411
+ metrics: { injectedChars: 0, injectedTokens: 0, elapsedMs: Date.now() - started },
1412
+ warn,
1413
+ });
1414
+ }
927
1415
  return decision;
928
1416
  }
929
1417
 
@@ -942,7 +1430,7 @@ export function apply(ctx, config = {}) {
942
1430
  turn,
943
1431
  messageText: lastUserText,
944
1432
  injected: logItems,
945
- cards: loaded,
1433
+ cards: directMode ? fastpathCards : loaded,
946
1434
  edges: linksStore?.edges ?? [],
947
1435
  now: Date.now(),
948
1436
  config: cfg.links,
@@ -968,13 +1456,15 @@ export function apply(ctx, config = {}) {
968
1456
  elapsedMs: Date.now() - started,
969
1457
  link: linkStat,
970
1458
  archiveUnavailable,
1459
+ injectedChars: laneMetrics.injectedChars,
1460
+ injectedTokens: laneMetrics.injectedTokens,
971
1461
  });
972
1462
  observe({
973
1463
  key, turn, why: gate.why, queryChars: queryText.length, eligible: result.hits.eligible,
974
1464
  injected: logItems.map((i) => i.path), tokens: logResult.tokens, budget: cfg.budget,
975
1465
  ms: Date.now() - started, forced,
976
1466
  link: { matchedTerms: linkStat.matchedTerms.length, injected: linkItems.length, tokens: linkTokens },
977
- archive: { unavailable: archiveUnavailable, injected: archiveItems.length },
1467
+ archive: { unavailable: archiveUnavailable, injected: archiveItems.length, code: archiveCode },
978
1468
  dropped: {
979
1469
  budget: result.hits.droppedByBudget,
980
1470
  dedupe: result.hits.droppedByDedupe,
@@ -984,7 +1474,22 @@ export function apply(ctx, config = {}) {
984
1474
  },
985
1475
  });
986
1476
 
987
- return { ...decision, messages: mergeInjectionOrder(sharedMessage === null ? messages : mergeInjectionOrder(messages, sharedMessage), message) };
1477
+ if (hardgatePending) {
1478
+ recordPendingResult({
1479
+ pending: hardgatePending,
1480
+ hit: fromArchive ? true : hardgateHit === true,
1481
+ items: fromArchive ? archiveItems.length : result.items.length,
1482
+ procedures: fromArchive ? 0 : hardgateProcedures,
1483
+ scanned: result.hits.eligible,
1484
+ extra: [turnBudget.evidence],
1485
+ metrics: laneMetrics,
1486
+ warn,
1487
+ });
1488
+ }
1489
+ return attachClaimGuard(
1490
+ { ...decision, messages: mergeInjectionOrder(sharedMessage === null ? messages : mergeInjectionOrder(messages, sharedMessage), message) },
1491
+ { composed: turnBudget.claimGuardFolded }, // 防编提示已并入九项预算块 → 不再追加第二条
1492
+ );
988
1493
  } catch (error) {
989
1494
  if (!st.warned) {
990
1495
  st.warned = true;
@@ -999,13 +1504,135 @@ export function apply(ctx, config = {}) {
999
1504
  forced: gateInfo?.why === 'forced',
1000
1505
  query: lastUserText,
1001
1506
  elapsedMs: Date.now() - started,
1507
+ injectedChars: 0,
1508
+ injectedTokens: 0,
1002
1509
  });
1003
- return attachShared(decision); // 插件失败不许拖垮本轮
1510
+ if (hardgatePending) {
1511
+ const failedVerdict = resolveRecallInjectionDecision({ failed: true });
1512
+ recordPendingFailure({
1513
+ pending: hardgatePending,
1514
+ reason: failedVerdict.reason,
1515
+ evidence: [String(error?.code ?? error?.message ?? error)],
1516
+ metrics: { injectedChars: 0, injectedTokens: 0, elapsedMs: Date.now() - started },
1517
+ warn,
1518
+ });
1519
+ }
1520
+ return attachClaimGuard(attachShared(decision)); // 插件失败不许拖垮本轮(防编提醒仍可独立注入)
1004
1521
  } finally {
1005
1522
  try { recallPhase.end(); } catch { /* timing only */ }
1006
1523
  }
1007
1524
  }, { prepend: false });
1008
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
+
1009
1636
  // 首条用户消息 + 轮数 + 压缩标记
1010
1637
  ctx.on('session/event', (session, event) => {
1011
1638
  try {
@@ -1023,6 +1650,13 @@ export function apply(ctx, config = {}) {
1023
1650
  if (event?.type === 'turn/end') {
1024
1651
  const t = Number(event?.data?.turn);
1025
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
+ }
1026
1660
  }
1027
1661
  if (/compaction/i.test(String(event?.type ?? ''))) st.compacted = true; // 上线前先核事件名(WIRING §8)
1028
1662
  } catch (error) {