@jjh32456/longlive 1.8.12 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +232 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +42 -11
  5. package/SPEC.md +3 -3
  6. package/build-info.json +231 -121
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ARCHITECTURE.md +1 -1
  9. package/docs/AUTO-RECALL.md +1 -1
  10. package/docs/CONFIG.md +41 -9
  11. package/docs/FAQ.md +7 -7
  12. package/docs/FEATURES.md +6 -6
  13. package/docs/OPERATIONS.md +1 -1
  14. package/docs/PANEL-INTEGRATION.md +1 -1
  15. package/docs/PRIVACY.md +5 -5
  16. package/docs/QUICKSTART.md +3 -3
  17. package/docs/README.en.md +4 -2
  18. package/docs/TROUBLESHOOTING.md +4 -4
  19. package/package.json +6 -3
  20. package/runbook.md +3 -3
  21. package/scripts/migrate-200.mjs +8 -0
  22. package/scripts/migrate-lifecycle.mjs +2 -2
  23. package/src/answer/claim-guard.mjs +234 -0
  24. package/src/backup.js +165 -1
  25. package/src/config.js +18 -7
  26. package/src/features.js +128 -5
  27. package/src/handoff/index.js +133 -0
  28. package/src/handoff/model.js +48 -0
  29. package/src/identity/handover.js +203 -15
  30. package/src/identity/inject-position.js +3 -1
  31. package/src/memory/a1-migration.js +72 -6
  32. package/src/memory/archive-cold-state.mjs +794 -0
  33. package/src/memory/archive-staging.mjs +305 -0
  34. package/src/memory/archive.mjs +415 -0
  35. package/src/memory/capture-host.js +71 -2
  36. package/src/memory/capture.js +45 -6
  37. package/src/memory/catchup.mjs +534 -0
  38. package/src/memory/conclusion-distill.js +51 -2
  39. package/src/memory/conclusion-drafts.js +7 -3
  40. package/src/memory/conflicts.js +915 -2
  41. package/src/memory/consolidate.js +20 -1
  42. package/src/memory/forget-v2.js +272 -2
  43. package/src/memory/forget.js +20 -1
  44. package/src/memory/frames-activation.js +3 -1
  45. package/src/memory/fts-query.js +2 -2
  46. package/src/memory/index.js +80 -7
  47. package/src/memory/land.mjs +743 -0
  48. package/src/memory/lifecycle.js +128 -0
  49. package/src/memory/maintenance.js +386 -22
  50. package/src/memory/memory-health.mjs +607 -0
  51. package/src/memory/migrate-200.js +1681 -0
  52. package/src/memory/migrate-lifecycle.js +3 -3
  53. package/src/memory/procedure-candidate.mjs +377 -0
  54. package/src/memory/procedure.js +20 -1
  55. package/src/memory/prospective-memory.mjs +362 -0
  56. package/src/memory/recall-feedback.mjs +406 -0
  57. package/src/memory/recall-v2.js +13 -1
  58. package/src/memory/recall.js +102 -1
  59. package/src/memory/reinforce.js +138 -2
  60. package/src/memory/retention.js +34 -0
  61. package/src/memory/turn-budget.mjs +290 -0
  62. package/src/memory/wake-bridge.mjs +2999 -0
  63. package/src/memory/working-frame.js +271 -8
  64. package/src/metrics/classify.mjs +3 -1
  65. package/src/recall/archive-config.mjs +130 -0
  66. package/src/recall/archive-fallback.mjs +174 -19
  67. package/src/recall/archive-search.mjs +3 -0
  68. package/src/recall/archive-state.mjs +588 -0
  69. package/src/recall/brain.mjs +501 -0
  70. package/src/recall/current-line.mjs +110 -0
  71. package/src/recall/edges.js +21 -2
  72. package/src/recall/explain.mjs +10 -0
  73. package/src/recall/gate-log.mjs +280 -0
  74. package/src/recall/gate-metrics.mjs +191 -0
  75. package/src/recall/index.js +322 -21
  76. package/src/recall/inject-order.mjs +3 -1
  77. package/src/recall/recall-core.mjs +47 -2
  78. package/src/recall/turn-budget-inject.mjs +154 -0
  79. package/src/retention/cold-gate.mjs +146 -0
  80. package/src/retention/config.js +58 -1
  81. package/src/retention/index.js +193 -35
  82. package/src/router/design-headings.json +10 -10
  83. package/src/tools.js +122 -6
@@ -32,6 +32,24 @@ import { buildEvidencePackage, writeEvidencePackage } from '../memory/evidence.j
32
32
  import { fastAnswerFromRecallItems } from '../memory/recall-v2.js';
