@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.
- package/CHANGELOG.md +258 -202
- package/QUICKSTART.md +10 -11
- package/README.en.md +13 -4
- package/README.md +61 -18
- package/SPEC.md +3 -3
- package/build-info.json +259 -129
- package/cordis.patch.yml +32 -1
- package/docs/ANSWER-GUARD.md +1 -1
- package/docs/ARCHITECTURE.md +3 -3
- package/docs/AUTO-RECALL-WIRING.md +5 -3
- package/docs/AUTO-RECALL.md +10 -4
- package/docs/CONFIG.md +46 -11
- package/docs/ERRORS.md +1 -1
- package/docs/FAQ.md +9 -9
- package/docs/FEATURES.md +19 -16
- package/docs/OPERATIONS.md +3 -3
- package/docs/PANEL-INTEGRATION.md +1 -1
- package/docs/PRIVACY.md +6 -6
- package/docs/QUICKSTART.md +5 -5
- package/docs/README.en.md +5 -3
- package/docs/TOOLS.md +1 -1
- 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 +132 -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/index.js +2 -2
- 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/memory-reader.mjs +1003 -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/continuity-log.mjs +435 -0
- package/src/recall/continuity-volatile.mjs +1001 -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 +663 -29
- package/src/recall/inject-order.mjs +3 -1
- package/src/recall/link-fastpath.mjs +662 -0
- package/src/recall/recall-core.mjs +74 -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,415 @@
|
|
|
1
|
+
// memory/archive.mjs — hardgate 归档写点(批 C / W1c 实装)
|
|
2
|
+
//
|
|
3
|
+
// 契约(DESIGN v0.5.1 §9 / MERGE-PLAN §4⑧、§12):
|
|
4
|
+
// - edges.jsonl 只追加不删卡;每条边带 schema、时间、证据与来源。
|
|
5
|
+
// - 归档移动 = 卡文件移入 topics/archive/<YYYY-MM>/ + 写 lifecycle:historical
|
|
6
|
+
// + 追加一条移动边 + 重建 INDEX(同一批内完成,避免悬空边)。
|
|
7
|
+
// - auto-run 槽表命中才跑,且按 last-run 节流(默认 6h)。
|
|
8
|
+
// - 写守卫:备份不可用必须拒写(E_HG_BACKUP),绝不静默成功。
|
|
9
|
+
// - fail-closed:未配置 memoryRoot / 坏 manifest 一律抛错,不许返回“看起来成功”。
|
|
10
|
+
//
|
|
11
|
+
// 对外错误码(A6 五码,见 MERGE-PLAN §17 L163):
|
|
12
|
+
// E_HG_ARCHIVE_OFFLINE / E_HG_ARCHIVE_READONLY / E_HG_ARCHIVE_LOW_SPACE /
|
|
13
|
+
// E_HG_ARCHIVE_WRONG_VOLUME / E_HG_ARCHIVE_MIGRATE_MISMATCH
|
|
14
|
+
// 旧名 STATE_INVALID / DIGEST_MISSING / DIGEST_INVALID / E_HG_ARCHIVE_DIGEST_INVALID
|
|
15
|
+
// 全部作废,不得再作为对外码出现。
|
|
16
|
+
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
|
|
21
|
+
import { dayString, isoStamp } from './frontmatter.js';
|
|
22
|
+
import { ensureBackup } from '../backup.js';
|
|
23
|
+
import { memoryIndex as rebuildMemoryIndex } from './index.js';
|
|
24
|
+
|
|
25
|
+
export const BATCH = 'C';
|
|
26
|
+
export const MODULE = 'memory/archive.mjs';
|
|
27
|
+
// 仅作兼容保留:骨架时代的外部常量,现在不再抛出。
|
|
28
|
+
export const UNIMPLEMENTED_CODE = 'E_HG_ARCHIVE_UNIMPLEMENTED';
|
|
29
|
+
export const ARCHIVE_SCHEMA = 'archive/v1';
|
|
30
|
+
export const EDGES_SCHEMA = 'edges/v1';
|
|
31
|
+
export const EDGES_LOG_REL = '.longlive/hardgate/edges.jsonl';
|
|
32
|
+
export const ARCHIVE_STATE_REL = '.longlive/hardgate/archive-state.json';
|
|
33
|
+
export const ARCHIVE_QUEUE_REL = '.longlive/hardgate/archive-queue.jsonl';
|
|
34
|
+
export const ARCHIVE_DIR_REL = 'topics/archive';
|
|
35
|
+
export const ARCHIVE_SLOTS = Object.freeze(['distill', 'rotation', 'archive-move', 'manual']);
|
|
36
|
+
export const ARCHIVE_MIN_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
37
|
+
export const MAX_QUEUE_LINES = 1000;
|
|
38
|
+
|
|
39
|
+
export const EDGE_TYPES = Object.freeze([
|
|
40
|
+
'supersedes', 'superseded_by', 'deprecated_by', 'conflicts_with',
|
|
41
|
+
'answers_with', 'derived_from', 'mentions', 'same_topic', 'moved_to',
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
/** 骨架兼容对象:implemented=true 表示本文件已是真实实现(保留导出名)。 */
|
|
45
|
+
export const SKELETON = Object.freeze({
|
|
46
|
+
version: '2.0.0', failClosed: true, batch: 'C', implemented: true,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export function archiveError(code, message, extra = {}) {
|
|
50
|
+
const error = new Error(message ?? String(code));
|
|
51
|
+
error.name = 'HardgateArchiveError';
|
|
52
|
+
error.code = code;
|
|
53
|
+
error.status = code;
|
|
54
|
+
Object.assign(error, extra);
|
|
55
|
+
return error;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sha256(text) {
|
|
59
|
+
return crypto.createHash('sha256').update(String(text)).digest('hex');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function toDate(now) {
|
|
63
|
+
const at = now instanceof Date ? now : new Date(now ?? Date.now());
|
|
64
|
+
if (Number.isNaN(at.getTime())) throw archiveError('E_HG_ARCHIVE_OFFLINE', 'bad clock');
|
|
65
|
+
return at;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function resolveRoot(memoryRoot) {
|
|
69
|
+
const root = typeof memoryRoot === 'string' && memoryRoot.trim() !== '' ? path.resolve(memoryRoot) : null;
|
|
70
|
+
if (!root) throw archiveError('E_HG_ARCHIVE_OFFLINE', 'memoryRoot 未配置:归档写点 fail-closed');
|
|
71
|
+
return root;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function insideRoot(root, rel) {
|
|
75
|
+
const abs = path.resolve(root, rel);
|
|
76
|
+
return abs === root || abs.startsWith(root + path.sep);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalizeEdge(edge, now) {
|
|
80
|
+
const src = edge && typeof edge === 'object' ? edge : {};
|
|
81
|
+
const from = String(src.from ?? '').trim();
|
|
82
|
+
const to = String(src.to ?? '').trim();
|
|
83
|
+
if (from === '' || to === '') throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', 'edge 缺少 from/to');
|
|
84
|
+
const type = String(src.type ?? '').trim();
|
|
85
|
+
if (!EDGE_TYPES.includes(type)) throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `edge type 非法: ${type}`);
|
|
86
|
+
const evidence = Array.isArray(src.evidence)
|
|
87
|
+
? src.evidence.map((item) => String(item))
|
|
88
|
+
: src.evidence
|
|
89
|
+
? [String(src.evidence)]
|
|
90
|
+
: [];
|
|
91
|
+
const row = {
|
|
92
|
+
schema: EDGES_SCHEMA,
|
|
93
|
+
at: isoStamp(now),
|
|
94
|
+
from: from.replace(/\\/g, '/'),
|
|
95
|
+
to: to.replace(/\\/g, '/'),
|
|
96
|
+
type,
|
|
97
|
+
evidence,
|
|
98
|
+
confidence: Number.isFinite(Number(src.confidence)) ? Number(src.confidence) : null,
|
|
99
|
+
source: String(src.source ?? 'archive'),
|
|
100
|
+
};
|
|
101
|
+
row.sha256 = sha256(JSON.stringify(row));
|
|
102
|
+
return row;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 追加一条边到 .longlive/hardgate/edges.jsonl(只追加,绝不改写/删除)。
|
|
107
|
+
* @returns {{ok:true, row:object, file:string, appended:true}}
|
|
108
|
+
*/
|
|
109
|
+
export function appendEdge(input = {}) {
|
|
110
|
+
const root = resolveRoot(input.memoryRoot);
|
|
111
|
+
const now = toDate(input.now);
|
|
112
|
+
const row = normalizeEdge(input.edge ?? input, now);
|
|
113
|
+
const file = path.join(root, EDGES_LOG_REL);
|
|
114
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
115
|
+
// 幂等:同一条边(from/to/type 相同)只保留一次;仍然只追加、绝不重写旧行。
|
|
116
|
+
if (fs.existsSync(file)) {
|
|
117
|
+
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
|
118
|
+
if (line.trim() === '') continue;
|
|
119
|
+
try {
|
|
120
|
+
const existing = JSON.parse(line);
|
|
121
|
+
if (existing.from === row.from && existing.to === row.to && existing.type === row.type) {
|
|
122
|
+
return { ok: true, row: existing, file, appended: false, duplicate: true };
|
|
123
|
+
}
|
|
124
|
+
} catch {
|
|
125
|
+
// 坏行不阻断新边;诊断走 readEdges()。
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// 一开一闭的追加写;不读旧行、不重写旧行。
|
|
130
|
+
const fd = fs.openSync(file, 'a');
|
|
131
|
+
try {
|
|
132
|
+
fs.writeSync(fd, JSON.stringify(row) + '\n');
|
|
133
|
+
fs.fsyncSync(fd);
|
|
134
|
+
} finally {
|
|
135
|
+
fs.closeSync(fd);
|
|
136
|
+
}
|
|
137
|
+
return { ok: true, row, file, appended: true };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 兼容别名:骨架期名字,语义与 appendEdge 完全一致。 */
|
|
141
|
+
export function appendArchiveEdge(input = {}) {
|
|
142
|
+
const row = appendEdge(input);
|
|
143
|
+
return { ...row, edge: row.row };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 读边(诊断用):缺失 = 空;坏行如实记 corrupt,不抛。 */
|
|
147
|
+
export function readEdges({ memoryRoot } = {}) {
|
|
148
|
+
const root = resolveRoot(memoryRoot);
|
|
149
|
+
const file = path.join(root, EDGES_LOG_REL);
|
|
150
|
+
if (!fs.existsSync(file)) return { ok: true, file, rows: [], corrupt: null };
|
|
151
|
+
const rows = [];
|
|
152
|
+
let corrupt = null;
|
|
153
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
154
|
+
for (const [index, line] of lines.entries()) {
|
|
155
|
+
if (line.trim() === '') continue;
|
|
156
|
+
try {
|
|
157
|
+
const parsed = JSON.parse(line);
|
|
158
|
+
if (parsed && parsed.schema === EDGES_SCHEMA) rows.push(parsed);
|
|
159
|
+
else corrupt = corrupt ?? { line: index + 1, reason: 'schema' };
|
|
160
|
+
} catch {
|
|
161
|
+
corrupt = corrupt ?? { line: index + 1, reason: 'json' };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { ok: corrupt === null, file, rows, corrupt };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function ensureFrontmatterHistorical(text) {
|
|
168
|
+
const src = typeof text === 'string' ? text : '';
|
|
169
|
+
const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/.exec(src);
|
|
170
|
+
if (!block) {
|
|
171
|
+
// 没有 frontmatter:补一个最小头,绝不丢正文。
|
|
172
|
+
return `---\nlifecycle: historical\n---\n\n${src}`;
|
|
173
|
+
}
|
|
174
|
+
if (/^[ \t]*lifecycle[ \t]*:/m.test(block[1])) {
|
|
175
|
+
return src.replace(/^([ \t]*lifecycle[ \t]*:[ \t]*).+$/m, '$1historical');
|
|
176
|
+
}
|
|
177
|
+
return `---\n${block[1]}\nlifecycle: historical\n---\n${src.slice(block[0].length)}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 归档一张卡:移动到 topics/archive/<YYYY-MM>/,写 lifecycle:historical,
|
|
182
|
+
* 追加 moved_to 边,并重建 INDEX。失败不写半成品(先算后写)。
|
|
183
|
+
*/
|
|
184
|
+
export function archiveTurn(input = {}) {
|
|
185
|
+
const root = resolveRoot(input.memoryRoot ?? input.root);
|
|
186
|
+
const now = toDate(input.now);
|
|
187
|
+
const rel = String(input.rel ?? input.cardRel ?? input.path ?? '').trim();
|
|
188
|
+
if (rel === '') throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', 'archiveTurn 缺少相对卡路径');
|
|
189
|
+
const fromRel = rel.replace(/\\/g, '/');
|
|
190
|
+
if (!insideRoot(root, fromRel)) throw archiveError('E_HG_ARCHIVE_WRONG_VOLUME', `路径越界: ${fromRel}`);
|
|
191
|
+
const abs = path.join(root, fromRel);
|
|
192
|
+
if (!fs.existsSync(abs)) throw archiveError('E_HG_ARCHIVE_OFFLINE', `待归档卡不存在: ${fromRel}`);
|
|
193
|
+
if (input.dryRun === true) {
|
|
194
|
+
return { ok: true, dryRun: true, from: fromRel, to: null, moved: false, archived: false };
|
|
195
|
+
}
|
|
196
|
+
const month = dayString(now).slice(0, 7);
|
|
197
|
+
// B7b 裁决:staging 过期清退不走 archiveTurn(它写 topics/archive,是 L2 活跃卡归档);
|
|
198
|
+
// staging 清退由 archive-staging.mjs 自己写 `.longlive/archive/staging-expired/`。
|
|
199
|
+
const toRel = `${ARCHIVE_DIR_REL}/${month}/${path.basename(fromRel)}`;
|
|
200
|
+
const toAbs = path.join(root, toRel);
|
|
201
|
+
if (fs.existsSync(toAbs)) throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `归档目标已存在: ${toRel}`);
|
|
202
|
+
const text = fs.readFileSync(abs, 'utf8');
|
|
203
|
+
const next = ensureFrontmatterHistorical(text);
|
|
204
|
+
fs.mkdirSync(path.dirname(toAbs), { recursive: true });
|
|
205
|
+
fs.writeFileSync(toAbs, next, 'utf8');
|
|
206
|
+
fs.unlinkSync(abs);
|
|
207
|
+
const edge = appendEdge({
|
|
208
|
+
memoryRoot: root,
|
|
209
|
+
now,
|
|
210
|
+
edge: {
|
|
211
|
+
from: fromRel,
|
|
212
|
+
to: toRel,
|
|
213
|
+
type: 'moved_to',
|
|
214
|
+
evidence: [String(input.reason ?? 'archive')],
|
|
215
|
+
source: 'archive',
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
let index = null;
|
|
219
|
+
try {
|
|
220
|
+
index = rebuildMemoryIndex({ apply: true }, { memoryRoot: root, now });
|
|
221
|
+
} catch (error) {
|
|
222
|
+
throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `归档后 INDEX 重建失败: ${error?.code ?? error?.message ?? error}`);
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
ok: true,
|
|
226
|
+
moved: true,
|
|
227
|
+
archived: true,
|
|
228
|
+
from: fromRel,
|
|
229
|
+
to: toRel,
|
|
230
|
+
bytes: Buffer.byteLength(next, 'utf8'),
|
|
231
|
+
edge: edge.row,
|
|
232
|
+
indexSha: index?.contentHash ?? index?.sha256 ?? null,
|
|
233
|
+
indexPath: index?.indexPath ?? null,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function readArchiveState(root) {
|
|
238
|
+
const file = path.join(root, ARCHIVE_STATE_REL);
|
|
239
|
+
if (!fs.existsSync(file)) return { ok: true, state: { schema: 'archive-state/v1', lastRunAt: null, slots: {} }, corrupt: null };
|
|
240
|
+
try {
|
|
241
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
242
|
+
if (!parsed || parsed.schema !== 'archive-state/v1') return { ok: false, state: { schema: 'archive-state/v1', lastRunAt: null, slots: {} }, corrupt: 'schema' };
|
|
243
|
+
return { ok: true, state: parsed, corrupt: null };
|
|
244
|
+
} catch (error) {
|
|
245
|
+
return { ok: false, state: { schema: 'archive-state/v1', lastRunAt: null, slots: {} }, corrupt: String(error?.message ?? error) };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function writeArchiveState(root, state, now) {
|
|
250
|
+
const file = path.join(root, ARCHIVE_STATE_REL);
|
|
251
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
252
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
253
|
+
const text = JSON.stringify({ ...state, schema: 'archive-state/v1', updatedAt: isoStamp(now) }, null, 2) + '\n';
|
|
254
|
+
const fd = fs.openSync(tmp, 'w');
|
|
255
|
+
try {
|
|
256
|
+
fs.writeSync(fd, text);
|
|
257
|
+
fs.fsyncSync(fd);
|
|
258
|
+
} finally {
|
|
259
|
+
fs.closeSync(fd);
|
|
260
|
+
}
|
|
261
|
+
fs.renameSync(tmp, file);
|
|
262
|
+
return { path: file, sha256: sha256(text), bytes: Buffer.byteLength(text, 'utf8') };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* 槽位自动运行:按 slot 记录 lastRunAt,节流;未命中槽表不跑。
|
|
267
|
+
* 传入 rel/cardRel 时才做一次归档移动。
|
|
268
|
+
*/
|
|
269
|
+
export function maybeAutoRunArchive(input = {}) {
|
|
270
|
+
const root = resolveRoot(input.memoryRoot ?? input.root);
|
|
271
|
+
const now = toDate(input.now);
|
|
272
|
+
const slot = String(input.slot ?? 'manual');
|
|
273
|
+
if (!ARCHIVE_SLOTS.includes(slot)) throw archiveError('E_HG_ARCHIVE_MIGRATE_MISMATCH', `未知归档槽: ${slot}`);
|
|
274
|
+
const interval = Number.isFinite(input.minIntervalMs) ? Math.max(0, Number(input.minIntervalMs)) : ARCHIVE_MIN_INTERVAL_MS;
|
|
275
|
+
const read = input.lastRun && typeof input.lastRun === 'object' ? { ok: true, state: input.lastRun } : readArchiveState(root);
|
|
276
|
+
const last = read.state?.slots?.[slot] ?? read.state?.lastRunAt ?? null;
|
|
277
|
+
const lastMs = typeof last === 'string' ? Date.parse(last) : NaN;
|
|
278
|
+
if (Number.isFinite(lastMs) && now.getTime() - lastMs < interval) {
|
|
279
|
+
return { ok: true, ran: false, reason: 'throttled', slot, nextAt: new Date(lastMs + interval).toISOString() };
|
|
280
|
+
}
|
|
281
|
+
const rel = String(input.rel ?? input.cardRel ?? '').trim();
|
|
282
|
+
let result = null;
|
|
283
|
+
if (rel !== '') result = archiveTurn({ memoryRoot: root, now, rel, reason: `slot:${slot}` });
|
|
284
|
+
const state = {
|
|
285
|
+
...read.state,
|
|
286
|
+
lastRunAt: isoStamp(now),
|
|
287
|
+
slots: { ...(read.state?.slots ?? {}), [slot]: isoStamp(now) },
|
|
288
|
+
};
|
|
289
|
+
const write = writeArchiveState(root, state, now);
|
|
290
|
+
return { ok: true, ran: result !== null, reason: result ? 'moved' : 'no-target', slot, result, state: write };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* 写守卫:先确认可回滚备份,否则拒写。EPERM/EACCES 等 IO 拒绝一律转 E_HG_BACKUP。
|
|
295
|
+
* 传入 writer 时执行 writer();否则传入 path+content 时做原子写。
|
|
296
|
+
*/
|
|
297
|
+
export function guardWriteArchive(input = {}) {
|
|
298
|
+
const sessionPath = String(input.sessionPath ?? '').trim();
|
|
299
|
+
if (sessionPath === '') {
|
|
300
|
+
throw archiveError('E_HG_ARCHIVE_OFFLINE', '写守卫缺少 sessionPath:无法确认备份可用,拒写');
|
|
301
|
+
}
|
|
302
|
+
let backup;
|
|
303
|
+
try {
|
|
304
|
+
backup = ensureBackup(sessionPath, {
|
|
305
|
+
date: toDate(input.now),
|
|
306
|
+
sourceBuf: input.sourceBuf ?? null,
|
|
307
|
+
sha256: input.sha256 ?? null,
|
|
308
|
+
size: input.size ?? null,
|
|
309
|
+
});
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (error?.code === 'E_HG_BACKUP') throw error;
|
|
312
|
+
throw archiveError('E_HG_BACKUP', `备份不可用,拒写: ${error?.code ?? error?.message ?? error}`, { cause: error });
|
|
313
|
+
}
|
|
314
|
+
if (typeof input.writer === 'function') {
|
|
315
|
+
const written = input.writer(backup);
|
|
316
|
+
return { ok: true, backup, written };
|
|
317
|
+
}
|
|
318
|
+
const target = String(input.path ?? input.cardPath ?? '').trim();
|
|
319
|
+
if (target === '') return { ok: true, backup, written: false };
|
|
320
|
+
const file = path.isAbsolute(target) ? target : path.resolve(input.memoryRoot ?? process.cwd(), target);
|
|
321
|
+
const content = String(input.content ?? '');
|
|
322
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
323
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
324
|
+
fs.writeFileSync(tmp, content, 'utf8');
|
|
325
|
+
fs.renameSync(tmp, file);
|
|
326
|
+
return { ok: true, backup, written: true, path: file, bytes: Buffer.byteLength(content, 'utf8') };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** 别名:守卫 + 可注入 writer。 */
|
|
330
|
+
export function writeWithBackupArchive(input = {}, writer = null) {
|
|
331
|
+
const opts = writer ? { ...input, writer } : input;
|
|
332
|
+
return guardWriteArchive(opts);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** 离线队列:归档盘不可用时只追加账(≤1000 行 / 90 天),不抛给调用方。 */
|
|
336
|
+
export function enqueueArchiveQueue({ memoryRoot, now = new Date(), code, sha256: digest = null, archiveRoot = null, batch = 'C' } = {}) {
|
|
337
|
+
const root = resolveRoot(memoryRoot);
|
|
338
|
+
const at = toDate(now);
|
|
339
|
+
const file = path.join(root, ARCHIVE_QUEUE_REL);
|
|
340
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
341
|
+
const row = {
|
|
342
|
+
schema: 'archive-queue/v1',
|
|
343
|
+
at: isoStamp(at),
|
|
344
|
+
code: String(code ?? 'E_HG_ARCHIVE_OFFLINE'),
|
|
345
|
+
sha256: digest ? String(digest) : null,
|
|
346
|
+
archiveRoot: archiveRoot ? String(archiveRoot) : null,
|
|
347
|
+
batch: String(batch),
|
|
348
|
+
};
|
|
349
|
+
let lines = [];
|
|
350
|
+
if (fs.existsSync(file)) {
|
|
351
|
+
lines = fs.readFileSync(file, 'utf8').split('\n').filter((line) => line.trim() !== '');
|
|
352
|
+
}
|
|
353
|
+
const cutoff = at.getTime() - 90 * 24 * 60 * 60 * 1000;
|
|
354
|
+
lines = lines.filter((line) => {
|
|
355
|
+
try {
|
|
356
|
+
const parsed = JSON.parse(line);
|
|
357
|
+
const ms = Date.parse(parsed.at);
|
|
358
|
+
return !Number.isFinite(ms) || ms >= cutoff;
|
|
359
|
+
} catch {
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
lines.push(JSON.stringify(row));
|
|
364
|
+
const kept = lines.slice(-MAX_QUEUE_LINES);
|
|
365
|
+
fs.writeFileSync(file, `${kept.join('\n')}\n`, 'utf8');
|
|
366
|
+
return { ok: true, file, rows: kept.length, dropped: lines.length - kept.length + Math.max(0, lines.length - kept.length) };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ---------------------------------------------------------------------------
|
|
370
|
+
// 批次 C 出口门用的显式断言(M18)
|
|
371
|
+
// ---------------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
/** 产卡只允许写 staging;任何直写 topics/ 的调用都必须当场失败。 */
|
|
374
|
+
export function assertNoDirectTopicsWrite(rel, { allowAuto = false } = {}) {
|
|
375
|
+
const normalized = String(rel ?? '').replace(/\\/g, '/');
|
|
376
|
+
const topics = normalized.startsWith('topics/');
|
|
377
|
+
const staging = normalized.startsWith('.longlive/staging/');
|
|
378
|
+
if (topics && !(allowAuto && normalized.startsWith('topics/auto/'))) {
|
|
379
|
+
throw archiveError('E_HG_DISTILL_TOPICS_WRITE', `蒸馏产卡不得直写 topics/: ${normalized}`);
|
|
380
|
+
}
|
|
381
|
+
if (!staging && !topics) {
|
|
382
|
+
throw archiveError('E_HG_DISTILL_TOPICS_WRITE', `蒸馏产卡必须在 staging 下: ${normalized}`);
|
|
383
|
+
}
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// ---------------------------------------------------------------------------
|
|
388
|
+
// B7b 草案接线(2026-11-29):冷层归档状态机 + staging 过期归档
|
|
389
|
+
// ---------------------------------------------------------------------------
|
|
390
|
+
// 冷层迁移状态机(scan→approve#1→copy→verify→approve#2→migrated→才可删原件),
|
|
391
|
+
// 只 re-export 不改既有归档行为;janitor/维护槽经这些入口调用,绝不复制实现。
|
|
392
|
+
export {
|
|
393
|
+
COLD_MANIFEST_SCHEMA,
|
|
394
|
+
COLD_MANIFEST_REL,
|
|
395
|
+
COLD_INTENTS_REL,
|
|
396
|
+
COLD_PHASES,
|
|
397
|
+
COLD_CODES,
|
|
398
|
+
coldError,
|
|
399
|
+
planColdManifest,
|
|
400
|
+
readColdManifest,
|
|
401
|
+
readColdState,
|
|
402
|
+
writeColdState,
|
|
403
|
+
approveColdOnce,
|
|
404
|
+
copyColdFiles,
|
|
405
|
+
verifyColdCopies,
|
|
406
|
+
approveColdWithManifest,
|
|
407
|
+
markColdMigrated,
|
|
408
|
+
gateColdArchive,
|
|
409
|
+
gateColdDeletion,
|
|
410
|
+
beginColdDelete,
|
|
411
|
+
finishColdDelete,
|
|
412
|
+
reconcileColdIntents,
|
|
413
|
+
deleteOriginalAfterMigrate,
|
|
414
|
+
coldMovePlan,
|
|
415
|
+
} from './archive-cold-state.mjs';
|
|
@@ -21,8 +21,11 @@ import { spawn } from 'node:child_process';
|
|
|
21
21
|
import path from 'node:path';
|
|
22
22
|
import { fileURLToPath } from 'node:url';
|
|
23
23
|
import { createCapture } from './capture.js';
|
|
24
|
+
import { landTurn } from './land.mjs';
|
|
24
25
|
|
|
25
26
|
export const CAPTURE_DEBOUNCE_MS = 500;
|
|
27
|
+
/** 单会话每轮保留的 tool/call 记录上限(防无界增长)。 */
|
|
28
|
+
export const LAND_TOOL_CALL_LIMIT = 200;
|
|
26
29
|
const PACKAGE_ROOT = path.dirname(path.dirname(path.dirname(fileURLToPath(import.meta.url))));
|
|
27
30
|
|
|
28
31
|
// 进程退出兜底:只挂一个 exit 监听,把每个实例的"待采集会话"同步 flush 一次。
|
|
@@ -64,6 +67,18 @@ export function registerTurnCapture(ctx, options = {}) {
|
|
|
64
67
|
const bootstrapEnabled = options.bootstrap !== false;
|
|
65
68
|
const now = options.now;
|
|
66
69
|
const capture = createCapture({ memoryRoot, sessionRoots, now });
|
|
70
|
+
// M08:land 同步接线(DESIGN §2-B / §7-B)。默认开;可注入 land 实现做测试替身。
|
|
71
|
+
const landGateEnabled = options.landGate !== false;
|
|
72
|
+
const land = options.land && typeof options.land.landTurn === 'function' ? options.land : { landTurn };
|
|
73
|
+
const nowMsOf = () => {
|
|
74
|
+
try {
|
|
75
|
+
const value = typeof now === 'function' ? now() : null;
|
|
76
|
+
const date = value instanceof Date ? value : value ? new Date(value) : new Date();
|
|
77
|
+
return Number.isFinite(date.getTime()) ? date.getTime() : Date.now();
|
|
78
|
+
} catch {
|
|
79
|
+
return Date.now();
|
|
80
|
+
}
|
|
81
|
+
};
|
|
67
82
|
|
|
68
83
|
/** sessionId -> 状态 */
|
|
69
84
|
const states = new Map();
|
|
@@ -82,6 +97,12 @@ export function registerTurnCapture(ctx, options = {}) {
|
|
|
82
97
|
bootstrapAttemptAt: 0,
|
|
83
98
|
bootstrapWarned: false,
|
|
84
99
|
warned: false,
|
|
100
|
+
// M08:本轮 tool/call 记录 + 本轮起始时间(land 证据窗口)
|
|
101
|
+
toolCalls: [],
|
|
102
|
+
turnStartAt: null,
|
|
103
|
+
landLastAt: null,
|
|
104
|
+
landLastError: null,
|
|
105
|
+
landWarned: false,
|
|
85
106
|
};
|
|
86
107
|
states.set(sessionId, state);
|
|
87
108
|
}
|
|
@@ -174,14 +195,62 @@ export function registerTurnCapture(ctx, options = {}) {
|
|
|
174
195
|
}
|
|
175
196
|
};
|
|
176
197
|
|
|
198
|
+
// M08:turn/end 同步落盘判定(land.mjs 统一入口)。写失败重试 1 次;
|
|
199
|
+
// 仍失败只告警并记录 landLastError,不抛宿主(land-log 由下一轮/回放补偿)。
|
|
200
|
+
const runLand = (sessionId, state, turn) => {
|
|
201
|
+
if (!landGateEnabled) return null;
|
|
202
|
+
const sinceMs = Number.isFinite(state.turnStartAt) ? state.turnStartAt : nowMsOf();
|
|
203
|
+
const toolCalls = state.toolCalls.filter((call) => call.turn === turn);
|
|
204
|
+
const input = { memoryRoot, sessionId, turn, toolCalls, sinceMs, now: nowMsOf() };
|
|
205
|
+
let lastError = null;
|
|
206
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
207
|
+
try {
|
|
208
|
+
const result = land.landTurn(input);
|
|
209
|
+
state.landLastAt = nowMsOf();
|
|
210
|
+
state.landLastError = null;
|
|
211
|
+
return result;
|
|
212
|
+
} catch (error) {
|
|
213
|
+
lastError = error;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
state.landLastError = String(lastError?.code ?? lastError?.message ?? lastError);
|
|
217
|
+
if (warn && !state.landWarned) {
|
|
218
|
+
state.landWarned = true;
|
|
219
|
+
warn(`[longlive] 落盘判定失败(${sessionId} turn ${turn}):${state.landLastError} — 已重试 1 次`);
|
|
220
|
+
}
|
|
221
|
+
return { ok: false, code: state.landLastError };
|
|
222
|
+
};
|
|
223
|
+
|
|
177
224
|
ctx.on('session/event', (session, event) => {
|
|
178
225
|
try {
|
|
179
|
-
if (event?.type !== 'turn/end') return;
|
|
180
226
|
const sessionId = typeof session?.id === 'string' ? session.id : '';
|
|
181
227
|
if (sessionId === '') return;
|
|
182
228
|
const state = stateFor(sessionId);
|
|
229
|
+
const type = event?.type;
|
|
183
230
|
const turn = Number(event?.data?.turn);
|
|
184
|
-
if (
|
|
231
|
+
if (type === 'tool/call') {
|
|
232
|
+
// M08(DESIGN §2-B):守卫扩到 tool/call —— 只记录调用名与参数路径,不做落盘判定。
|
|
233
|
+
if (!Number.isFinite(turn)) return;
|
|
234
|
+
if (state.turnStartAt === null || turn > state.lastTurn) state.turnStartAt = nowMsOf();
|
|
235
|
+
if (turn > state.lastTurn) state.lastTurn = turn;
|
|
236
|
+
const tool = typeof event?.data?.tool === 'string'
|
|
237
|
+
? event.data.tool
|
|
238
|
+
: (typeof event?.data?.name === 'string' ? event.data.name : '');
|
|
239
|
+
const callPath = typeof event?.data?.path === 'string' ? event.data.path : null;
|
|
240
|
+
if (tool !== '') state.toolCalls.push({ turn, tool, path: callPath, at: nowMsOf() });
|
|
241
|
+
if (state.toolCalls.length > LAND_TOOL_CALL_LIMIT) {
|
|
242
|
+
state.toolCalls.splice(0, state.toolCalls.length - LAND_TOOL_CALL_LIMIT);
|
|
243
|
+
}
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (type !== 'turn/end') return;
|
|
247
|
+
if (Number.isFinite(turn)) {
|
|
248
|
+
state.lastTurn = Math.max(state.lastTurn, turn);
|
|
249
|
+
// 同步落盘判定(不走 500ms 去抖;失败重试 1 次,绝不抛宿主)。
|
|
250
|
+
runLand(sessionId, state, turn);
|
|
251
|
+
state.toolCalls = state.toolCalls.filter((call) => call.turn > turn);
|
|
252
|
+
state.turnStartAt = null;
|
|
253
|
+
}
|
|
185
254
|
schedule(sessionId);
|
|
186
255
|
} catch (error) {
|
|
187
256
|
if (warn) warn(`[longlive] 逐轮采集接线异常:${error?.message ?? error}`);
|
package/src/memory/capture.js
CHANGED
|
@@ -40,10 +40,46 @@ function nowDate(now) {
|
|
|
40
40
|
return value instanceof Date ? value : new Date(value);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/** journal 幂等命中计数(M09:同轮重复追加不增行,计数 +1)。 */
|
|
44
|
+
export const JOURNAL_IDEMPOTENT_REL = '.longlive/hardgate/journal-idempotent.json';
|
|
45
|
+
export const JOURNAL_IDEMPOTENT_SCHEMA = 'journal-idempotent/v1';
|
|
46
|
+
|
|
47
|
+
export function journalIdempotentPathOf(memoryRoot) {
|
|
48
|
+
return path.join(path.resolve(String(memoryRoot)), ...JOURNAL_IDEMPOTENT_REL.split('/'));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 日文件 journal 路径(M09:journal/YYYY-MM-DD.md;旧月文件 journal/YYYY-MM.md 只读保留为冷层)。
|
|
53
|
+
*/
|
|
43
54
|
export function journalPathOf(memoryRoot, atMs) {
|
|
44
55
|
const date = new Date(atMs);
|
|
45
|
-
const
|
|
46
|
-
return path.join(path.resolve(String(memoryRoot)), 'journal', `${
|
|
56
|
+
const day = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
57
|
+
return path.join(path.resolve(String(memoryRoot)), 'journal', `${day}.md`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function readJournalIdempotent(memoryRoot) {
|
|
61
|
+
const file = journalIdempotentPathOf(memoryRoot);
|
|
62
|
+
try {
|
|
63
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
64
|
+
return {
|
|
65
|
+
schema: JOURNAL_IDEMPOTENT_SCHEMA,
|
|
66
|
+
hits: Number.isInteger(parsed?.hits) ? parsed.hits : 0,
|
|
67
|
+
lastCap: typeof parsed?.lastCap === 'string' ? parsed.lastCap : null,
|
|
68
|
+
updatedAt: typeof parsed?.updatedAt === 'string' ? parsed.updatedAt : null,
|
|
69
|
+
};
|
|
70
|
+
} catch {
|
|
71
|
+
return { schema: JOURNAL_IDEMPOTENT_SCHEMA, hits: 0, lastCap: null, updatedAt: null };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function bumpJournalIdempotent(memoryRoot, cap, atMs) {
|
|
76
|
+
const file = journalIdempotentPathOf(memoryRoot);
|
|
77
|
+
const state = readJournalIdempotent(memoryRoot);
|
|
78
|
+
state.hits += 1;
|
|
79
|
+
state.lastCap = cap;
|
|
80
|
+
state.updatedAt = new Date(atMs).toISOString();
|
|
81
|
+
writeFileAtomic(file, `${JSON.stringify(state)}\n`);
|
|
82
|
+
return state.hits;
|
|
47
83
|
}
|
|
48
84
|
|
|
49
85
|
export function recordsPathOf(memoryRoot) {
|
|
@@ -58,8 +94,9 @@ export function writeFileAtomic(file, content) {
|
|
|
58
94
|
}
|
|
59
95
|
|
|
60
96
|
/**
|
|
61
|
-
* Append an idempotent journal line
|
|
62
|
-
* marker; the same key is written at
|
|
97
|
+
* Append an idempotent journal line (M09:日文件 journal/YYYY-MM-DD.md).
|
|
98
|
+
* `capKey` is hashed into a `<!-- cap:… -->` marker; the same key is written at
|
|
99
|
+
* most once (checked by substring scan). 命中重复时 journal 行不增,幂等计数 +1。
|
|
63
100
|
*/
|
|
64
101
|
export function appendJournalLine({ memoryRoot, atMs, text, capKey }) {
|
|
65
102
|
const file = journalPathOf(memoryRoot, atMs);
|
|
@@ -70,13 +107,15 @@ export function appendJournalLine({ memoryRoot, atMs, text, capKey }) {
|
|
|
70
107
|
} catch {
|
|
71
108
|
existing = '';
|
|
72
109
|
}
|
|
73
|
-
if (existing.includes(`<!-- cap:${cap} -->`))
|
|
110
|
+
if (existing.includes(`<!-- cap:${cap} -->`)) {
|
|
111
|
+
return { ok: true, written: false, file, cap, idempotentHits: bumpJournalIdempotent(memoryRoot, cap, atMs) };
|
|
112
|
+
}
|
|
74
113
|
const date = new Date(atMs);
|
|
75
114
|
const stamp = `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
|
|
76
115
|
const prefix = existing === '' ? '' : (existing.endsWith('\n') ? '' : '\n');
|
|
77
116
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
78
117
|
fs.appendFileSync(file, `${prefix}- **${stamp}** ${text} <!-- cap:${cap} -->\n`, 'utf8');
|
|
79
|
-
return { ok: true, written: true, file, cap };
|
|
118
|
+
return { ok: true, written: true, file, cap, idempotentHits: readJournalIdempotent(memoryRoot).hits };
|
|
80
119
|
}
|
|
81
120
|
|
|
82
121
|
/** Append one records.jsonl assertion (idempotent by record.id). */
|