@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,234 @@
|
|
|
1
|
+
// src/answer/claim-guard.mjs — D22 防编(W2 写侧,批 D)
|
|
2
|
+
//
|
|
3
|
+
// 设计依据(计划 v3.6.4 §4⑪ / §15 裁决):
|
|
4
|
+
// * 只读复用 answer/guard.js(HISTORY_CLAIM_RE / TOOL_CLAIM_RE / extractNumberClaims /
|
|
5
|
+
// SOURCE_GATE_HARD_CODES / auditTurn),不新建分析器、不改 guard.js / audit.js;
|
|
6
|
+
// * 触发点 = 宿主 pre-step 扫上一轮 assistant 文本(W4:src/recall/index.js),
|
|
7
|
+
// 不改 answer/index.js(含 :932)、不增改性点;
|
|
8
|
+
// * 命中 requires-source 时注入一条 ≤50 字的提醒(「称『我记得/上次』须指卡」),
|
|
9
|
+
// 同时经 recall/gate-log.mjs 的 appendGateLog 写 hg.d22.fail(decision=fail),
|
|
10
|
+
// 不阻断回答;分析失败一律 catch(写 warn),不得把主流程拖垮。
|
|
11
|
+
//
|
|
12
|
+
// fail-closed:参数缺失返回结构化错误码(不抛进调用方主流程的,是 apply/record 这类
|
|
13
|
+
// 预处理器;scanClaimGuard 作为纯函数在文本非法时也返回 ok:false 而不是编一个结果)。
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
HISTORY_CLAIM_RE,
|
|
17
|
+
SOURCE_GATE_HARD_CODES,
|
|
18
|
+
auditTurn,
|
|
19
|
+
isAbstention,
|
|
20
|
+
} from './guard.js';
|
|
21
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
22
|
+
|
|
23
|
+
export const BATCH = 'D';
|
|
24
|
+
export const SKELETON = Object.freeze({ version: '2.0.0', failClosed: true, implemented: true });
|
|
25
|
+
export const REQUIRES_SOURCE_MARK = 'requires-source';
|
|
26
|
+
export const INJECT_BUDGET_CHARS = 50;
|
|
27
|
+
export const GATE_EVENT = 'hg.d22.fail';
|
|
28
|
+
export const UNIMPLEMENTED_CODE = 'E_HG_CLAIM_GUARD_UNIMPLEMENTED';
|
|
29
|
+
|
|
30
|
+
export const FLAG_CODES = Object.freeze([
|
|
31
|
+
'HISTORY_CLAIM_NO_CITATION',
|
|
32
|
+
'ANSWERED_WITHOUT_EVIDENCE',
|
|
33
|
+
'FAKE_TOOL_CLAIM',
|
|
34
|
+
'UNGROUNDED_NUMBER',
|
|
35
|
+
'FAKE_TURN_REF',
|
|
36
|
+
'FAKE_CARD_REF',
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
/** 命中 requires-source 时的注入前缀(计划原文:「称『我记得/上次』须指卡」)。 */
|
|
40
|
+
export const INJECT_PREFIX = '称『我记得/上次』须指卡:';
|
|
41
|
+
|
|
42
|
+
function clip(text, max) {
|
|
43
|
+
const chars = Array.from(String(text ?? ''));
|
|
44
|
+
if (chars.length <= max) return chars.join('');
|
|
45
|
+
return chars.slice(0, Math.max(0, max - 1)).join('') + '…';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isHardFlag(flag) {
|
|
49
|
+
if (!flag || typeof flag.code !== 'string') return false;
|
|
50
|
+
return flag.severity === 'fabrication' || SOURCE_GATE_HARD_CODES.includes(flag.code);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function buildInjectText(flags) {
|
|
54
|
+
const codes = [...new Set(flags.filter(isHardFlag).map((flag) => flag.code))].slice(0, 3);
|
|
55
|
+
const body = codes.length > 0 ? `${INJECT_PREFIX}${codes.join('/')}` : `${INJECT_PREFIX}先指卡再答`;
|
|
56
|
+
return clip(body, INJECT_BUDGET_CHARS);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 纯扫描:把一段 assistant 文本交给 guard.auditTurn 判定,登记防编结果。
|
|
61
|
+
*
|
|
62
|
+
* @param {object} input {text, turn?, question?, historyQuestion?, zeroHit?, evidenceTurns?,
|
|
63
|
+
* evidenceUnits?, toolNames?, sessionToolNames?, sessionTurns?, knownTools?, cardExists?,
|
|
64
|
+
* contextText?, contextTruncated?, canAbstain?, difficulty?, questionType?, now?}
|
|
65
|
+
* @returns {{ok:boolean,code?:string,requiresSource:boolean,hardCodes:string[],flags:object[],
|
|
66
|
+
* injectText:string,verdict:string|null,evidence:object}}
|
|
67
|
+
*/
|
|
68
|
+
export function scanClaimGuard(input = {}) {
|
|
69
|
+
const text = String(input?.text ?? '');
|
|
70
|
+
if (text.trim() === '') {
|
|
71
|
+
return {
|
|
72
|
+
ok: false,
|
|
73
|
+
code: 'E_HG_D22_NO_TEXT',
|
|
74
|
+
requiresSource: false,
|
|
75
|
+
hardCodes: [],
|
|
76
|
+
flags: [],
|
|
77
|
+
injectText: '',
|
|
78
|
+
verdict: null,
|
|
79
|
+
evidence: { reason: 'empty-text' },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
let audit;
|
|
83
|
+
try {
|
|
84
|
+
audit = auditTurn({
|
|
85
|
+
text,
|
|
86
|
+
turn: Number.isInteger(Number(input.turn)) ? Number(input.turn) : 0,
|
|
87
|
+
question: String(input.question ?? text),
|
|
88
|
+
historyQuestion: input.historyQuestion === true || HISTORY_CLAIM_RE.test(text),
|
|
89
|
+
zeroHit: input.zeroHit === true,
|
|
90
|
+
evidenceTurns: Array.isArray(input.evidenceTurns) ? input.evidenceTurns : [],
|
|
91
|
+
evidenceUnits: input.evidenceUnits,
|
|
92
|
+
toolNames: Array.isArray(input.toolNames) ? input.toolNames : [],
|
|
93
|
+
sessionToolNames: Array.isArray(input.sessionToolNames) ? input.sessionToolNames : [],
|
|
94
|
+
sessionTurns: Array.isArray(input.sessionTurns) ? input.sessionTurns : [],
|
|
95
|
+
knownTools: Array.isArray(input.knownTools) ? input.knownTools : [],
|
|
96
|
+
cardExists: typeof input.cardExists === 'function' ? input.cardExists : () => true,
|
|
97
|
+
contextText: String(input.contextText ?? ''),
|
|
98
|
+
contextTruncated: input.contextTruncated === true,
|
|
99
|
+
canAbstain: input.canAbstain === true,
|
|
100
|
+
difficulty: String(input.difficulty ?? ''),
|
|
101
|
+
questionType: String(input.questionType ?? ''),
|
|
102
|
+
now: input.now,
|
|
103
|
+
sessionId: input.sessionId,
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
code: 'E_HG_D22_AUDIT_FAILED',
|
|
109
|
+
requiresSource: false,
|
|
110
|
+
hardCodes: [],
|
|
111
|
+
flags: [],
|
|
112
|
+
injectText: '',
|
|
113
|
+
verdict: null,
|
|
114
|
+
evidence: { reason: 'audit-threw', message: clip(error?.message ?? String(error), 200) },
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const flags = Array.isArray(audit.flags) ? audit.flags : [];
|
|
118
|
+
const hardCodes = [...new Set(flags.filter(isHardFlag).map((flag) => flag.code))];
|
|
119
|
+
const requiresSource = hardCodes.length > 0;
|
|
120
|
+
const zeroHit = audit.zeroHit === true;
|
|
121
|
+
return {
|
|
122
|
+
ok: true,
|
|
123
|
+
requiresSource,
|
|
124
|
+
hardCodes,
|
|
125
|
+
flags,
|
|
126
|
+
injectText: requiresSource ? buildInjectText(flags) : '',
|
|
127
|
+
verdict: typeof audit.verdict === 'string' ? audit.verdict : null,
|
|
128
|
+
evidence: {
|
|
129
|
+
mode: audit.answerMode ?? null,
|
|
130
|
+
zeroHit,
|
|
131
|
+
abstained: isAbstention(text),
|
|
132
|
+
historyQuestion: audit.historyQuestion === true,
|
|
133
|
+
turnRefs: audit.checks?.turnRefs ?? [],
|
|
134
|
+
cardRefs: audit.checks?.cardRefs ?? [],
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 写 hg.d22.fail(唯一门事件入口:appendGateLog)。
|
|
141
|
+
* 失败吞掉(返回 written:false),调用方据此只记录 warn。
|
|
142
|
+
*/
|
|
143
|
+
export function recordClaimGuardFailure(input = {}) {
|
|
144
|
+
const memoryRoot = input?.memoryRoot;
|
|
145
|
+
if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
|
|
146
|
+
return { ok: false, code: 'E_HG_D22_NO_ROOT', written: false };
|
|
147
|
+
}
|
|
148
|
+
const at = input.now instanceof Date ? input.now : new Date(input.now ?? Date.now());
|
|
149
|
+
const codes = Array.isArray(input.codes) ? input.codes : [];
|
|
150
|
+
const reason = codes.length > 0 ? codes.join('+') : String(input.code ?? 'E_HG_D22_FAIL');
|
|
151
|
+
try {
|
|
152
|
+
appendGateLog(memoryRoot, {
|
|
153
|
+
at: at.toISOString(),
|
|
154
|
+
sessionId: input.sessionId,
|
|
155
|
+
turn: Number.isInteger(Number(input.turn)) ? Number(input.turn) : undefined,
|
|
156
|
+
gate: GATE_EVENT,
|
|
157
|
+
decision: 'fail',
|
|
158
|
+
reason,
|
|
159
|
+
evidence: [String(input.detail ?? ''), ...codes].filter((item) => item !== ''),
|
|
160
|
+
});
|
|
161
|
+
return { ok: true, written: true, gate: GATE_EVENT, reason };
|
|
162
|
+
} catch (error) {
|
|
163
|
+
return {
|
|
164
|
+
ok: false,
|
|
165
|
+
written: false,
|
|
166
|
+
code: 'E_HG_D22_GATELOG_FAILED',
|
|
167
|
+
message: clip(error?.message ?? String(error), 200),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 预处理器:扫描上一轮 assistant 文本,requires-source 时生成注入提醒并写门事件。
|
|
174
|
+
* 永不 throw(catch 后 warn),返回结构化结果供 W4 合并注入。
|
|
175
|
+
*/
|
|
176
|
+
export function applyClaimGuard(context = {}) {
|
|
177
|
+
const memoryRoot = context?.memoryRoot;
|
|
178
|
+
const warn = typeof context.warn === 'function' ? context.warn : null;
|
|
179
|
+
const text = String(context?.text ?? '');
|
|
180
|
+
if (text.trim() === '') {
|
|
181
|
+
return { ok: true, requiresSource: false, injectText: '', gateWritten: false, code: 'E_HG_D22_NO_TEXT' };
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
const scan = scanClaimGuard({
|
|
185
|
+
text,
|
|
186
|
+
turn: context.turn,
|
|
187
|
+
question: context.question,
|
|
188
|
+
historyQuestion: context.historyQuestion,
|
|
189
|
+
zeroHit: context.zeroHit,
|
|
190
|
+
evidenceTurns: context.evidenceTurns,
|
|
191
|
+
evidenceUnits: context.evidenceUnits,
|
|
192
|
+
toolNames: context.toolNames,
|
|
193
|
+
sessionToolNames: context.sessionToolNames,
|
|
194
|
+
sessionTurns: context.sessionTurns,
|
|
195
|
+
knownTools: context.knownTools,
|
|
196
|
+
cardExists: context.cardExists,
|
|
197
|
+
contextText: context.contextText,
|
|
198
|
+
contextTruncated: context.contextTruncated,
|
|
199
|
+
canAbstain: context.canAbstain,
|
|
200
|
+
difficulty: context.difficulty,
|
|
201
|
+
questionType: context.questionType,
|
|
202
|
+
now: context.now,
|
|
203
|
+
sessionId: context.sessionId,
|
|
204
|
+
});
|
|
205
|
+
if (!scan.ok) {
|
|
206
|
+
warn?.(`[claim-guard] scan 未完成(${scan.code}):${scan.evidence?.message ?? ''}`);
|
|
207
|
+
return { ok: false, requiresSource: false, injectText: '', gateWritten: false, code: scan.code };
|
|
208
|
+
}
|
|
209
|
+
if (!scan.requiresSource) {
|
|
210
|
+
return { ok: true, requiresSource: false, injectText: '', gateWritten: false, code: null, flags: scan.flags };
|
|
211
|
+
}
|
|
212
|
+
const record = recordClaimGuardFailure({
|
|
213
|
+
memoryRoot,
|
|
214
|
+
sessionId: context.sessionId,
|
|
215
|
+
turn: context.turn,
|
|
216
|
+
now: context.now,
|
|
217
|
+
codes: scan.hardCodes,
|
|
218
|
+
detail: clip(text, 200),
|
|
219
|
+
});
|
|
220
|
+
if (!record.ok) warn?.(`[claim-guard] 门事件写入失败(${record.code}):${record.message ?? ''}`);
|
|
221
|
+
return {
|
|
222
|
+
ok: true,
|
|
223
|
+
requiresSource: true,
|
|
224
|
+
injectText: scan.injectText,
|
|
225
|
+
gateWritten: record.written === true,
|
|
226
|
+
code: REQUIRES_SOURCE_MARK,
|
|
227
|
+
flags: scan.flags,
|
|
228
|
+
hardCodes: scan.hardCodes,
|
|
229
|
+
};
|
|
230
|
+
} catch (error) {
|
|
231
|
+
warn?.(`[claim-guard] apply 异常已吞(${error?.code ?? 'E_HG_D22_INTERNAL'}):${error?.message ?? error}`);
|
|
232
|
+
return { ok: false, requiresSource: false, injectText: '', gateWritten: false, code: 'E_HG_D22_INTERNAL' };
|
|
233
|
+
}
|
|
234
|
+
}
|
package/src/backup.js
CHANGED
|
@@ -10,6 +10,14 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import crypto from 'node:crypto';
|
|
12
12
|
|
|
13
|
+
import { appendGateLog } from './recall/gate-log.mjs';
|
|
14
|
+
|
|
15
|
+
// 批 C(M22):备份是写路径的前置条件。备份不可用时必须 fail-closed,
|
|
16
|
+
// 对外只认一个错误码:E_HG_BACKUP。
|
|
17
|
+
export const BACKUP_ERROR_CODE = 'E_HG_BACKUP';
|
|
18
|
+
export const BACKUP_KEEP = 7;
|
|
19
|
+
const BACKUP_IO_CODES = ['EPERM', 'EACCES', 'EROFS', 'EBUSY', 'ENOSPC', 'ENOTDIR', 'EMFILE', 'ENFILE'];
|
|
20
|
+
|
|
13
21
|
export function sha256File(file) {
|
|
14
22
|
const hash = crypto.createHash('sha256');
|
|
15
23
|
hash.update(fs.readFileSync(file));
|
|
@@ -98,7 +106,15 @@ export function nextBackupPath(sessionPath, date = new Date(), expected = null)
|
|
|
98
106
|
* from the file we just wrote. A concurrent append therefore cannot slip into a
|
|
99
107
|
* backup that claims to represent the bytes the plan was built from.
|
|
100
108
|
*/
|
|
101
|
-
export function ensureBackup(sessionPath,
|
|
109
|
+
export function ensureBackup(sessionPath, options = {}) {
|
|
110
|
+
try {
|
|
111
|
+
return ensureBackupUnsafe(sessionPath, options);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
throw asBackupError(error, sessionPath);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function ensureBackupUnsafe(sessionPath, { date = new Date(), sourceBuf = null, sha256: expectedSha = null, size = null } = {}) {
|
|
102
118
|
const source = sourceBuf ?? fs.readFileSync(sessionPath);
|
|
103
119
|
const bytes = size ?? source.length;
|
|
104
120
|
if (source.length !== bytes) {
|
|
@@ -144,3 +160,151 @@ export function verifyBackup(file, expectedSha256) {
|
|
|
144
160
|
}
|
|
145
161
|
return { ok: true, sha256: actual };
|
|
146
162
|
}
|
|
163
|
+
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
// 批 C(M22):backup fail-closed 四守卫 + 保留上限
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
export function backupError(code, message, cause = null) {
|
|
169
|
+
const error = new Error(message ?? String(code));
|
|
170
|
+
error.name = 'HardgateBackupError';
|
|
171
|
+
error.code = code;
|
|
172
|
+
if (cause) error.cause = cause;
|
|
173
|
+
return error;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 任何 IO 拒绝(EPERM/EACCES/只读/磁盘满…)统一转 E_HG_BACKUP;业务错误原样透传。 */
|
|
177
|
+
export function asBackupError(error, sessionPath = '') {
|
|
178
|
+
if (!error) return backupError(BACKUP_ERROR_CODE, '备份失败(未知原因)');
|
|
179
|
+
if (error.code === BACKUP_ERROR_CODE) return error;
|
|
180
|
+
if (BACKUP_IO_CODES.includes(error.code)) {
|
|
181
|
+
return backupError(
|
|
182
|
+
BACKUP_ERROR_CODE,
|
|
183
|
+
`备份不可用,拒写(${error.code})${sessionPath ? `:${sessionPath}` : ''}`,
|
|
184
|
+
error,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
return error;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* 写前守卫 1:备份必须先成功,返回备份回执;备份失败抛 E_HG_BACKUP。
|
|
192
|
+
*/
|
|
193
|
+
export function assertBackupReady(sessionPath, options = {}) {
|
|
194
|
+
if (typeof sessionPath !== 'string' || sessionPath.trim() === '') {
|
|
195
|
+
throw backupError(BACKUP_ERROR_CODE, 'assertBackupReady 缺少 sessionPath:无法确认备份,拒写');
|
|
196
|
+
}
|
|
197
|
+
return ensureBackup(sessionPath, options);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 写前守卫 2:备份成功后再执行 writer(backup)。
|
|
202
|
+
* writer 抛错时备份保留(可回滚),错误原样抛出(不伪装成成功)。
|
|
203
|
+
*/
|
|
204
|
+
export function ensureBackupThenWrite(input = {}, writer = null) {
|
|
205
|
+
const sessionPath = input.sessionPath;
|
|
206
|
+
const backup = assertBackupReady(sessionPath, {
|
|
207
|
+
date: input.date ?? new Date(),
|
|
208
|
+
sourceBuf: input.sourceBuf ?? null,
|
|
209
|
+
sha256: input.sha256 ?? null,
|
|
210
|
+
size: input.size ?? null,
|
|
211
|
+
});
|
|
212
|
+
const run = typeof writer === 'function' ? writer : (typeof input.writer === 'function' ? input.writer : null);
|
|
213
|
+
if (!run) return { ok: true, backup, written: false };
|
|
214
|
+
const written = run(backup);
|
|
215
|
+
return { ok: true, backup, written };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* 写前守卫 3:guardedWrite。给卡片/状态写盘用:先备份会话日志,再原子写
|
|
220
|
+
* target(缺省 false 时只做备份守卫)。任何备份失败都拒绝落盘。
|
|
221
|
+
*/
|
|
222
|
+
export function guardedWrite(input = {}) {
|
|
223
|
+
const sessionPath = String(input.sessionPath ?? '').trim();
|
|
224
|
+
if (sessionPath === '') {
|
|
225
|
+
throw backupError(BACKUP_ERROR_CODE, 'guardedWrite 缺少 sessionPath:无法确认备份,拒写');
|
|
226
|
+
}
|
|
227
|
+
const backup = assertBackupReady(sessionPath, {
|
|
228
|
+
date: input.date ?? new Date(),
|
|
229
|
+
sourceBuf: input.sourceBuf ?? null,
|
|
230
|
+
sha256: input.sha256 ?? null,
|
|
231
|
+
size: input.size ?? null,
|
|
232
|
+
});
|
|
233
|
+
const target = String(input.path ?? input.cardPath ?? '').trim();
|
|
234
|
+
if (target === '') return { ok: true, backup, written: false };
|
|
235
|
+
if (typeof input.writer === 'function') {
|
|
236
|
+
return { ok: true, backup, written: input.writer(backup) };
|
|
237
|
+
}
|
|
238
|
+
const file = path.isAbsolute(target) ? target : path.resolve(input.memoryRoot ?? process.cwd(), target);
|
|
239
|
+
const content = String(input.content ?? '');
|
|
240
|
+
const dir = path.dirname(file);
|
|
241
|
+
try {
|
|
242
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
243
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
244
|
+
fs.writeFileSync(tmp, content, 'utf8');
|
|
245
|
+
fs.renameSync(tmp, file);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
throw asBackupError(error, file);
|
|
248
|
+
}
|
|
249
|
+
return { ok: true, backup, written: true, path: file, bytes: Buffer.byteLength(content, 'utf8') };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 写前守卫 4:writeWithBackup = guardedWrite 的可注入 writer 形态(旧名兼容)。 */
|
|
253
|
+
export function writeWithBackup(input = {}, writer = null) {
|
|
254
|
+
const opts = writer ? { ...input, writer } : input;
|
|
255
|
+
return guardedWrite(opts);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 保留上限(7 份):只删本会话自己的 .bak-* 副本,不碰 ledger 与其他文件。
|
|
260
|
+
* 删除前写 gate-log(备份可回滚,删的是重复副本);默认 dryRun=false 由调用方显式开启。
|
|
261
|
+
*/
|
|
262
|
+
export function pruneBackups({ sessionPath, memoryRoot = null, keep = BACKUP_KEEP, now = new Date(), dryRun = false } = {}) {
|
|
263
|
+
const session = String(sessionPath ?? '').trim();
|
|
264
|
+
if (session === '') return { ok: false, error: 'session-path-missing', removed: [], kept: 0 };
|
|
265
|
+
const backups = listBackups(session);
|
|
266
|
+
const keepN = Math.max(1, Math.floor(Number(keep) || BACKUP_KEEP));
|
|
267
|
+
const excess = backups.slice(0, Math.max(0, backups.length - keepN));
|
|
268
|
+
const removed = [];
|
|
269
|
+
for (const item of excess) {
|
|
270
|
+
if (dryRun) {
|
|
271
|
+
removed.push({ file: item.file, dryRun: true });
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
fs.unlinkSync(item.file);
|
|
276
|
+
removed.push({ file: item.file });
|
|
277
|
+
} catch (error) {
|
|
278
|
+
return { ok: false, error: String(error?.code ?? error), removed, kept: backups.length - removed.length };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// ledger 里只保留现存副本,避免下次读到幽灵记录。
|
|
282
|
+
if (!dryRun && removed.length > 0) {
|
|
283
|
+
try {
|
|
284
|
+
const ledger = readLedger(session);
|
|
285
|
+
const present = new Set(listBackups(session).map((item) => item.file));
|
|
286
|
+
ledger.backups = ledger.backups.filter((entry) => present.has(entry.file));
|
|
287
|
+
writeLedger(session, ledger);
|
|
288
|
+
} catch (error) {
|
|
289
|
+
return { ok: false, error: String(error?.code ?? error), removed, kept: backups.length - removed.length };
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (removed.length > 0 && memoryRoot) {
|
|
293
|
+
try {
|
|
294
|
+
appendGateLog(memoryRoot, {
|
|
295
|
+
gate: 'backup.prune',
|
|
296
|
+
decision: 'ok',
|
|
297
|
+
reason: 'backup.prune',
|
|
298
|
+
evidence: removed.map((item) => path.basename(item.file)),
|
|
299
|
+
at: (now instanceof Date ? now : new Date(now ?? Date.now())).toISOString(),
|
|
300
|
+
sessionId: null,
|
|
301
|
+
turn: null,
|
|
302
|
+
});
|
|
303
|
+
} catch {
|
|
304
|
+
// gate-log 写失败不回滚删除(副本已不在,账可事后补)
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return { ok: true, removed, kept: backups.length - removed.length, dryRun, keep: keepN };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export { pruneBackups as cleanupBackups, pruneBackups as enforceBackupRetention, pruneBackups as retainBackups, pruneBackups as trimBackups };
|
package/src/config.js
CHANGED
|
@@ -93,7 +93,7 @@ const ZH = {
|
|
|
93
93
|
$description: '自动想起:按轮次从记忆库召回卡片并注入上下文。',
|
|
94
94
|
enabled: '开启自动想起(默认开启;显式 false 关闭)。',
|
|
95
95
|
topK: '每次召回的最大卡片数(默认 3,范围 1–10)。',
|
|
96
|
-
budgetTokens: '每次召回的 token 预算(默认 2000,范围 200–2000)。',
|
|
96
|
+
budgetTokens: '每次召回的 token 预算(默认 2000,范围 200–2000)。B3 起每轮注入走字符车道:九项合计 2000 字符(≈1000 token,见 src/memory/turn-budget.mjs),召回块自身 ≤990 字符;本项同时作为字符车道上限使用(2000 字符),不再是纯 token 口径。',
|
|
97
97
|
everyNTurns: '每 N 轮召回一次(默认 6;1.8.8 起强制触发路径不再受它限制)。',
|
|
98
98
|
forceOnUserMessage: '1.8.8:每条真实用户任务消息都强制召回一次(默认 true;显式 false 完全回落 1.8.7 的按轮次/话题切换触发)。纯应答(好/嗯/继续/谢谢/收到)不触发。',
|
|
99
99
|
},
|
|
@@ -118,10 +118,10 @@ const ZH = {
|
|
|
118
118
|
},
|
|
119
119
|
},
|
|
120
120
|
identityCard: {
|
|
121
|
-
$description: '身份卡:在每次对话前置注入 STATE.md 摘要。',
|
|
121
|
+
$description: '身份卡:在每次对话前置注入 STATE.md 摘要。recentBudgetChars(最近三件预算,默认 1161)与 handoffSummary(交接摘要承接,默认开启)按块内非严格解析透传,不新增 schema 叶子(153 节点锁)。',
|
|
122
122
|
enabled: '开启身份卡注入(默认开启;显式 false 关闭)。',
|
|
123
123
|
path: '身份卡路径(默认 <memoryRoot>/STATE.md)。',
|
|
124
|
-
maxChars: '身份卡最多注入的字符数(默认
|
|
124
|
+
maxChars: '身份卡最多注入的字符数(默认 2233,范围 120–4000)。',
|
|
125
125
|
},
|
|
126
126
|
presenceBus: {
|
|
127
127
|
$description: '共享大脑:消费其他会话写入总线的消息。',
|
|
@@ -371,10 +371,10 @@ const EN = {
|
|
|
371
371
|
},
|
|
372
372
|
},
|
|
373
373
|
identityCard: {
|
|
374
|
-
$description: 'Identity card: prepend a STATE.md digest at the start of the conversation.',
|
|
374
|
+
$description: 'Identity card: prepend a STATE.md digest at the start of the conversation. recentBudgetChars (recent-section budget, default 1161) and handoffSummary (handoff-summary carry-over, on by default) pass through the block via non-strict parsing and add no schema leaves (153-node lock).',
|
|
375
375
|
enabled: 'Enable identity-card injection (on by default; explicitly false opts out).',
|
|
376
376
|
path: 'Identity-card path (default <memoryRoot>/STATE.md).',
|
|
377
|
-
maxChars: 'Maximum characters injected (default
|
|
377
|
+
maxChars: 'Maximum characters injected (default 2233, range 120–4000).',
|
|
378
378
|
},
|
|
379
379
|
presenceBus: {
|
|
380
380
|
$description: 'Shared brain: consume messages other sessions write to the bus.',
|
|
@@ -562,10 +562,13 @@ function schemaOf() {
|
|
|
562
562
|
everyNTurns: z.number().default(6).description(ZH.autoRecall.everyNTurns),
|
|
563
563
|
}).collapse();
|
|
564
564
|
|
|
565
|
+
// M05(DESIGN §8 C):maxChars 默认对齐生产契约 2233。recentBudgetChars / handoffSummary
|
|
566
|
+
// 不声明 schemastery 叶子:settings schema 节点数与 1.8.3 锁死一致 153;schemastery
|
|
567
|
+
// 非严格解析会把块内未声明键合并回解析结果(test/config-schema.test.mjs「未知键保留」)。
|
|
565
568
|
const identityCard = z.object({
|
|
566
569
|
enabled: z.boolean().default(true).description(ZH.identityCard.enabled),
|
|
567
570
|
path: z.string().default('<memoryRoot>/STATE.md').description(ZH.identityCard.path),
|
|
568
|
-
maxChars: z.number().default(
|
|
571
|
+
maxChars: z.number().default(2233).description(ZH.identityCard.maxChars),
|
|
569
572
|
}).collapse();
|
|
570
573
|
|
|
571
574
|
const presenceBus = z.object({
|
|
@@ -719,7 +722,8 @@ function schemaOf() {
|
|
|
719
722
|
enabled: z.boolean().default(false).description(ZH.retention.enabled),
|
|
720
723
|
dryRun: z.boolean().default(true).description(ZH.retention.dryRun),
|
|
721
724
|
intervalMs: z.number().default(86400000).description(ZH.retention.intervalMs),
|
|
722
|
-
|
|
725
|
+
// 批 C(M25):启动瞬间不跑清理;先门禁(冷档校验 + approve)再执行。
|
|
726
|
+
runOnStart: z.boolean().default(false).description(ZH.retention.runOnStart),
|
|
723
727
|
hotTruncate: z.object({
|
|
724
728
|
maxBytes: z.number().default(2147483648).description(ZH.retention.hotTruncate.maxBytes),
|
|
725
729
|
maxAgeDays: z.number().default(14).description(ZH.retention.hotTruncate.maxAgeDays),
|
|
@@ -795,6 +799,13 @@ function schemaOf() {
|
|
|
795
799
|
// config.proactive / config.handoff / config.tiering 仍是原始行配置,归一化分别由
|
|
796
800
|
// normalizeProactiveConfig / normalizeHandoffConfig / normalizeTiering 从 raw config 读取;
|
|
797
801
|
// 配置文案见上方 ZH/EN.tiering、ZH/EN.proactive、ZH/EN.handoff。
|
|
802
|
+
//
|
|
803
|
+
// H 批 hardgate 唤醒桥(N15)也走同一 passthrough 路线:config.hardgate.wake 不声明 leaf
|
|
804
|
+
// (153 节点锁不变),只允许 6 个运维键 enabled/triggers/maxPerDay/cooldownSec/timeoutSec/
|
|
805
|
+
// toolExclude(其余键 maxRounds/maxOutputTokens/maxOutputChars/retryMax/ticketTtlHours/
|
|
806
|
+
// queueMax/maxFilesPerRun/allowTools/preset/approvalPolicy 走代码默认、只可收紧)。
|
|
807
|
+
// 归一化 + 钳制在 src/memory/wake-bridge.mjs 的 normalizeWakeConfig(越界 clamp + warn +
|
|
808
|
+
// 下次 run 审计 configClamps),接线见 src/features.js 的 registerHardgateWake 块。
|
|
798
809
|
|
|
799
810
|
d2,
|
|
800
811
|
d6,
|