@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.
- package/CHANGELOG.md +232 -202
- package/QUICKSTART.md +10 -11
- package/README.en.md +13 -4
- package/README.md +42 -11
- package/SPEC.md +3 -3
- package/build-info.json +231 -121
- package/cordis.patch.yml +32 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/AUTO-RECALL.md +1 -1
- package/docs/CONFIG.md +41 -9
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +6 -6
- package/docs/OPERATIONS.md +1 -1
- package/docs/PANEL-INTEGRATION.md +1 -1
- package/docs/PRIVACY.md +5 -5
- package/docs/QUICKSTART.md +3 -3
- package/docs/README.en.md +4 -2
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +6 -3
- package/runbook.md +3 -3
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-lifecycle.mjs +2 -2
- package/src/answer/claim-guard.mjs +234 -0
- package/src/backup.js +165 -1
- package/src/config.js +18 -7
- package/src/features.js +128 -5
- package/src/handoff/index.js +133 -0
- package/src/handoff/model.js +48 -0
- package/src/identity/handover.js +203 -15
- package/src/identity/inject-position.js +3 -1
- package/src/memory/a1-migration.js +72 -6
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/capture-host.js +71 -2
- package/src/memory/capture.js +45 -6
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +51 -2
- package/src/memory/conclusion-drafts.js +7 -3
- package/src/memory/conflicts.js +915 -2
- package/src/memory/consolidate.js +20 -1
- package/src/memory/forget-v2.js +272 -2
- package/src/memory/forget.js +20 -1
- package/src/memory/frames-activation.js +3 -1
- package/src/memory/fts-query.js +2 -2
- package/src/memory/index.js +80 -7
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +128 -0
- package/src/memory/maintenance.js +386 -22
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +3 -3
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +20 -1
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +13 -1
- package/src/memory/recall.js +102 -1
- package/src/memory/reinforce.js +138 -2
- package/src/memory/retention.js +34 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/working-frame.js +271 -8
- package/src/metrics/classify.mjs +3 -1
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +174 -19
- package/src/recall/archive-search.mjs +3 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +21 -2
- package/src/recall/explain.mjs +10 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +322 -21
- package/src/recall/inject-order.mjs +3 -1
- package/src/recall/recall-core.mjs +47 -2
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +58 -1
- package/src/retention/index.js +193 -35
- package/src/router/design-headings.json +10 -10
- 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
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// N02 · 当前线(current line)
|
|
2
|
+
//
|
|
3
|
+
// 从记忆根取「我刚站哪儿」的一行,供硬门注入块的 `当前线:…` 行使用。
|
|
4
|
+
// 读源优先级(只读,绝不写):
|
|
5
|
+
// 1) flow/current.md 的「我正在做什么 / 下一步 / 卡在哪」首条非空行
|
|
6
|
+
// 2) STATE.md 的「我在哪」节首条非空行
|
|
7
|
+
// 预算分节沿用 handover.js 的 allocateBudget / compactSection(单一实现,
|
|
8
|
+
// 不在这里复写预算逻辑)。任何缺失都返回显式的 UNSET,而不是编一行假的。
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
allocateBudget,
|
|
15
|
+
compactSection,
|
|
16
|
+
parseState,
|
|
17
|
+
truncateChars,
|
|
18
|
+
} from '../identity/handover.js';
|
|
19
|
+
|
|
20
|
+
export const CURRENT_LINE_MAX_CHARS = 80;
|
|
21
|
+
export const UNSET = Symbol('hg.current-line.unset');
|
|
22
|
+
|
|
23
|
+
export class HardGateUnimplementedError extends Error {
|
|
24
|
+
constructor(moduleName, detail = '') {
|
|
25
|
+
super(`E_HG_${String(moduleName).toUpperCase()}_UNIMPLEMENTED${detail ? `: ${detail}` : ''}`);
|
|
26
|
+
this.code = `E_HG_${String(moduleName).toUpperCase()}_UNIMPLEMENTED`;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function firstMeaningfulLine(markdown) {
|
|
31
|
+
for (const raw of String(markdown ?? '').split(/\r?\n/)) {
|
|
32
|
+
const line = raw
|
|
33
|
+
.trim()
|
|
34
|
+
.replace(/^[-*+]\s+/u, '')
|
|
35
|
+
.replace(/^#{1,6}\s+/u, '')
|
|
36
|
+
.replace(/^\d+[.)]\s+/u, '')
|
|
37
|
+
.trim();
|
|
38
|
+
if (line === '' || line.startsWith('<!--') || line.startsWith('```')) continue;
|
|
39
|
+
return line;
|
|
40
|
+
}
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readTextIfAny(filePath) {
|
|
45
|
+
try {
|
|
46
|
+
return fs.readFileSync(filePath, 'utf8');
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 读当前线。返回 {text, chars, source, truncated};没有可用内容返回 UNSET。
|
|
54
|
+
* @param {{memoryRoot?: string, maxChars?: number}} [options]
|
|
55
|
+
*/
|
|
56
|
+
export function readCurrentLine(options = {}) {
|
|
57
|
+
const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
|
|
58
|
+
? path.resolve(options.memoryRoot.trim())
|
|
59
|
+
: null;
|
|
60
|
+
if (!memoryRoot) return UNSET;
|
|
61
|
+
const maxChars = Number.isFinite(options.maxChars)
|
|
62
|
+
? Math.max(8, Math.floor(options.maxChars))
|
|
63
|
+
: CURRENT_LINE_MAX_CHARS;
|
|
64
|
+
|
|
65
|
+
const flowText = readTextIfAny(path.join(memoryRoot, 'flow', 'current.md'));
|
|
66
|
+
if (flowText !== null) {
|
|
67
|
+
const sections = [];
|
|
68
|
+
const parsedFlow = parseState(flowText);
|
|
69
|
+
sections.push(...(parsedFlow.sections ?? []));
|
|
70
|
+
for (const heading of ['我正在做什么', '下一步', '卡在哪']) {
|
|
71
|
+
const section = sections.find((item) => String(item?.title ?? '').includes(heading));
|
|
72
|
+
const line = firstMeaningfulLine(section?.content ?? '');
|
|
73
|
+
if (line !== '') {
|
|
74
|
+
const cut = truncateChars(line, maxChars);
|
|
75
|
+
return { text: cut.text, chars: Array.from(cut.text).length, source: 'flow/current.md', truncated: cut.truncated };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const fallback = firstMeaningfulLine(flowText);
|
|
79
|
+
if (fallback !== '') {
|
|
80
|
+
const cut = truncateChars(fallback, maxChars);
|
|
81
|
+
return { text: cut.text, chars: Array.from(cut.text).length, source: 'flow/current.md', truncated: cut.truncated };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const stateText = readTextIfAny(path.join(memoryRoot, 'STATE.md'));
|
|
86
|
+
if (stateText !== null) {
|
|
87
|
+
const parsed = parseState(stateText);
|
|
88
|
+
const where = compactSection(parsed.sections, '我在哪', maxChars);
|
|
89
|
+
if (where.found && where.text.trim() !== '') {
|
|
90
|
+
const line = firstMeaningfulLine(where.text);
|
|
91
|
+
if (line !== '') {
|
|
92
|
+
const cut = truncateChars(line, maxChars);
|
|
93
|
+
return { text: cut.text, chars: Array.from(cut.text).length, source: 'STATE.md#我在哪', truncated: cut.truncated };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return UNSET;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 渲染注入块里的当前线行;没有当前线时返回空串(不编造)。 */
|
|
101
|
+
export function renderCurrentLine(memoryRoot) {
|
|
102
|
+
const line = readCurrentLine({ memoryRoot });
|
|
103
|
+
if (line === UNSET) return '';
|
|
104
|
+
return `当前线:${line.text}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 预算分节(暴露 handover 的单一实现,供后续 C 面复用)。 */
|
|
108
|
+
export function splitBudgets(parts, total) {
|
|
109
|
+
return allocateBudget(parts, total);
|
|
110
|
+
}
|
package/src/recall/edges.js
CHANGED
|
@@ -29,6 +29,8 @@ export const EXPAND_PRIORITY = Object.freeze({
|
|
|
29
29
|
conflicts_with: 1,
|
|
30
30
|
superseded_by: 2,
|
|
31
31
|
answers_with: 3,
|
|
32
|
+
derived_from: 4,
|
|
33
|
+
supersedes: 5,
|
|
32
34
|
});
|
|
33
35
|
// 历史查询词判定统一走 src/memory/lifecycle.js 的 isHistoricalQuery(D9 单一实现)。
|
|
34
36
|
|
|
@@ -336,22 +338,31 @@ export function expandEdges(baseItems, {
|
|
|
336
338
|
const items = [];
|
|
337
339
|
const seen = new Set(basePaths);
|
|
338
340
|
const dropped = [];
|
|
341
|
+
const dropCounts = { missingCard: 0, historical: 0, archived: 0, budget: 0 };
|
|
339
342
|
let tokens = 0;
|
|
340
343
|
let injected = 0;
|
|
341
344
|
for (const candidate of candidates) {
|
|
342
345
|
if (seen.has(candidate.target)) continue;
|
|
343
346
|
const card = cardsByPath.get(candidate.target);
|
|
344
|
-
if (!card) { dropped.push({ path: candidate.target, reason: 'missing-card' }); continue; }
|
|
347
|
+
if (!card) { dropCounts.missingCard += 1; dropped.push({ path: candidate.target, reason: 'missing-card' }); continue; }
|
|
345
348
|
const lifecycle = lifecycleOf ? lifecycleOf(candidate.target) : null;
|
|
346
349
|
if (lifecycle === 'historical' && !allowHistory) {
|
|
350
|
+
dropCounts.historical += 1;
|
|
347
351
|
dropped.push({ path: candidate.target, reason: 'historical' });
|
|
348
352
|
continue;
|
|
349
353
|
}
|
|
354
|
+
// M21 归档修边:archived/forgotten 目标不再注入(历史查询也不放行归档卡)。
|
|
355
|
+
const targetStatus = card?.fields?.status ?? card?.status ?? 'active';
|
|
356
|
+
if (targetStatus === 'archived' || targetStatus === 'forgotten') {
|
|
357
|
+
dropCounts.archived += 1;
|
|
358
|
+
dropped.push({ path: candidate.target, reason: 'archived' });
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
350
361
|
const title = String(card.title ?? card.fields?.title ?? candidate.target);
|
|
351
362
|
const excerpt = relationSentence(candidate.edge, card);
|
|
352
363
|
const text = `- 《${title}》(${candidate.target})\n${excerpt}`;
|
|
353
364
|
const cost = estimateTokens(text);
|
|
354
|
-
if (tokens + cost > budget) { dropped.push({ path: candidate.target, reason: 'budget' }); continue; }
|
|
365
|
+
if (tokens + cost > budget) { dropCounts.budget += 1; dropped.push({ path: candidate.target, reason: 'budget' }); continue; }
|
|
355
366
|
tokens += cost;
|
|
356
367
|
injected += 1;
|
|
357
368
|
seen.add(candidate.target);
|
|
@@ -375,5 +386,13 @@ export function expandEdges(baseItems, {
|
|
|
375
386
|
walked: walked.size,
|
|
376
387
|
injected,
|
|
377
388
|
dropped,
|
|
389
|
+
counts: {
|
|
390
|
+
walked: walked.size,
|
|
391
|
+
injected,
|
|
392
|
+
droppedHistorical: dropCounts.historical,
|
|
393
|
+
droppedArchived: dropCounts.archived,
|
|
394
|
+
droppedMissingCard: dropCounts.missingCard,
|
|
395
|
+
droppedBudget: dropCounts.budget,
|
|
396
|
+
},
|
|
378
397
|
};
|
|
379
398
|
}
|