33
33
  import { buildQueryText, chooseRecall, decideTrigger, 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,6 +79,11 @@ import {
61
79
  isRealUserMessage,
62
80
  mergeInjectionOrder,
63
81
  } from './inject-order.mjs';
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';
64
87
  import { appendFileSync, mkdirSync, readdirSync, statSync } from 'node:fs';
65
88
  import { dirname, join } from 'node:path';
66
89
  import { dshHome } from '../home.js';
@@ -165,9 +188,60 @@ function firstTextOf(data) {
165
188
  return typeof data?.text === 'string' ? data.text : null;
166
189
  }
167
190
 
191
+ /**
192
+ * B3 九项预算接线(P1):把本轮**实际要注入的文本**按 9 条车道合成一条 ≤2,000 字符的预算块。
193
+ *
194
+ * 数据源口径(只填真实文本,不伪造车道内容):
195
+ * - recall ← 本轮召回块(applyRecallLaneBudget 之后,≤990)
196
+ * - antiFabrication ← 防编提示(claim-guard 命中才非空;≤47 时并入本块承载,过长仍走独立消息)
197
+ * - working/prospective/review/conflict/activity/alert ← 由各自产生者提供(D12/D15/D17… 交付前如实为 0)
198
+ * - margin ← 预算保留(不塞文本;composeTurnBlocks 不参与拼装)
199
+ * 返回的 lanes 是 9 车道逐条字符账(0 也列出),evidence 进 gate-log evidence 供独立复算。
200
+ */
201
+ function composeInjectionTurnBudget({ recallText, claimGuardText = '', laneTexts = {} } = {}) {
202
+ const claim = typeof claimGuardText === 'string' ? claimGuardText : '';
203
+ // 车道 cap 是 50;【防编】前缀占 3 字符,只有 ≤47 的提示才能整条并入而不被裁剪。
204
+ const antiFabricationText = claim !== '' && charLength(claim) <= 47 ? `【防编】${claim}` : '';
205
+ const blocks = [];
206
+ if (typeof recallText === 'string' && recallText !== '') blocks.push({ lane: 'recall', text: recallText });
207
+ if (antiFabricationText !== '') blocks.push({ lane: 'antiFabrication', text: antiFabricationText });
208
+ for (const lane of TURN_BUDGET_LANE_ORDER) {
209
+ const text = laneTexts?.[lane];
210
+ const measured = lane !== 'recall' && lane !== 'antiFabrication' && lane !== 'margin'
211
+ && typeof text === 'string' && text !== '';
212
+ if (measured) blocks.push({ lane, text });
213
+ }
214
+ const composed = composeTurnBlocks(blocks);
215
+ // C2:整块 ≤2,000 字符;超了显式抛 E_HG_TURN_BUDGET_OVERFLOW,不静默吞掉整块。
216
+ assertTurnBudgetMessage(composed);
217
+ const lanes = {};
218
+ for (const lane of TURN_BUDGET_LANE_ORDER) {
219
+ const part = composed.parts.find((entry) => entry.lane === lane);
220
+ lanes[lane] = {
221
+ chars: part?.chars ?? 0,
222
+ cap: getTurnBudgetCap(lane),
223
+ rendered: part !== undefined,
224
+ };
225
+ }
226
+ const evidence = `budget=${composed.usedChars}/${composed.totalChars}`
227
+ + ` lanes=${TURN_BUDGET_LANE_ORDER.map((lane) => `${lane}:${lanes[lane].chars}`).join(',')}`;
228
+ return {
229
+ schema: 'turn-budget/v1',
230
+ text: composed.text,
231
+ lanes,
232
+ composed,
233
+ claimGuardFolded: antiFabricationText !== '',
234
+ usedChars: composed.usedChars,
235
+ totalChars: composed.totalChars,
236
+ trimmedLanes: composed.trimmedLanes,
237
+ evidence,
238
+ };
239
+ }
240
+
168
241
  export function apply(ctx, config = {}) {
169
242
  const cfg = normalize(config);
170
- if (cfg.autoRecall === false) return; // ← 总开关:autoRecall:false 时不注册任何钩子
243
+ // 2.0.0 硬门(M01/M04):handler 恒注册;autoRecall:false 不再「不挂钩子」,
244
+ // 而是走 killswitch 分支注入「硬门已被关闭(配置)」告警块并记 gate-log。
171
245
 
172
246
  const warn = (...a) => {
173
247
  if (cfg.log && ctx?.logger?.warn) ctx.logger.warn('[auto-recall]', ...a);
@@ -202,6 +276,9 @@ export function apply(ctx, config = {}) {
202
276
  // 是否真的注入了要看 injected / outcome,不看 why。
203
277
  query: explain.query ?? '',
204
278
  elapsedMs: explain.elapsedMs ?? null,
279
+ // B3 C5:注入块的实际字符/估算 token(字符车道口径,1 token ≈ 2 字符)。
280
+ injectedChars: explain.injectedChars ?? null,
281
+ injectedTokens: explain.injectedTokens ?? null,
205
282
  forced: explain.forced === true,
206
283
  why: explain.why ?? (explain.forced === true ? 'user-task' : null),
207
284
  trigger: explain.trigger ?? (explain.forced === true ? 'forced' : null),
@@ -358,12 +435,61 @@ export function apply(ctx, config = {}) {
358
435
  const decision = await next(); // waterfall:先让下游决定
359
436
  if (!decision || decision.kind === 'reject') return decision;
360
437
  if (Number(payload?.step) !== 1) return decision;
361
- if (cfg.skipSubagents && isSubagent(payload)) return decision;
362
438
 
363
439
  const key = sessionKey(payload?.agent);
364
440
  const st = stateFor(key);
365
441
  const messages = Array.isArray(decision.messages) ? decision.messages : [];
366
442
  const turn = Number.isFinite(Number(payload?.turn)) ? Number(payload.turn) : st.turn + 1;
443
+ // 2.0.0 硬门(M01/M04):step1 一律先过度单一入口(brain),四类 skip 与
444
+ // 命中/零命中/killswitch 都由它写 gate-log。新路径未绿之前旧链保留在下面
445
+ // (双路由):只有 brain 明确不接管(handled=false)才继续走旧逻辑。
446
+ // B3 C1/C6:每轮统一预算 2,000 字符;召回车道 ≤990 字符。硬门块(brain 的
447
+ // capBlock)也压到同一车道,避免旧 token 口径与字符口径混用。
448
+ const recallLaneChars = Math.max(200, Math.min(recallLaneCapChars(), Number(cfg.budget) || recallLaneCapChars()));
449
+ const hardgateCfg = { ...cfg, budget: recallLaneChars };
450
+ const hardgate = await runHardGate({ payload, cfg: hardgateCfg, decision, getCreateUserMessage, warn, startedAt: started });
451
+ if (hardgate?.handled) return hardgate.decision;
452
+ // 2.0.0 D22 防编(W4):扫上一轮 assistant 文本(decision.messages 里最后一条
453
+ // assistant),命中 requires-source 时生成 ≤50 字提醒块并写 hg.d22.fail;异常一律
454
+ // 吞掉(warn),绝不阻断本轮召回;硬门 handled 早返回路径不重复扫(R6 GAP)。
455
+ let claimGuard = null;
456
+ try {
457
+ const prevAssistant = [...messages].reverse().find((m) => (m?.kind === 'assistant' || m?.role === 'assistant') && !isRealUserMessage(m));
458
+ const prevText = prevAssistant ? (firstTextOf(prevAssistant) ?? '') : '';
459
+ if (prevText !== '') {
460
+ claimGuard = await applyClaimGuard({
461
+ memoryRoot: cfg.memoryRoot,
462
+ sessionId: payload?.agent?.session?.id ?? key,
463
+ turn: Math.max(0, turn - 1),
464
+ text: prevText,
465
+ warn,
466
+ });
467
+ }
468
+ } catch (error) {
469
+ warn('CLAIM_GUARD_FAILED', error?.code ?? error?.message ?? error);
470
+ }
471
+ // 把防编提醒块追加到最终 decision.messages;无提醒/无工厂/异常一律原样返回。
472
+ // composed=true 表示防编提示已并入 B3 九项预算块(同一注入消息),不再单独追加第二条。
473
+ const attachClaimGuard = async (value, { composed = false } = {}) => {
474
+ if (composed) return value;
475
+ if (!claimGuard || claimGuard.ok !== true || typeof claimGuard.injectText !== 'string' || claimGuard.injectText === '') return value;
476
+ try {
477
+ const claimFactory = await getCreateUserMessage();
478
+ if (!claimFactory) return value;
479
+ const claimMessage = assertInjectionMessage(claimFactory({
480
+ content: [{ type: 'text', text: `【防编】${claimGuard.injectText}` }],
481
+ source: injectionSource(),
482
+ }));
483
+ return { ...value, messages: mergeInjectionOrder(Array.isArray(value?.messages) ? value.messages : messages, claimMessage) };
484
+ } catch (error) {
485
+ warn('CLAIM_GUARD_INJECT_FAILED', error?.code ?? error?.message ?? error);
486
+ return value;
487
+ }
488
+ };
489
+ // brain 不接管时只产出一个 pending 描述;legacy 生产链继续跑(embedding/实体
490
+ // 扩展/证据包/audit/recall-log 的写入都保留),尾端再用 brain 渲染的新块替换
491
+ // 注入文本,并补写唯一一行 gate-log(recallId 三写:recall-log/evidence/gate-log)。
492
+ const hardgatePending = hardgate?.pending ?? null;
367
493
  // 1.8.8 M2:触发判据用「本轮最后一条真实用户消息」。取最后一条而不是字面
368
494
  // messages.at(-1),因为 identity-router 的开机卡会插在第一条真实 user 之后,
369
495
  // 首轮末尾可能是【开机卡】而不是用户的话;isRealUserMessage 已排除注入形态。
@@ -498,12 +624,27 @@ export function apply(ctx, config = {}) {
498
624
  options: { everyNTurns: cfg.everyNTurns },
499
625
  });
500
626
  }
627
+ // 2.0.0 硬门(M01):step1 的真实用户轮一律硬召回——不看 quiet/everyNTurns,
628
+ // 也不因纯应答退让;gate-log 的判定行由尾端 brain 补写(每轮恰好一行)。
629
+ if (hardgatePending) {
630
+ forced = true;
631
+ st.forcedTurn = turn;
632
+ gate = { recall: true, why: 'hard', everyNTurns: cfg.everyNTurns };
633
+ }
501
634
  gateInfo = gate;
635
+ // B3 C3:每个真实用户轮都必须注入。触发判据只决定「为什么召回」,不再允许
636
+ // gate.recall=false 写 gate-skip 后早返回——这里把任何非召回判决升为召回
637
+ // (why 保留原触发原因,面板仍能区分 quiet / every-n-turns / same-as-last)。
502
638
  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);
639
+ notePrestepDegrade(key, turn, { kind: 'gate-forced', phase: 'recall', detail: gate.why });
640
+ forced = true;
641
+ gate = {
642
+ ...gate,
643
+ recall: true,
644
+ why: typeof gate.why === 'string' && gate.why !== '' ? gate.why : 'forced',
645
+ everyNTurns: cfg.everyNTurns,
646
+ };
647
+ gateInfo = gate;
507
648
  }
508
649
 
509
650
  const loaded = getCards();
@@ -833,7 +974,11 @@ export function apply(ctx, config = {}) {
833
974
  });
