@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
@@ -0,0 +1,501 @@
1
+ // N01 · 硬门召回策略单一入口(brain)
2
+ //
3
+ // 设计 v0.5.1 §6 A1:agent/pre-step step===1 一律走这里,不再用 decideTrigger
4
+ // 决定「要不要想」。本模块只做四件事:
5
+ // 1. 判本轮属于哪种情形(子代理 / 非用户轮 / 同轮多 user / killswitch / 正常);
6
+ // 2. 正常时打分选卡 + 选程序卡,交给 recall-core 渲染成注入块;
7
+ // 3. 每种情形恰好写一行 gate-log(d1 要求命中场景 1 行/轮);
8
+ // 4. 用宿主工厂造注入消息(模式 A)或仅记 fail(模式 B)。
9
+ //
10
+ // 失败一律显式:没有工厂 → 记 fail 且不注入;工厂造消息失败 → 记 fail 且不注入;
11
+ // 绝不 return true / 静默空过。N01 尚未接线的子能力会用 E_HG_<MOD>_UNIMPLEMENTED 报错。
12
+
13
+ import { scanCards } from '../memory/index.js';
14
+ import { scanProcedures } from '../memory/procedure.js';
15
+
16
+ import { loadCards } from './cards.mjs';
17
+ import { renderCurrentLine } from './current-line.mjs';
18
+ import { appendGateLog } from './gate-log.mjs';
19
+ import {
20
+ assertInjectionMessage,
21
+ identityInjectedPaths,
22
+ injectionSource,
23
+ isRealUserMessage,
24
+ mergeInjectionOrder,
25
+ textsOf,
26
+ } from './inject-order.mjs';
27
+ import {
28
+ HARDGATE_DISABLED_TEXT,
29
+ chooseRecall,
30
+ renderHardgateInjection,
31
+ renderZeroHitBlock,
32
+ } from './recall-core.mjs';
33
+ // B3 P1 接线:判决词表/原因码只由 resolveRecallInjectionDecision 一处产出(warn/disabled/
34
+ // zero-hit/ok/fail),brain 不再各分支手写 decision/reason;assert 兜住非法值。
35
+ import { assertRecallInjectionDecision, resolveRecallInjectionDecision } from './turn-budget-inject.mjs';
36
+
37
+ export const KILLSWITCH_ENV = 'DSH_LONGLIVE_DISABLE_HARDGATE';
38
+ export const KILLSWITCH_ENV_VALUE = '1';
39
+ export const RECALL_FAIL_CODE_NO_CHANNEL = 'E_HG_RECALL_NO_CHANNEL';
40
+ export const RECALL_FAIL_CODE_INJECT = 'E_HG_RECALL_INJECT';
41
+ export const HARDGATE_DEFAULT_BUDGET = 1600;
42
+ export const HARDGATE_MAX_ITEMS = 5;
43
+ // DESIGN §6 A1 六目录:journal 由调用方按近 2 天窗口预筛;这里只负责读盘。
44
+ export const HARDGATE_DIRS = Object.freeze(['topics', 'journal', 'topics/auto', 'procedures', 'flow', 'handover']);
45
+
46
+ /** N01 尚未实现的能力占位:调用即报错(fail-closed),不返回默认值。 */
47
+ export function unimplemented(moduleName, detail = '') {
48
+ const code = `E_HG_${String(moduleName).toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_UNIMPLEMENTED`;
49
+ const error = new Error(`${code}${detail ? `: ${detail}` : ''}`);
50
+ error.code = code;
51
+ return error;
52
+ }
53
+
54
+ /* ------------------------------------------------------------------ *
55
+ * 打分:ASCII 词 + CJK 单字/二元组;标题命中 ×3,正文 ×1。
56
+ * 归一化到 [0,1],阈值取 max(0.5, minScore)。这保证「完全无关」的卡
57
+ * 只靠一两个孤字/错误 bigram 不会被当成命中(d1 zero 夹具)。
58
+ * ------------------------------------------------------------------ */
59
+ function tokenizeWeighted(text) {
60
+ const weights = new Map();
61
+ const source = String(text ?? '').toLowerCase();
62
+ for (const word of source.match(/[a-z0-9_]+/g) ?? []) {
63
+ if (word.length >= 2) weights.set(word, 2);
64
+ }
65
+ for (const run of source.match(/[\u4e00-\u9fff]+/g) ?? []) {
66
+ const chars = Array.from(run);
67
+ for (const ch of chars) weights.set(ch, 1);
68
+ for (let i = 0; i + 1 < chars.length; i += 1) weights.set(chars[i] + chars[i + 1], 2);
69
+ }
70
+ return weights;
71
+ }
72
+
73
+ function tokenSet(text) {
74
+ return new Set(tokenizeWeighted(text).keys());
75
+ }
76
+
77
+ function matchedWeight(queryWeights, textSet) {
78
+ let hit = 0;
79
+ for (const [token, weight] of queryWeights) {
80
+ if (textSet.has(token)) hit += weight;
81
+ }
82
+ return hit;
83
+ }
84
+
85
+ function totalWeight(queryWeights) {
86
+ let sum = 0;
87
+ for (const weight of queryWeights.values()) sum += weight;
88
+ return sum || 1;
89
+ }
90
+
91
+ function titleOf(card) {
92
+ return String(card?.title ?? card?.name ?? '');
93
+ }
94
+
95
+ function bodyOf(card) {
96
+ const body = card?.body;
97
+ if (typeof body === 'string' && body !== '' && body !== '<hidden>') return body;
98
+ return String(card?.summary ?? '');
99
+ }
100
+
101
+ /** 单卡相关度:标题命中权重 ×3 + 正文命中权重;返回 [0,1]。 */
102
+ export function relevanceOf(queryWeights, card) {
103
+ const total = totalWeight(queryWeights);
104
+ const titleHit = matchedWeight(queryWeights, tokenSet(titleOf(card)));
105
+ const bodyHit = matchedWeight(queryWeights, tokenSet(bodyOf(card)));
106
+ return Math.min(1, (titleHit * 3 + bodyHit) / total);
107
+ }
108
+
109
+ function thresholdOf(cfg) {
110
+ const minScore = Number.isFinite(Number(cfg?.minScore)) ? Number(cfg.minScore) : 0.7;
111
+ return Math.max(0.5, Math.min(0.95, minScore));
112
+ }
113
+
114
+ function excerptOf(card, maxChars = 120) {
115
+ const body = bodyOf(card).replace(/\s+/g, ' ').trim();
116
+ if (body === '') return '';
117
+ const chars = Array.from(body);
118
+ if (chars.length <= maxChars) return body;
119
+ return `${chars.slice(0, maxChars - 1).join('')}…`;
120
+ }
121
+
122
+ /** 读六目录卡;目录全缺时返回 [](零命中由上层写 zero-hit 块,不崩)。 */
123
+ export function loadHardgateCards(memoryRoot, cfg = {}) {
124
+ const dirs = Array.isArray(cfg.dirs) && cfg.dirs.length > 0 ? cfg.dirs : HARDGATE_DIRS;
125
+ try {
126
+ return loadCards(memoryRoot, { dirs }) ?? [];
127
+ } catch {
128
+ return [];
129
+ }
130
+ }
131
+
132
+ /** 选卡:loadCards(六目录) → recall-core.chooseRecall(scope_in/别名/隐私/去重)→ 截断。 */
133
+ export function selectCards(memoryRoot, queryText, cfg = {}) {
134
+ const cards = Array.isArray(cfg.cards) ? cfg.cards : loadHardgateCards(memoryRoot, cfg);
135
+ const maxItems = Number.isFinite(Number(cfg.maxItems))
136
+ ? Math.max(1, Math.min(HARDGATE_MAX_ITEMS, Number(cfg.maxItems)))
137
+ : HARDGATE_MAX_ITEMS;
138
+ const seenPaths = Array.isArray(cfg.seenPaths) ? cfg.seenPaths : [];
139
+ let result;
140
+ try {
141
+ result = chooseRecall({
142
+ queryText,
143
+ cards,
144
+ seenPaths,
145
+ options: {
146
+ minScore: thresholdOf(cfg),
147
+ privacyPolicy: cfg.privacyPolicy ?? 'drop',
148
+ },
149
+ });
150
+ } catch {
151
+ result = { items: [], hits: {} };
152
+ }
153
+ const items = (Array.isArray(result.items) ? result.items : []).slice(0, maxItems).map((item) => ({
154
+ path: item.path,
155
+ title: item.title,
156
+ score: item.score,
157
+ excerpt: item.excerpt,
158
+ }));
159
+ const droppedBy = {};
160
+ for (const [key, value] of Object.entries(result.hits ?? {})) {
161
+ if (typeof value === 'number' && value > 0 && key.startsWith('dropped')) droppedBy[key] = value;
162
+ }
163
+ if (Object.keys(droppedBy).length === 0) droppedBy.score = Math.max(0, cards.length - items.length);
164
+ return { items, scanned: cards.length, droppedBy, cards };
165
+ }
166
+
167
+ /** 选程序卡:按 trigger/name 与 query 的相关度取 top2(d3 契约)。 */
168
+ export function selectProcedures(memoryRoot, queryText, maxItems = 2) {
169
+ const queryWeights = tokenizeWeighted(queryText);
170
+ let cards = [];
171
+ try {
172
+ cards = scanProcedures(memoryRoot)?.cards ?? [];
173
+ } catch {
174
+ cards = [];
175
+ }
176
+ const scored = [];
177
+ for (const card of cards) {
178
+ if (card?.invalid) continue;
179
+ const trigger = Array.isArray(card.trigger) ? card.trigger.join(' ') : String(card.trigger ?? '');
180
+ // 程序卡只看 trigger:名字里带任务关键词但 trigger 无关的卡不得被拉进来(d3 丙)。
181
+ const total = totalWeight(queryWeights);
182
+ const score = Math.min(1, matchedWeight(queryWeights, tokenSet(trigger)) / total);
183
+ if (score <= 0) continue;
184
+ scored.push({ name: String(card.name ?? ''), trigger: Array.isArray(card.trigger) ? card.trigger.slice(0, 4) : [String(card.trigger ?? '')], score });
185
+ }
186
+ scored.sort((left, right) => right.score - left.score || left.name.localeCompare(right.name));
187
+ return scored.slice(0, Math.max(0, maxItems));
188
+ }
189
+
190
+ /* ------------------------------------------------------------------ *
191
+ * 情形判定 + 每轮一行 gate-log
192
+ * ------------------------------------------------------------------ */
193
+ function subagentOf(payload) {
194
+ const agent = payload?.agent;
195
+ return agent?.session?.header?.origin === 'subagent'
196
+ || agent?.origin === 'subagent'
197
+ || payload?.origin === 'subagent';
198
+ }
199
+
200
+ function userMessagesOf(messages) {
201
+ return (Array.isArray(messages) ? messages : []).filter((message) => isRealUserMessage(message));
202
+ }
203
+
204
+ function textOf(message) {
205
+ const parts = textsOf(message);
206
+ return parts.length > 0 ? parts.join('\n') : '';
207
+ }
208
+
209
+ function normalizeTurn(payload) {
210
+ const value = Number(payload?.turn);
211
+ return Number.isFinite(value) ? value : null;
212
+ }
213
+
214
+ function writeGateRow(memoryRoot, { sessionId, turn, decision, reason, evidence = [], metrics = null, warn }) {
215
+ try {
216
+ return appendGateLog(memoryRoot, {
217
+ sessionId,
218
+ turn,
219
+ gate: 'recall',
220
+ decision,
221
+ // B3 C4:每行都要有非空 reason。ok 行用稳定值 'hit'(旧代码写空串,L7/d1 读不到);
222
+ // 其它缺省按 decision 回落,绝不写空串。
223
+ reason: typeof reason === 'string' && reason !== '' ? reason : (decision === 'ok' ? 'hit' : decision),
224
+ evidence,
225
+ // B3 C4:注入度量(字符/token/延迟)随行落盘;旧行没有该字段时域与 sha 不变。
226
+ ...(metrics && typeof metrics === 'object' ? {
227
+ injectedChars: metrics.injectedChars,
228
+ injectedTokens: metrics.injectedTokens,
229
+ elapsedMs: metrics.elapsedMs,
230
+ } : {}),
231
+ });
232
+ } catch (error) {
233
+ if (typeof warn === 'function') warn('HG_GATE_LOG_WRITE_FAILED', error?.code ?? error?.message ?? error);
234
+ return null;
235
+ }
236
+ }
237
+
238
+ function makeInjection(factory, text) {
239
+ const message = factory({ content: [{ type: 'text', text }], source: injectionSource() });
240
+ return assertInjectionMessage(message);
241
+ }
242
+
243
+ /**
244
+ * 硬门总入口。返回 {handled, decision, row?}。
245
+ * handled=false 表示本模块不接管(当前仅 step!==1 会这样)。
246
+ */
247
+ export async function runHardGate({
248
+ payload,
249
+ cfg = {},
250
+ decision,
251
+ getCreateUserMessage,
252
+ warn,
253
+ startedAt = null,
254
+ } = {}) {
255
+ if (Number(payload?.step) !== 1) return { handled: false, decision };
256
+ const messages = Array.isArray(decision?.messages) ? decision.messages : [];
257
+ const sessionId = String(payload?.agent?.session?.id ?? payload?.agent?.id ?? 'unknown');
258
+ const turn = normalizeTurn(payload);
259
+ const memoryRoot = typeof cfg.memoryRoot === 'string' ? cfg.memoryRoot.trim() : '';
260
+ const switchReason = cfg.autoRecall === false
261
+ ? 'autoRecall:false'
262
+ : (process.env[KILLSWITCH_ENV] === KILLSWITCH_ENV_VALUE || process.env[KILLSWITCH_ENV] === 'true' ? KILLSWITCH_ENV : '');
263
+ const killswitch = switchReason !== '';
264
+ // B3 C4:每行 gate-log 都要有非空 reason + 注入度量(字符/token/延迟)。warn/
265
+ // killswitch 这类不注入或只注入告警块的分支也记 0 字符行与真实耗时(由调用方传入
266
+ // 本轮 pre-step 起点),不再出现「有 reason 没 token」的行。
267
+ const startedMs = Number.isFinite(Number(startedAt)) && Number(startedAt) > 0 ? Number(startedAt) : null;
268
+ const gateRowMetrics = (injectedChars = 0) => ({
269
+ injectedChars,
270
+ injectedTokens: Math.ceil(injectedChars / 2),
271
+ elapsedMs: startedMs === null ? 0 : Math.max(0, Date.now() - startedMs),
272
+ });
273
+
274
+ if (switchReason === '') {
275
+ if (subagentOf(payload)) {
276
+ // B3 C3:子代理轮不是用户轮,但不许再写 skip——记 warn + 稳定原因码。
277
+ const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ subagent: true }));
278
+ const row = writeGateRow(memoryRoot, { sessionId, turn, decision: verdict.decision, reason: verdict.reason, evidence: [], metrics: gateRowMetrics(0), warn });
279
+ return { handled: true, decision, row };
280
+ }
281
+ const userMessages = userMessagesOf(messages);
282
+ if (userMessages.length === 0) {
283
+ const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ nonUser: true }));
284
+ const row = writeGateRow(memoryRoot, { sessionId, turn, decision: verdict.decision, reason: verdict.reason, evidence: [], metrics: gateRowMetrics(0), warn });
285
+ return { handled: true, decision, row };
286
+ }
287
+ if (userMessages.length > 1) {
288
+ // 同一轮多条 user:判决仍用非用户轮口径(warn),原因码保留更具体的 W_HG_MULTI_USER_MSG。
289
+ const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ nonUser: true }));
290
+ const row = writeGateRow(memoryRoot, {
291
+ sessionId, turn, decision: verdict.decision, reason: 'W_HG_MULTI_USER_MSG', evidence: [], metrics: gateRowMetrics(0), warn,
292
+ });
293
+ return { handled: true, decision, row };
294
+ }
295
+ }
296
+
297
+ let factory = null;
298
+ try {
299
+ factory = typeof getCreateUserMessage === 'function' ? await getCreateUserMessage() : null;
300
+ } catch {
301
+ factory = null;
302
+ }
303
+
304
+ // killswitch:走 shared 可见块通道;不依赖 factory 才不注入,但块文本仍必须
305
+ // 带「硬门已被关闭(配置)」(d1 配置/环境两种开关都断言这段文本)。
306
+ if (killswitch) {
307
+ const block = `${HARDGATE_DISABLED_TEXT}本轮不做召回注入。原因:${switchReason}。开关去掉后下一轮自动恢复。`;
308
+ let injected = null;
309
+ if (typeof factory === 'function') {
310
+ try {
311
+ injected = makeInjection(factory, block);
312
+ } catch {
313
+ injected = null;
314
+ }
315
+ }
316
+ // B3 P1 接线:disabled/killswitch 由统一判决函数给出(不再手写字符串)。
317
+ const disabledVerdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ killswitch: true }));
318
+ const row = writeGateRow(memoryRoot, {
319
+ sessionId,
320
+ turn,
321
+ decision: disabledVerdict.decision,
322
+ reason: disabledVerdict.reason,
323
+ evidence: [`switch=${switchReason}`, `recallId=null`],
324
+ metrics: gateRowMetrics(Array.from(block).length),
325
+ warn,
326
+ });
327
+ const nextDecision = injected
328
+ ? { ...decision, messages: mergeInjectionOrder(messages, injected) }
329
+ : decision;
330
+ return { handled: true, decision: nextDecision, row };
331
+ }
332
+
333
+ // 模式 B:没有消息工厂 → 不注入(d1 check5)。仍把 pending 交给 legacy 生产链:
334
+ // 统一审计/证据包/recall-log 的既有写入必须保留(A5/M2-C 依赖),只在注入点写
335
+ // fail 行(reason=E_HG_RECALL_NO_CHANNEL),不静默也不假注入。
336
+ const recallId = `${sessionId}-${turn ?? 0}-${Date.now()}`;
337
+ const budget = Number.isFinite(Number(cfg.budget)) ? Math.max(200, Math.min(2000, Number(cfg.budget))) : HARDGATE_DEFAULT_BUDGET;
338
+ if (typeof factory !== 'function') {
339
+ return {
340
+ handled: false,
341
+ decision,
342
+ pending: {
343
+ recallId,
344
+ sessionId,
345
+ turn,
346
+ budget,
347
+ memoryRoot: typeof memoryRoot === 'string' && memoryRoot !== '' ? memoryRoot : null,
348
+ noChannel: true,
349
+ },
350
+ };
351
+ }
352
+
353
+ // 正常路径:brain 只产出 pending 描述(recallId/预算/记忆根),选卡、渲染与
354
+ // gate-log 写入交给 recall/index.js 的生产链尾——那里已有 embedding/实体扩展/
355
+ // 证据包/统一审计/recall-log 的既有写入(recallId 三写不重复,也不旁路)。
356
+ return {
357
+ handled: false,
358
+ decision,
359
+ pending: {
360
+ recallId,
361
+ sessionId,
362
+ turn,
363
+ budget,
364
+ memoryRoot: typeof memoryRoot === 'string' && memoryRoot !== '' ? memoryRoot : null,
365
+ },
366
+ };
367
+ }
368
+
369
+ function droppedByText(droppedBy) {
370
+ if (!droppedBy || typeof droppedBy !== 'object') return 'none';
371
+ const parts = Object.entries(droppedBy)
372
+ .filter(([, value]) => Number(value) > 0)
373
+ .map(([key, value]) => `${key}:${value}`);
374
+ return parts.length > 0 ? parts.join(',') : 'none';
375
+ }
376
+
377
+ /** 生产链尾渲染:命中块(卡 + 程序卡 + 当前线)或零命中兜底块。 */
378
+ export function renderPendingBlock({ pending, items = [], procedures = [], scanned = 0, droppedBy = null } = {}) {
379
+ const recallId = pending?.recallId ?? 'unknown';
380
+ const budget = pending?.budget ?? HARDGATE_DEFAULT_BUDGET;
381
+ if (items.length + procedures.length === 0) {
382
+ return { hit: false, block: renderZeroHitBlock({ recallId, scanned, droppedBy: droppedByText(droppedBy) }) };
383
+ }
384
+ const block = capBlock(renderHardgateInjection({
385
+ recallId,
386
+ items,
387
+ procedures,
388
+ currentLine: renderCurrentLine(pending?.memoryRoot ?? ''),
389
+ budget,
390
+ }), budget);
391
+ return { hit: true, block };
392
+ }
393
+
394
+ function hardgateEvidence({ pending, items = 0, procedures = 0, scanned = 0, extra = [] } = {}) {
395
+ return [
396
+ `recallId=${pending?.recallId ?? 'unknown'}`,
397
+ `items=${items}`,
398
+ `procedures=${procedures}`,
399
+ `scanned=${scanned}`,
400
+ ...(Array.isArray(extra) ? extra : []),
401
+ ];
402
+ }
403
+
404
+ /** 零命中分支专用:渲染零命中块、注入、写唯一一行 gate-log(d1 check2/8)。 */
405
+ export function finishPendingInjection({
406
+ pending,
407
+ decision,
408
+ messages,
409
+ block,
410
+ hit,
411
+ factory,
412
+ items = 0,
413
+ procedures = 0,
414
+ scanned = 0,
415
+ extra = [],
416
+ metrics = null,
417
+ warn,
418
+ } = {}) {
419
+ if (typeof factory !== 'function') {
420
+ // B3 P1 接线:无消息通道 → fail/E_HG_RECALL_NO_CHANNEL(统一判决函数)。
421
+ const noChannelVerdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ noChannel: true }));
422
+ const row = writeGateRow(pending?.memoryRoot ?? '', {
423
+ sessionId: pending?.sessionId,
424
+ turn: pending?.turn,
425
+ decision: noChannelVerdict.decision,
426
+ reason: noChannelVerdict.reason,
427
+ evidence: [],
428
+ metrics,
429
+ warn,
430
+ });
431
+ return { decision, row, injected: false };
432
+ }
433
+ let injected;
434
+ try {
435
+ injected = makeInjection(factory, block);
436
+ } catch (error) {
437
+ const failedVerdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ failed: true }));
438
+ const row = writeGateRow(pending?.memoryRoot ?? '', {
439
+ sessionId: pending?.sessionId,
440
+ turn: pending?.turn,
441
+ decision: failedVerdict.decision,
442
+ reason: failedVerdict.reason,
443
+ evidence: [String(error?.code ?? error?.message ?? error)].slice(0, 14),
444
+ metrics,
445
+ warn,
446
+ });
447
+ return { decision, row, injected: false };
448
+ }
449
+ // B3 P1 接线:命中/零命中判决由统一函数给出(ok/hit 或 zero-hit/zero-hit)。
450
+ const resultVerdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ zeroHit: hit !== true }));
451
+ const row = writeGateRow(pending?.memoryRoot ?? '', {
452
+ sessionId: pending?.sessionId,
453
+ turn: pending?.turn,
454
+ decision: resultVerdict.decision,
455
+ reason: resultVerdict.reason,
456
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
457
+ metrics,
458
+ warn,
459
+ });
460
+ return {
461
+ decision: { ...decision, messages: mergeInjectionOrder(Array.isArray(messages) ? messages : [], injected) },
462
+ row,
463
+ injected: true,
464
+ };
465
+ }
466
+
467
+ /** 生产链尾失败分支:只写一行 fail gate-log(不注入),用于工厂缺失/异常。 */
468
+ export function recordPendingFailure({ pending, reason = RECALL_FAIL_CODE_INJECT, evidence = [], metrics = null, warn } = {}) {
469
+ // B3 P1 接线:默认失败原因码由统一判决函数给(调用方仍可传更具体的原因码)。
470
+ const failedVerdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ failed: true }));
471
+ return writeGateRow(pending?.memoryRoot ?? '', {
472
+ sessionId: pending?.sessionId,
473
+ turn: pending?.turn,
474
+ decision: failedVerdict.decision,
475
+ reason,
476
+ evidence: hardgateEvidence({ pending, extra: evidence }),
477
+ metrics,
478
+ warn,
479
+ });
480
+ }
481
+
482
+ /** 生产链尾命中/归档分支:文本已注入,只补写唯一一行 gate-log。 */
483
+ export function recordPendingResult({ pending, hit, items = 0, procedures = 0, scanned = 0, extra = [], metrics = null, warn } = {}) {
484
+ // B3 P1 接线:ok/zero-hit 判决由统一判决函数给(命中 → ok/hit,零命中 → zero-hit/zero-hit)。
485
+ const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ zeroHit: hit !== true }));
486
+ return writeGateRow(pending?.memoryRoot ?? '', {
487
+ sessionId: pending?.sessionId,
488
+ turn: pending?.turn,
489
+ decision: verdict.decision,
490
+ reason: verdict.reason,
491
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
492
+ metrics,
493
+ warn,
494
+ });
495
+ }
496
+
497
+ function capBlock(text, budget) {
498
+ const chars = Array.from(text);
499
+ if (chars.length <= budget) return text;
500
+ return `${chars.slice(0, Math.max(1, budget - 1)).join('')}…`;
501
+ }