834
975
  } catch { /* recall auditing must never block injection */ }
835
976
  // 1.8.8 M2 归档兜底:常规召回 + 链路命中合计为 0 时,才去历史会话归档里找线索。
836
- // 模块不存在 / 调用失败 → archiveUnavailable:true(静默回落,不算成功、不假报命中)。
977
+ // 2.0.0 W3b(M32):冷档 fail-closed 门——显式 archiveRoot/archiveStatePath raw 透传,
978
+ // offline/坏 state → throw E_HG_ARCHIVE_OFFLINE;manifest schema/index 不符 →
979
+ // throw E_HG_ARCHIVE_MIGRATE_MISMATCH;READONLY/LOW_SPACE/WRONG_VOLUME 只降级不抛。
980
+ // 抛错时:archiveUnavailable:true + notePrestepDegrade + 唯一一行 hg.d19.fail gate event,
981
+ // 不注入卡正文(正文外只留一行 A6 告警给 logRecall/observe)。
837
982
  const linkStat = {
838
983
  enabled: cfg.links.enabled === true,
839
984
  matchedTerms: Array.isArray(linkResolution.matchedTerms) ? linkResolution.matchedTerms : [],
@@ -842,12 +987,16 @@ export function apply(ctx, config = {}) {
842
987
  };
843
988
  let archiveUnavailable = false;
844
989
  let archiveBlock = null;
990
+ let archiveCode = null;
845
991
  if (result.items.length === 0) {
846
992
  try {
847
993
  const archive = await searchArchiveFallback({
848
994
  memoryRoot: cfg.memoryRoot,
849
995
  queryText: lastUserText || queryText,
850
996
  limit: ARCHIVE_DEFAULTS.limit,
997
+ archiveRoot: cfg.archiveRoot ?? '',
998
+ archiveStatePath: cfg.archiveStatePath ?? '',
999
+ failOpen: cfg.archiveFailOpen === true,
851
1000
  });
852
1001
  if (archive.ok === true) {
853
1002
  archiveBlock = renderArchiveBlock(archive.items, {
@@ -856,10 +1005,30 @@ export function apply(ctx, config = {}) {
856
1005
  });
857
1006
  } else {
858
1007
  archiveUnavailable = true;
1008
+ archiveCode = archive.code ?? null;
859
1009
  }
860
1010
  } catch (error) {
861
1011
  archiveUnavailable = true;
862
- warn('ARCHIVE_FALLBACK_FAILED', error?.code ?? error?.message ?? error);
1012
+ archiveCode = typeof error?.code === 'string' && error.code !== '' ? error.code : 'E_HG_ARCHIVE_OFFLINE';
1013
+ notePrestepDegrade(key, turn, {
1014
+ kind: 'archive-unavailable',
1015
+ phase: 'recall',
1016
+ detail: `${archiveCode}:${error?.reason ?? ''}`,
1017
+ });
1018
+ try {
1019
+ appendGateLog(cfg.memoryRoot, {
1020
+ sessionId: key,
1021
+ turn,
1022
+ gate: 'hg.d19.fail',
1023
+ decision: 'fail',
1024
+ reason: archiveCode,
1025
+ evidence: [String(error?.reason ?? ''), String(error?.manifestSha ?? '')],
1026
+ code: archiveCode,
1027
+ });
1028
+ } catch (gateError) {
1029
+ warn('ARCHIVE_GATE_EVENT_FAILED', gateError?.code ?? gateError?.message ?? gateError);
1030
+ }
1031
+ warn('ARCHIVE_UNAVAILABLE', `${archiveCode}${error?.reason ? `:${error.reason}` : ''}`);
863
1032
  }
864
1033
  }
865
1034
  const archiveItems = archiveBlock && archiveBlock.items.length > 0 ? archiveBlock.items : [];
@@ -867,6 +1036,48 @@ export function apply(ctx, config = {}) {
867
1036
  notePrestepDegrade(key, turn, { kind: 'zero-hit', phase: 'recall', detail: `eligible=${result.hits.eligible}` });
868
1037
  st.lastQuery = queryText;
869
1038
  st.compacted = false;
1039
+ // 2.0.0 硬门零命中:先渲染零命中兜底块(recallId 头 + 记忆里没有命中卡 +
1040
+ // scanned/dropped_by/zero-hit=1)。B3 C6 让它也走 990 字车道,度量同时进
1041
+ // recall-log(C5)与 gate-log(C4)。
1042
+ let zeroRendered = null;
1043
+ let zeroLane = null;
1044
+ let zeroProcedures = 0;
1045
+ if (hardgatePending) {
1046
+ let procedures = [];
1047
+ try {
1048
+ procedures = selectProcedures(cfg.memoryRoot, lastUserText || queryText, 2);
1049
+ } catch (error) {
1050
+ warn('HARDGATE_PROCEDURES_FAILED', error?.code ?? error?.message ?? error);
1051
+ }
1052
+ zeroProcedures = procedures.length;
1053
+ zeroRendered = renderPendingBlock({
1054
+ pending: hardgatePending,
1055
+ items: [],
1056
+ procedures,
1057
+ scanned: result.hits.eligible,
1058
+ droppedBy: {
1059
+ budget: result.hits.droppedByBudget,
1060
+ dedupe: result.hits.droppedByDedupe,
1061
+ seen: result.hits.droppedBySeen,
1062
+ localOnly: result.hits.droppedLocalOnly,
1063
+ privacy: result.hits.droppedByPrivacy,
1064
+ },
1065
+ });
1066
+ zeroLane = applyRecallLaneBudget(zeroRendered.block, { laneChars: recallLaneChars });
1067
+ }
1068
+ // B3 九项预算接线(P1):兜底块(+ 防编提示)合成 ≤2,000 字符预算块;990 字召回
1069
+ // 车道之外的车道这里如实带 0,逐车道字符账进 gate-log evidence。不注入时两者都为 null。
1070
+ const zeroBudget = zeroLane === null ? null : composeInjectionTurnBudget({
1071
+ recallText: zeroLane.text,
1072
+ claimGuardText: claimGuard?.ok === true ? claimGuard.injectText : '',
1073
+ });
1074
+ const zeroMetrics = zeroLane === null ? null : {
1075
+ ...buildRecallLaneMetrics(zeroLane, Date.now() - started),
1076
+ ...(zeroBudget === null ? {} : {
1077
+ injectedChars: zeroBudget.usedChars,
1078
+ injectedTokens: estimateTurnTokens(zeroBudget.usedChars),
1079
+ }),
1080
+ };
870
1081
  logRecall(key, turn, result, {
871
1082
  gate,
872
1083
  everyNTurns: cfg.everyNTurns,
@@ -876,13 +1087,16 @@ export function apply(ctx, config = {}) {
876
1087
  elapsedMs: Date.now() - started,
877
1088
  link: linkStat,
878
1089
  archiveUnavailable,
1090
+ archiveCode,
1091
+ injectedChars: zeroMetrics === null ? 0 : zeroMetrics.injectedChars,
1092
+ injectedTokens: zeroMetrics === null ? 0 : zeroMetrics.injectedTokens,
879
1093
  });
880
1094
  observe({
881
1095
  key, turn, why: gate.why, queryChars: queryText.length,
882
- eligible: result.hits.eligible, injected: [], tokens: 0, ms: Date.now() - started,
1096
+ eligible: result.hits.eligible, injected: [], tokens: zeroMetrics === null ? 0 : zeroMetrics.injectedTokens, ms: Date.now() - started,
883
1097
  forced,
884
1098
  link: { matchedTerms: linkStat.matchedTerms.length, injected: 0, tokens: 0 },
885
- archive: { unavailable: archiveUnavailable, injected: 0 },
1099
+ archive: { unavailable: archiveUnavailable, injected: 0, code: archiveCode },
886
1100
  dropped: {
887
1101
  budget: result.hits.droppedByBudget,
888
1102
  dedupe: result.hits.droppedByDedupe,
@@ -891,7 +1105,25 @@ export function apply(ctx, config = {}) {
891
1105
  privacy: result.hits.droppedByPrivacy,
892
1106
  },
893
1107
  });
894
- return attachShared(decision); // 无命中:什么都不注入(共享可见块仍可注入)
1108
+ if (hardgatePending && zeroRendered !== null && zeroLane !== null) {
1109
+ const zeroFactory = await getCreateUserMessage();
1110
+ const finished = finishPendingInjection({
1111
+ pending: hardgatePending,
1112
+ decision,
1113
+ messages: sharedMessage === null ? messages : mergeInjectionOrder(messages, sharedMessage),
1114
+ block: zeroBudget === null ? zeroLane.text : zeroBudget.text,
1115
+ hit: zeroRendered.hit,
1116
+ factory: zeroFactory,
1117
+ items: 0,
1118
+ procedures: zeroProcedures,
1119
+ scanned: result.hits.eligible,
1120
+ extra: zeroBudget === null ? [] : [zeroBudget.evidence],
1121
+ metrics: zeroMetrics,
1122
+ warn,
1123
+ });
1124
+ return attachClaimGuard(finished.decision, { composed: zeroBudget !== null && zeroBudget.claimGuardFolded });
1125
+ }
1126
+ return attachClaimGuard(attachShared(decision)); // 无命中:旧链什么都不注入(共享可见块仍可注入)
895
1127
  }
896
1128
 
897
1129
  // B3: inject phase = render + message factory + merge into decision.messages.
@@ -899,15 +1131,41 @@ export function apply(ctx, config = {}) {
899
1131
  const fromArchive = archiveItems.length > 0;
900
1132
  const logItems = fromArchive ? archiveToInjectedItems(archiveItems) : result.items;
901
1133
  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 });
1134
+ // B3 C6:召回块 ≤990 字符(头 60 + 卡区 750 + 程序卡 120 + 当前线 60)。
1135
+ // 旧的 token 口径逐条裁剪删除——最终块的字符车道是唯一裁剪依据(下方统一应用),
1136
+ // 超限从尾裁且保留头部/防编/告警/余量;归档块同样受该车道约束。
1137
+ // 2.0.0 硬门:legacy 生产链据实选出候选(embedding/实体/证据包/audit 均已
1138
+ // 照常写入)后,注入文本改为 brain 的硬门块——recallId 头/卡列表/程序卡/
1139
+ // 当前线都在块里,capBlock 保证 ≤ budget。
1140
+ let hardgateHit = null;
1141
+ let hardgateProcedures = 0;
1142
+ if (hardgatePending && !fromArchive) {
1143
+ let procedures = [];
1144
+ try {
1145
+ procedures = selectProcedures(cfg.memoryRoot, lastUserText || queryText, 2);
1146
+ } catch (error) {
1147
+ warn('HARDGATE_PROCEDURES_FAILED', error?.code ?? error?.message ?? error);
908
1148
  }
909
- if (trimResult !== result) result = trimResult;
1149
+ const rendered = renderPendingBlock({ pending: hardgatePending, items: result.items, procedures });
1150
+ finalText = rendered.block;
1151
+ hardgateHit = rendered.hit;
1152
+ hardgateProcedures = procedures.length;
910
1153
  }
1154
+ // B3 C6/C4:最终块(硬门块或 legacy 块)统一过 990 字车道并产出注入度量;
1155
+ // 该度量写进 recall-log(injectedChars/injectedTokens)与 gate-log(B1/C1)。
1156
+ const recallLane = applyRecallLaneBudget(finalText, { laneChars: recallLaneChars });
1157
+ // B3 九项预算接线(P1):召回块(≤990)+ 防编提示合成 ≤2,000 字符预算块;
1158
+ // 9 条车道逐条字符账(含如实为 0 的车道)进 gate-log evidence,budget 总量进度量。
1159
+ const turnBudget = composeInjectionTurnBudget({
1160
+ recallText: recallLane.text,
1161
+ claimGuardText: claimGuard?.ok === true ? claimGuard.injectText : '',
1162
+ });
1163
+ finalText = turnBudget.text;
1164
+ const laneMetrics = {
1165
+ ...buildRecallLaneMetrics(recallLane, Date.now() - started),
1166
+ injectedChars: turnBudget.usedChars,
1167
+ injectedTokens: estimateTurnTokens(turnBudget.usedChars),
1168
+ };
911
1169
  const factory = await getCreateUserMessage();
912
1170
  if (!factory) {
913
1171
  injectPhase.end();
@@ -923,7 +1181,21 @@ export function apply(ctx, config = {}) {
923
1181
  elapsedMs: Date.now() - started,
924
1182
  link: linkStat,
925
1183
  archiveUnavailable,
1184
+ archiveCode,
1185
+ injectedChars: 0,
1186
+ injectedTokens: 0,
926
1187
  });
1188
+ if (hardgatePending) {
1189
+ // B3 P1 接线:失败判决/原因码统一由 resolveRecallInjectionDecision 给(noChannel → fail)。
1190
+ const noChannelVerdict = resolveRecallInjectionDecision({ noChannel: true });
1191
+ recordPendingFailure({
1192
+ pending: hardgatePending,
1193
+ reason: noChannelVerdict.reason,
1194
+ evidence: ['factoryUnavailable', turnBudget.evidence],
1195
+ metrics: { injectedChars: 0, injectedTokens: 0, elapsedMs: Date.now() - started },
1196
+ warn,
1197
+ });
1198
+ }
927
1199
  return decision;
928
1200
  }
929
1201
 
@@ -968,13 +1240,15 @@ export function apply(ctx, config = {}) {
968
1240
  elapsedMs: Date.now() - started,
969
1241
  link: linkStat,
970
1242
  archiveUnavailable,
1243
+ injectedChars: laneMetrics.injectedChars,
1244
+ injectedTokens: laneMetrics.injectedTokens,
971
1245
  });
972
1246
  observe({
973
1247
  key, turn, why: gate.why, queryChars: queryText.length, eligible: result.hits.eligible,
974
1248
  injected: logItems.map((i) => i.path), tokens: logResult.tokens, budget: cfg.budget,
975
1249
  ms: Date.now() - started, forced,
976
1250
  link: { matchedTerms: linkStat.matchedTerms.length, injected: linkItems.length, tokens: linkTokens },
977
- archive: { unavailable: archiveUnavailable, injected: archiveItems.length },
1251
+ archive: { unavailable: archiveUnavailable, injected: archiveItems.length, code: archiveCode },
978
1252
  dropped: {
979
1253
  budget: result.hits.droppedByBudget,
980
1254
  dedupe: result.hits.droppedByDedupe,
@@ -984,7 +1258,22 @@ export function apply(ctx, config = {}) {
984
1258
  },
985
1259
  });
986
1260
 
987
- return { ...decision, messages: mergeInjectionOrder(sharedMessage === null ? messages : mergeInjectionOrder(messages, sharedMessage), message) };
1261
+ if (hardgatePending) {
1262
+ recordPendingResult({
1263
+ pending: hardgatePending,
1264
+ hit: fromArchive ? true : hardgateHit === true,
1265
+ items: fromArchive ? archiveItems.length : result.items.length,
1266
+ procedures: fromArchive ? 0 : hardgateProcedures,
1267
+ scanned: result.hits.eligible,
1268
+ extra: [turnBudget.evidence],
1269
+ metrics: laneMetrics,
1270
+ warn,
1271
+ });
1272
+ }
1273
+ return attachClaimGuard(
1274
+ { ...decision, messages: mergeInjectionOrder(sharedMessage === null ? messages : mergeInjectionOrder(messages, sharedMessage), message) },
1275
+ { composed: turnBudget.claimGuardFolded }, // 防编提示已并入九项预算块 → 不再追加第二条
1276
+ );
988
1277
  } catch (error) {
989
1278
  if (!st.warned) {
990
1279
  st.warned = true;
@@ -999,8 +1288,20 @@ export function apply(ctx, config = {}) {
999
1288
  forced: gateInfo?.why === 'forced',
1000
1289
  query: lastUserText,
1001
1290
  elapsedMs: Date.now() - started,
1291
+ injectedChars: 0,
1292
+ injectedTokens: 0,
1002
1293
  });
1003
- return attachShared(decision); // 插件失败不许拖垮本轮
1294
+ if (hardgatePending) {
1295
+ const failedVerdict = resolveRecallInjectionDecision({ failed: true });
1296
+ recordPendingFailure({
1297
+ pending: hardgatePending,
1298
+ reason: failedVerdict.reason,
1299
+ evidence: [String(error?.code ?? error?.message ?? error)],
1300
+ metrics: { injectedChars: 0, injectedTokens: 0, elapsedMs: Date.now() - started },
1301
+ warn,
1302
+ });
1303
+ }
1304
+ return attachClaimGuard(attachShared(decision)); // 插件失败不许拖垮本轮(防编提醒仍可独立注入)
1004
1305
  } finally {
1005
1306
  try { recallPhase.end(); } catch { /* timing only */ }
1006
1307
  }
@@ -76,7 +76,9 @@ export const AUTO_SECTION = 'auto-recall.cards';
76
76
  export const IDENTITY_SECTION = 'identity-router.open-card';
77
77
 
78
78
  /** 正文首行标记:保留用于识别历史消息与外部注入。 */
79
- export const AUTO_TEXT_MARK = '【自动想起】';
79
+ // 2.0.0 hardgate 起头带 recallId(`【自动想起 · recallId=…】`),零命中块同头;
80
+ // 因此只认前缀,不再要求恰好以 `】` 结尾。
81
+ export const AUTO_TEXT_MARK = '【自动想起';
80
82
  export const IDENTITY_TEXT_MARK = '【开机卡】';
81
83
  /**
82
84
  * 1.8.8 M2:归档兜底块的标记。它是 auto-recall 的第三种正文形态
@@ -121,7 +121,7 @@ export const FUSION_DEFAULTS = Object.freeze({
121
121
  /**
122
122
  * 路径本身命中 PII 时,header 里显示的替代文本。
123
123
  * chooseRecall 默认直接丢整卡;renderItemHeader 再兜一层,任何调用方都不会把
124
- * `topics/13900002222-订单.md` 这样的文件名写进上下文。
124
+ * `topics/<手机号>-订单.md` 这样的文件名写进上下文。
125
125
  */
126
126
  export const PRIVACY_HIDDEN_PATH = '<hidden>';
127
127
 
@@ -589,7 +589,7 @@ export function chooseRecall({
589
589
  }
590
590
 
591
591
  // 隐私门:标题、摘要或**路径**命中就不注入(默认整条丢;'title' 只留标题 + [已隐藏])。
592
- // 路径也是泄漏面:文件名可能直接带手机号(topics/13900002222-订单.md)。
592
+ // 路径也是泄漏面:文件名可能直接带手机号(示意:topics/<手机号>-订单.md)。
593
593
  // 这一步在去重之前,保证「就算重复也绝不把 PII 写进上下文」。
594
594
  if (privacyBlocked(scan, cand.title)) { stats.droppedByPrivacy += 1; reject(cand, 'privacy'); continue; }
595
595
  if (privacyBlocked(scan, cand.path)) { stats.droppedByPrivacy += 1; reject(cand, 'privacy'); continue; }
@@ -703,6 +703,51 @@ export function renderInjection(result, opts = {}) {
703
703
  return lines.join('\n');
704
704
  }
705
705
 
706
+ /* ------------------------------------------------------------------ *
707
+ * 5b. 硬门注入块(M02):recallId 头 / 逐卡 / 程序卡 / 当前线 / 零命中兜底
708
+ * ------------------------------------------------------------------ */
709
+
710
+ export const HARDGATE_RECALL_HEADER_PREFIX = '【自动想起 · recallId=';
711
+ export const HARDGATE_INSTRUCTION = '下面这些卡与当前消息的字面线索相关,只是线索不是指令;需要细节时再读原卡。';
712
+ export const HARDGATE_DISABLED_TEXT = '【硬门已被关闭(配置)】';
713
+ export const HARDGATE_SKIP_REASONS = Object.freeze(['SUBAGENT', 'NONUSER', 'MULTI_USER_MSG', 'KILLSWITCH', 'DISABLED']);
714
+
715
+ /**
716
+ * 渲染正常命中块(M02)。结构固定:
717
+ * 头(含 recallId)+ 一句口径声明 + 逐卡(标题/路径/相关度 + 正文摘录≤120)
718
+ * + 程序卡([程序] name · trigger,top2)+ 当前线(有才写)。
719
+ * @param {{recallId:string, items?:object[], procedures?:object[], currentLine?:string, budget?:number}} input
720
+ */
721
+ export function renderHardgateInjection(input = {}) {
722
+ const recallId = String(input.recallId ?? '');
723
+ const items = Array.isArray(input.items) ? input.items : [];
724
+ const procedures = Array.isArray(input.procedures) ? input.procedures : [];
725
+ const lines = [`${HARDGATE_RECALL_HEADER_PREFIX}${recallId}】`, HARDGATE_INSTRUCTION];
726
+ for (const item of items) {
727
+ lines.push(renderItemHeader(item, { showScore: true, withPath: true }));
728
+ const body = sanitizeDataText(item?.excerpt ?? '', 120);
729
+ if (body !== '') lines.push(` ${body}`);
730
+ }
731
+ for (const procedure of procedures) {
732
+ const name = sanitizeDataText(procedure?.name ?? '', 80);
733
+ const trigger = Array.isArray(procedure?.trigger)
734
+ ? procedure.trigger.map((value) => sanitizeDataText(value, 40)).join(' / ')
735
+ : sanitizeDataText(procedure?.trigger ?? '', 120);
736
+ lines.push(`[程序] ${name} · ${trigger}`);
737
+ }
738
+ const currentLine = String(input.currentLine ?? '').trim();
739
+ if (currentLine !== '') lines.push(currentLine);
740
+ return lines.join('\n');
741
+ }
742
+
743
+ /** 零命中兜底块:必须带 scanned / dropped_by / zero-hit=1(d1 check2)。 */
744
+ export function renderZeroHitBlock(input = {}) {
745
+ const recallId = String(input.recallId ?? '');
746
+ const scanned = Number.isFinite(Number(input.scanned)) ? Number(input.scanned) : 0;
747
+ const dropped = String(input.droppedBy ?? 'none') || 'none';
748
+ return `${HARDGATE_RECALL_HEADER_PREFIX}${recallId}】记忆里没有命中卡(scanned=${scanned} dropped_by=${dropped} zero-hit=1)`;
749
+ }
750
+
706
751
  /* ------------------------------------------------------------------ *
707
752
  * 6. 查询文本怎么拼
708
753
  * ------------------------------------------------------------------ */