@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,743 @@
|
|
|
1
|
+
// src/memory/land.mjs — 落盘检测与自动 journal 的唯一入口(agent 直写与 turn/end 自动落盘共用)。
|
|
2
|
+
//
|
|
3
|
+
// 契约来源:V0.5.2-MERGE-PLAN §11 N03 / DESIGN v0.5.2 §2-B / §7-B / KICKOFF-PLAN §2-B。
|
|
4
|
+
// land-log 相对路径 .longlive/hardgate/land-log.jsonl,schema 'land-gate/v1',行形状:
|
|
5
|
+
// { schema:'land-gate/v1', at, sessionId, turn, landed:boolean,
|
|
6
|
+
// evidence:[{kind:'tool',name,path?}|{kind:'file',path,mtimeDelta,sha}|{kind:'card'}],
|
|
7
|
+
// action:'none'|'auto-journal'|'auto-record', capKey, reason, gate:null, decision:null,
|
|
8
|
+
// sha, prevSha }
|
|
9
|
+
// capKey = `land:<sessionId>:<turn>`;同一 (sessionId,turn) 幂等,不重复写行;
|
|
10
|
+
// 幂等命中计数落在 head.idempotentHits(+1/次)。
|
|
11
|
+
// capture-host turn/end **同步**调用(不走 500ms 去抖);写失败由调用方重试 1 次。
|
|
12
|
+
// 只读 tool/call 记录 landed=false / action='none'。
|
|
13
|
+
//
|
|
14
|
+
// 链式 sha 与 gate-log 同构:body = {schema,at,sessionId,turn,gate,decision,reason,evidence}
|
|
15
|
+
// (canonical JSON:键名升序、无多余空白),head = {rows,tailSha,updatedAt,idempotentHits}。
|
|
16
|
+
//
|
|
17
|
+
// fail-closed:非法输入 / 坏行 / 锁占用一律抛结构化错误(error.code 必有),
|
|
18
|
+
// 不写空行、不默认通过、不空操作。
|
|
19
|
+
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
|
|
24
|
+
// 注意:这里**不** import capture.js。批 A 的双路由把 land.mjs 拉进 procedure.js 的
|
|
25
|
+
// import 链,而 capture.js → index.js → procedure.js 会形成模块环(PROCEDURES_DIR TDZ)。
|
|
26
|
+
// auto:land journal 行在本文件内按同一格式/同一幂等账本实现(appendAutoLandJournal)。
|
|
27
|
+
|
|
28
|
+
export const BATCH = 'B';
|
|
29
|
+
export const MODULE = 'memory/land.mjs';
|
|
30
|
+
export const UNIMPLEMENTED_CODE = 'E_HG_LAND_UNIMPLEMENTED';
|
|
31
|
+
export const SKELETON = Object.freeze({
|
|
32
|
+
version: '2.0.0',
|
|
33
|
+
failClosed: true,
|
|
34
|
+
batch: BATCH,
|
|
35
|
+
implemented: true,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
/** land-log 行 schema(计划 §11 冻结) */
|
|
39
|
+
export const LAND_LOG_SCHEMA = 'land-gate/v1';
|
|
40
|
+
/** land-log 相对 memoryRoot 的路径 */
|
|
41
|
+
export const LAND_LOG_REL = '.longlive/hardgate/land-log.jsonl';
|
|
42
|
+
/** 写锁相对 memoryRoot 的路径 */
|
|
43
|
+
export const LAND_LOCK_REL = '.longlive/memory/write.lock';
|
|
44
|
+
/** land-log 头(幂等去重)相对 memoryRoot 的路径 */
|
|
45
|
+
export const LAND_HEAD_REL = '.longlive/hardgate/land-log-head.json';
|
|
46
|
+
/** 工具证据相对 memoryRoot 的路径 */
|
|
47
|
+
export const TOOL_EVIDENCE_REL = '.longlive/hardgate/tool-evidence.jsonl';
|
|
48
|
+
/** 工具证据行 schema */
|
|
49
|
+
export const TOOL_EVIDENCE_SCHEMA = 'land-tool-evidence/v1';
|
|
50
|
+
/** 自动落盘 journal 行的标记 */
|
|
51
|
+
export const AUTO_LAND_MARK = 'auto:land';
|
|
52
|
+
/** 允许扫描的卡片目录 */
|
|
53
|
+
export const CARD_SCAN_DIRS = Object.freeze(['topics', 'procedures', 'journal']);
|
|
54
|
+
/** 视为写类调用的工具名(只读 memory_recall 不算落盘) */
|
|
55
|
+
export const WRITE_TOOL_NAMES = Object.freeze([
|
|
56
|
+
'memory_procedure',
|
|
57
|
+
'memory_reinforce',
|
|
58
|
+
'memory_forget',
|
|
59
|
+
'memory_consolidate',
|
|
60
|
+
'memory_index',
|
|
61
|
+
'memory_feedback',
|
|
62
|
+
'memory_wake',
|
|
63
|
+
]);
|
|
64
|
+
/** 只 bump strength 的工具:计入 tool 证据,但不作为写类证据(DESIGN §7-B) */
|
|
65
|
+
export const BUMP_TOOL_NAMES = Object.freeze(['memory_reinforce']);
|
|
66
|
+
/** 证据时间窗(turn/end 前多少毫秒内改写的文件算本轮) */
|
|
67
|
+
export const LAND_EVIDENCE_WINDOW_MS = 120000;
|
|
68
|
+
/** 锁判定为陈旧的时间(毫秒);超过即接管。 */
|
|
69
|
+
export const LAND_LOCK_STALE_MS = 10000;
|
|
70
|
+
/** head 中幂等命中计数字段名 */
|
|
71
|
+
export const IDEMPOTENT_HITS_FIELD = 'idempotentHits';
|
|
72
|
+
|
|
73
|
+
function landError(code, message, extra = {}) {
|
|
74
|
+
const error = new Error(`${code}: ${message}`);
|
|
75
|
+
error.name = 'HardgateLandError';
|
|
76
|
+
error.code = code;
|
|
77
|
+
error.module = MODULE;
|
|
78
|
+
error.batch = BATCH;
|
|
79
|
+
Object.assign(error, extra);
|
|
80
|
+
return error;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function sha256Hex(value) {
|
|
84
|
+
return crypto.createHash('sha256').update(value).digest('hex');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** DESIGN §2-A1 canonical JSON:递归键名升序、数组保序、无多余空白。 */
|
|
88
|
+
export function canonicalJson(value) {
|
|
89
|
+
const norm = (input) => {
|
|
90
|
+
if (input === null || typeof input === 'number' || typeof input === 'boolean') {
|
|
91
|
+
return Number.isNaN(input) ? null : input;
|
|
92
|
+
}
|
|
93
|
+
if (typeof input === 'string') return input;
|
|
94
|
+
if (Array.isArray(input)) return input.map(norm);
|
|
95
|
+
if (input !== null && typeof input === 'object') {
|
|
96
|
+
const out = {};
|
|
97
|
+
for (const key of Object.keys(input).sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))) {
|
|
98
|
+
if (input[key] === undefined) out[key] = null;
|
|
99
|
+
else out[key] = norm(input[key]);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
};
|
|
105
|
+
return JSON.stringify(norm(value));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function toIso(value) {
|
|
109
|
+
if (typeof value === 'string' && Number.isFinite(Date.parse(value))) return new Date(value).toISOString();
|
|
110
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString();
|
|
111
|
+
if (Number.isFinite(value)) return new Date(value).toISOString();
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function nowMsOf(now) {
|
|
116
|
+
if (now instanceof Date && Number.isFinite(now.getTime())) return now.getTime();
|
|
117
|
+
if (typeof now === 'function') {
|
|
118
|
+
const value = now();
|
|
119
|
+
const iso = toIso(value instanceof Date ? value : value);
|
|
120
|
+
if (iso) return Date.parse(iso);
|
|
121
|
+
}
|
|
122
|
+
if (Number.isFinite(now)) return now;
|
|
123
|
+
return Date.now();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function rootOf(memoryRoot) {
|
|
127
|
+
const root = String(memoryRoot ?? '').trim();
|
|
128
|
+
if (root === '') throw landError('E_HG_LAND_NO_MEMORY_ROOT', 'memoryRoot 不能为空');
|
|
129
|
+
return path.resolve(root);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function relFile(memoryRoot, rel) {
|
|
133
|
+
return path.join(rootOf(memoryRoot), ...rel.split('/'));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function localDayPath(root, atMs) {
|
|
137
|
+
const date = new Date(atMs);
|
|
138
|
+
const day = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
139
|
+
return path.join(root, 'journal', `${day}.md`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 幂等键:`land:<sessionId>:<turn>`。 */
|
|
143
|
+
export function landIdempotencyKey(sessionId, turn) {
|
|
144
|
+
const sid = String(sessionId ?? '').trim();
|
|
145
|
+
const n = Number(turn);
|
|
146
|
+
if (sid === '' || !Number.isInteger(n) || n < 0) {
|
|
147
|
+
throw landError('E_HG_LAND_BAD_INPUT', `非法幂等键输入 sessionId=${String(sessionId)} turn=${String(turn)}`);
|
|
148
|
+
}
|
|
149
|
+
return `land:${sid}:${n}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** land-log 绝对路径。 */
|
|
153
|
+
export function landLogPath(memoryRoot) {
|
|
154
|
+
return relFile(memoryRoot, LAND_LOG_REL);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 当天 journal 文件路径(YYYY-MM-DD.md;M09 日文件化,与 capture.js 一致)。 */
|
|
158
|
+
export function journalDayPathOf(memoryRoot, atMs = Date.now()) {
|
|
159
|
+
return localDayPath(rootOf(memoryRoot), atMs);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ---- auto:land journal(本地实现,避免 land.mjs → capture.js → index.js → procedure.js 模块环)----
|
|
163
|
+
|
|
164
|
+
/** journal 幂等命中计数账本(与 capture.js 共用同一文件/同一 schema)。 */
|
|
165
|
+
const JOURNAL_IDEMPOTENT_REL = '.longlive/hardgate/journal-idempotent.json';
|
|
166
|
+
const JOURNAL_IDEMPOTENT_SCHEMA = 'journal-idempotent/v1';
|
|
167
|
+
|
|
168
|
+
function sha1Short(text, length = 12) {
|
|
169
|
+
return crypto.createHash('sha1').update(text, 'utf8').digest('hex').slice(0, length);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function journalIdempotentFile(memoryRoot) {
|
|
173
|
+
return path.join(path.resolve(String(memoryRoot)), ...JOURNAL_IDEMPOTENT_REL.split('/'));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function readJournalIdempotent(memoryRoot) {
|
|
177
|
+
try {
|
|
178
|
+
const parsed = JSON.parse(fs.readFileSync(journalIdempotentFile(memoryRoot), 'utf8'));
|
|
179
|
+
return {
|
|
180
|
+
schema: JOURNAL_IDEMPOTENT_SCHEMA,
|
|
181
|
+
hits: Number.isInteger(parsed?.hits) ? parsed.hits : 0,
|
|
182
|
+
lastCap: typeof parsed?.lastCap === 'string' ? parsed.lastCap : null,
|
|
183
|
+
updatedAt: typeof parsed?.updatedAt === 'string' ? parsed.updatedAt : null,
|
|
184
|
+
};
|
|
185
|
+
} catch {
|
|
186
|
+
return { schema: JOURNAL_IDEMPOTENT_SCHEMA, hits: 0, lastCap: null, updatedAt: null };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function bumpJournalIdempotent(memoryRoot, cap, atMs) {
|
|
191
|
+
const state = readJournalIdempotent(memoryRoot);
|
|
192
|
+
state.hits += 1;
|
|
193
|
+
state.lastCap = cap;
|
|
194
|
+
state.updatedAt = new Date(atMs).toISOString();
|
|
195
|
+
writeJsonAtomic(journalIdempotentFile(memoryRoot), state);
|
|
196
|
+
return state.hits;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 追加一行幂等 `auto:land` journal(与 capture.js appendJournalLine 同格式):
|
|
201
|
+
* 同 capKey 的 `<!-- cap:… -->` 标记已在文件中时,journal 行不增、幂等计数 +1。
|
|
202
|
+
*/
|
|
203
|
+
export function appendAutoLandJournal({ memoryRoot, atMs, text, capKey }) {
|
|
204
|
+
const file = journalDayPathOf(memoryRoot, atMs);
|
|
205
|
+
const cap = sha1Short(`lifecycle:${capKey}`);
|
|
206
|
+
let existing = '';
|
|
207
|
+
try {
|
|
208
|
+
existing = fs.readFileSync(file, 'utf8');
|
|
209
|
+
} catch {
|
|
210
|
+
existing = '';
|
|
211
|
+
}
|
|
212
|
+
if (existing.includes(`<!-- cap:${cap} -->`)) {
|
|
213
|
+
return { ok: true, written: false, file, cap, idempotentHits: bumpJournalIdempotent(memoryRoot, cap, atMs) };
|
|
214
|
+
}
|
|
215
|
+
const date = new Date(atMs);
|
|
216
|
+
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')}`;
|
|
217
|
+
const prefix = existing === '' ? '' : (existing.endsWith('\n') ? '' : '\n');
|
|
218
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
219
|
+
fs.appendFileSync(file, `${prefix}- **${stamp}** ${text} <!-- cap:${cap} -->\n`, 'utf8');
|
|
220
|
+
return { ok: true, written: true, file, cap, idempotentHits: readJournalIdempotent(memoryRoot).hits };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 工具调用分类:只读 / 写类 / bump。 */
|
|
224
|
+
export function classifyToolCall(name) {
|
|
225
|
+
const tool = String(name ?? '').trim();
|
|
226
|
+
if (tool === '') return { name: '', kind: 'invalid', write: false, evidence: false };
|
|
227
|
+
if (BUMP_TOOL_NAMES.includes(tool)) return { name: tool, kind: 'bump', write: false, evidence: true };
|
|
228
|
+
if (WRITE_TOOL_NAMES.includes(tool)) return { name: tool, kind: 'write', write: true, evidence: true };
|
|
229
|
+
return { name: tool, kind: 'read', write: false, evidence: true };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 读 land-log;坏行抛 E_HG_LAND_LOG_CORRUPT(不静默丢弃)。 */
|
|
233
|
+
export function readLandLog(memoryRoot) {
|
|
234
|
+
const file = landLogPath(memoryRoot);
|
|
235
|
+
let text = '';
|
|
236
|
+
try {
|
|
237
|
+
text = fs.readFileSync(file, 'utf8');
|
|
238
|
+
} catch (error) {
|
|
239
|
+
if (error?.code === 'ENOENT') return [];
|
|
240
|
+
throw landError('E_HG_LAND_READ', `land-log 读取失败:${error?.message ?? error}`, { cause: error?.code });
|
|
241
|
+
}
|
|
242
|
+
const rows = [];
|
|
243
|
+
const lines = text.split('\n');
|
|
244
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
245
|
+
const line = lines[index].trim();
|
|
246
|
+
if (line === '') continue;
|
|
247
|
+
try {
|
|
248
|
+
rows.push(JSON.parse(line));
|
|
249
|
+
} catch (error) {
|
|
250
|
+
throw landError('E_HG_LAND_LOG_CORRUPT', `land-log 第 ${index + 1} 行不是合法 JSON`, { line: index + 1 });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return rows;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function readLandHead(memoryRoot) {
|
|
257
|
+
const file = relFile(memoryRoot, LAND_HEAD_REL);
|
|
258
|
+
try {
|
|
259
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
260
|
+
return {
|
|
261
|
+
rows: Number.isInteger(parsed?.rows) ? parsed.rows : 0,
|
|
262
|
+
tailSha: typeof parsed?.tailSha === 'string' ? parsed.tailSha : null,
|
|
263
|
+
updatedAt: typeof parsed?.updatedAt === 'string' ? parsed.updatedAt : null,
|
|
264
|
+
[IDEMPOTENT_HITS_FIELD]: Number.isInteger(parsed?.[IDEMPOTENT_HITS_FIELD]) ? parsed[IDEMPOTENT_HITS_FIELD] : 0,
|
|
265
|
+
};
|
|
266
|
+
} catch {
|
|
267
|
+
return { rows: 0, tailSha: null, updatedAt: null, [IDEMPOTENT_HITS_FIELD]: 0 };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function writeJsonAtomic(file, value) {
|
|
272
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
273
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
274
|
+
fs.writeFileSync(tmp, `${JSON.stringify(value)}\n`, 'utf8');
|
|
275
|
+
fs.renameSync(tmp, file);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function writeJsonlAtomic(file, rows) {
|
|
279
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
280
|
+
const body = rows.length === 0 ? '' : `${rows.map((row) => JSON.stringify(row)).join('\n')}\n`;
|
|
281
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
282
|
+
const fd = fs.openSync(tmp, 'w');
|
|
283
|
+
try {
|
|
284
|
+
fs.writeFileSync(fd, body, 'utf8');
|
|
285
|
+
fs.fsyncSync(fd);
|
|
286
|
+
} finally {
|
|
287
|
+
fs.closeSync(fd);
|
|
288
|
+
}
|
|
289
|
+
fs.renameSync(tmp, file);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** 链式 sha:与 hardgate gate-log 同构(body 只有冻结的 8 个字段)。 */
|
|
293
|
+
export function landRowSha(row) {
|
|
294
|
+
const body = {
|
|
295
|
+
schema: row?.schema ?? null,
|
|
296
|
+
at: row?.at ?? null,
|
|
297
|
+
sessionId: row?.sessionId ?? null,
|
|
298
|
+
turn: row?.turn ?? null,
|
|
299
|
+
gate: row?.gate ?? null,
|
|
300
|
+
decision: row?.decision ?? null,
|
|
301
|
+
reason: row?.reason ?? null,
|
|
302
|
+
evidence: row?.evidence ?? [],
|
|
303
|
+
};
|
|
304
|
+
return sha256Hex(canonicalJson(body));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function acquireLandLock(memoryRoot) {
|
|
308
|
+
const file = relFile(memoryRoot, LAND_LOCK_REL);
|
|
309
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
310
|
+
const attempt = () => {
|
|
311
|
+
const fd = fs.openSync(file, 'wx');
|
|
312
|
+
try {
|
|
313
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: new Date().toISOString(), module: MODULE }), 'utf8');
|
|
314
|
+
} finally {
|
|
315
|
+
fs.closeSync(fd);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
try {
|
|
319
|
+
attempt();
|
|
320
|
+
} catch (error) {
|
|
321
|
+
if (error?.code !== 'EEXIST') throw landError('E_HG_LAND_LOCK', `land 锁创建失败:${error?.message ?? error}`, { cause: error?.code });
|
|
322
|
+
let ageMs = 0;
|
|
323
|
+
try {
|
|
324
|
+
ageMs = Date.now() - fs.statSync(file).mtimeMs;
|
|
325
|
+
} catch {
|
|
326
|
+
ageMs = Number.POSITIVE_INFINITY;
|
|
327
|
+
}
|
|
328
|
+
if (ageMs > LAND_LOCK_STALE_MS) {
|
|
329
|
+
try {
|
|
330
|
+
fs.unlinkSync(file);
|
|
331
|
+
} catch {
|
|
332
|
+
/* 已被别人清掉 */
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
attempt();
|
|
336
|
+
} catch (retry) {
|
|
337
|
+
throw landError('E_HG_LAND_LOCKED', `land 锁占用(接管失败:${retry?.message ?? retry})`, { lock: file });
|
|
338
|
+
}
|
|
339
|
+
} else {
|
|
340
|
+
throw landError('E_HG_LAND_LOCKED', `land 锁占用(age=${Math.round(ageMs)}ms)`, { lock: file });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return () => {
|
|
344
|
+
try {
|
|
345
|
+
fs.unlinkSync(file);
|
|
346
|
+
} catch {
|
|
347
|
+
/* 已被移走 */
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** 追加一条 land-log 行(先拿锁,再整体 tmp→fsync→rename;非法输入抛错不写空行)。 */
|
|
353
|
+
export function appendLandLog(input = {}) {
|
|
354
|
+
const root = rootOf(input.memoryRoot);
|
|
355
|
+
const sessionId = String(input.sessionId ?? '').trim();
|
|
356
|
+
const turn = Number(input.turn);
|
|
357
|
+
const capKey = typeof input.capKey === 'string' && input.capKey !== ''
|
|
358
|
+
? input.capKey
|
|
359
|
+
: landIdempotencyKey(sessionId, turn);
|
|
360
|
+
if (sessionId === '' || !Number.isInteger(turn) || turn < 0) {
|
|
361
|
+
throw landError('E_HG_LAND_BAD_INPUT', 'appendLandLog 需要 sessionId + 非负整数 turn');
|
|
362
|
+
}
|
|
363
|
+
if (typeof input.landed !== 'boolean') throw landError('E_HG_LAND_BAD_INPUT', 'appendLandLog 需要 landed:boolean');
|
|
364
|
+
if (!Array.isArray(input.evidence)) throw landError('E_HG_LAND_BAD_INPUT', 'appendLandLog 需要 evidence 数组');
|
|
365
|
+
const action = typeof input.action === 'string' && input.action !== '' ? input.action : (input.landed ? 'auto-record' : 'none');
|
|
366
|
+
if (!['none', 'auto-journal', 'auto-record'].includes(action)) {
|
|
367
|
+
throw landError('E_HG_LAND_BAD_INPUT', `非法 action=${action}`);
|
|
368
|
+
}
|
|
369
|
+
const at = toIso(input.at ?? input.now ?? Date.now());
|
|
370
|
+
if (!at) throw landError('E_HG_LAND_BAD_INPUT', 'appendLandLog 需要合法时间');
|
|
371
|
+
const reason = typeof input.reason === 'string' ? input.reason : (input.landed ? 'write-evidence' : 'read-only');
|
|
372
|
+
|
|
373
|
+
const file = landLogPath(root);
|
|
374
|
+
const headFile = relFile(root, LAND_HEAD_REL);
|
|
375
|
+
const release = acquireLandLock(root);
|
|
376
|
+
try {
|
|
377
|
+
const rows = readLandLog(root);
|
|
378
|
+
const existing = rows.find((row) => row?.capKey === capKey);
|
|
379
|
+
if (existing) {
|
|
380
|
+
const head = readLandHead(root);
|
|
381
|
+
const idempotentHits = (Number.isInteger(head[IDEMPOTENT_HITS_FIELD]) ? head[IDEMPOTENT_HITS_FIELD] : 0) + 1;
|
|
382
|
+
const nextHead = {
|
|
383
|
+
rows: rows.length,
|
|
384
|
+
tailSha: rows.length ? rows[rows.length - 1].sha ?? null : null,
|
|
385
|
+
updatedAt: at,
|
|
386
|
+
[IDEMPOTENT_HITS_FIELD]: idempotentHits,
|
|
387
|
+
};
|
|
388
|
+
writeJsonAtomic(headFile, nextHead);
|
|
389
|
+
return { ok: true, written: false, duplicate: true, row: existing, idempotentHits, head: nextHead, file };
|
|
390
|
+
}
|
|
391
|
+
const prevSha = rows.length ? rows.at(-1)?.sha ?? null : null;
|
|
392
|
+
const row = {
|
|
393
|
+
schema: LAND_LOG_SCHEMA,
|
|
394
|
+
at,
|
|
395
|
+
sessionId,
|
|
396
|
+
turn,
|
|
397
|
+
gate: null,
|
|
398
|
+
decision: null,
|
|
399
|
+
reason,
|
|
400
|
+
evidence: input.evidence.map((item) => ({ ...item })),
|
|
401
|
+
landed: input.landed,
|
|
402
|
+
action,
|
|
403
|
+
capKey,
|
|
404
|
+
};
|
|
405
|
+
row.sha = landRowSha(row);
|
|
406
|
+
row.prevSha = prevSha;
|
|
407
|
+
const head = readLandHead(root);
|
|
408
|
+
writeJsonlAtomic(file, [...rows, row]);
|
|
409
|
+
const nextHead = {
|
|
410
|
+
rows: rows.length + 1,
|
|
411
|
+
tailSha: row.sha,
|
|
412
|
+
updatedAt: at,
|
|
413
|
+
[IDEMPOTENT_HITS_FIELD]: Number.isInteger(head[IDEMPOTENT_HITS_FIELD]) ? head[IDEMPOTENT_HITS_FIELD] : 0,
|
|
414
|
+
};
|
|
415
|
+
writeJsonAtomic(headFile, nextHead);
|
|
416
|
+
return { ok: true, written: true, duplicate: false, row, idempotentHits: nextHead[IDEMPOTENT_HITS_FIELD], head: nextHead, file };
|
|
417
|
+
} finally {
|
|
418
|
+
release();
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function walkMarkdownFiles(dir, out = []) {
|
|
423
|
+
let entries = [];
|
|
424
|
+
try {
|
|
425
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
426
|
+
} catch {
|
|
427
|
+
return out;
|
|
428
|
+
}
|
|
429
|
+
for (const entry of entries) {
|
|
430
|
+
if (entry.name.startsWith('.')) continue;
|
|
431
|
+
const abs = path.join(dir, entry.name);
|
|
432
|
+
if (entry.isDirectory()) walkMarkdownFiles(abs, out);
|
|
433
|
+
else if (entry.isFile() && /\.mdx?$/i.test(entry.name)) out.push(abs);
|
|
434
|
+
}
|
|
435
|
+
return out;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function sessionMarkerOf(text) {
|
|
439
|
+
const head = String(text ?? '').slice(0, 2000);
|
|
440
|
+
const match = head.match(/^session:\s*["']?([^"'\n]+?)["']?\s*$/m);
|
|
441
|
+
if (match) return match[1].trim();
|
|
442
|
+
const inline = head.match(/session:\s*["']?([A-Za-z0-9._:-]{2,})["']?/);
|
|
443
|
+
return inline ? inline[1].trim() : null;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** 扫描 sinceMs 之后被改写、且带本会话 session 标记的卡片(topics/procedures/journal)。 */
|
|
447
|
+
export function scanRecentCardWrites(input = {}) {
|
|
448
|
+
const root = rootOf(input.memoryRoot);
|
|
449
|
+
const sinceMs = Number.isFinite(input.sinceMs) ? input.sinceMs : 0;
|
|
450
|
+
const nowMs = nowMsOf(input.now);
|
|
451
|
+
const sessionId = String(input.sessionId ?? '').trim();
|
|
452
|
+
const limit = Number.isFinite(input.limit) ? Math.max(1, Math.min(200, input.limit)) : 50;
|
|
453
|
+
const evidence = [];
|
|
454
|
+
for (const dir of CARD_SCAN_DIRS) {
|
|
455
|
+
const base = path.join(root, dir);
|
|
456
|
+
for (const abs of walkMarkdownFiles(base)) {
|
|
457
|
+
let stat;
|
|
458
|
+
let text;
|
|
459
|
+
try {
|
|
460
|
+
stat = fs.statSync(abs);
|
|
461
|
+
if (!(stat.mtimeMs > sinceMs)) continue;
|
|
462
|
+
text = fs.readFileSync(abs, 'utf8');
|
|
463
|
+
} catch {
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
const marker = sessionMarkerOf(text);
|
|
467
|
+
const rel = path.relative(root, abs).split(path.sep).join('/');
|
|
468
|
+
const toolOutput = `/.longlive/tool-output/${String(input.turn ?? '')}/`;
|
|
469
|
+
if (marker !== null && sessionId !== '' && marker !== sessionId && !rel.includes(toolOutput)) continue;
|
|
470
|
+
evidence.push({
|
|
471
|
+
kind: 'file',
|
|
472
|
+
path: rel,
|
|
473
|
+
mtimeDelta: Math.max(0, Math.round(nowMs - stat.mtimeMs)),
|
|
474
|
+
sha: sha256Hex(Buffer.from(text, 'utf8')),
|
|
475
|
+
});
|
|
476
|
+
if (evidence.length >= limit) return evidence;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return evidence;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** 收集本轮落盘证据(tool / card / file 三类)。 */
|
|
483
|
+
export function collectLandEvidence(input = {}) {
|
|
484
|
+
const root = rootOf(input.memoryRoot);
|
|
485
|
+
const sessionId = String(input.sessionId ?? '').trim();
|
|
486
|
+
const turn = Number(input.turn);
|
|
487
|
+
if (sessionId === '' || !Number.isInteger(turn)) {
|
|
488
|
+
throw landError('E_HG_LAND_BAD_INPUT', 'collectLandEvidence 需要 sessionId + 整数 turn');
|
|
489
|
+
}
|
|
490
|
+
const nowMs = nowMsOf(input.now);
|
|
491
|
+
const sinceMs = Number.isFinite(input.sinceMs) ? input.sinceMs : nowMs - LAND_EVIDENCE_WINDOW_MS;
|
|
492
|
+
const toolCalls = Array.isArray(input.toolCalls) ? input.toolCalls : [];
|
|
493
|
+
const evidence = [];
|
|
494
|
+
const writeCalls = [];
|
|
495
|
+
for (const call of toolCalls) {
|
|
496
|
+
const name = String(call?.tool ?? call?.name ?? '').trim();
|
|
497
|
+
if (name === '') continue;
|
|
498
|
+
const classified = classifyToolCall(name);
|
|
499
|
+
const item = { kind: 'tool', name };
|
|
500
|
+
const callPath = typeof call?.path === 'string' && call.path !== '' ? call.path : null;
|
|
501
|
+
if (callPath) item.path = callPath;
|
|
502
|
+
evidence.push(item);
|
|
503
|
+
if (classified.write) writeCalls.push({ name, path: callPath });
|
|
504
|
+
}
|
|
505
|
+
for (const call of writeCalls) {
|
|
506
|
+
if (call.path) evidence.push({ kind: 'card', path: call.path, name: call.name });
|
|
507
|
+
}
|
|
508
|
+
const files = scanRecentCardWrites({ memoryRoot: root, sessionId, turn, sinceMs, now: nowMs });
|
|
509
|
+
evidence.push(...files);
|
|
510
|
+
const landed = writeCalls.length > 0 || files.length > 0;
|
|
511
|
+
return {
|
|
512
|
+
ok: true,
|
|
513
|
+
landed,
|
|
514
|
+
evidence,
|
|
515
|
+
toolCalls: toolCalls.length,
|
|
516
|
+
writeCalls: writeCalls.length,
|
|
517
|
+
fileWrites: files.length,
|
|
518
|
+
sinceMs,
|
|
519
|
+
action: landed ? 'auto-record' : 'none',
|
|
520
|
+
reason: landed ? 'write-evidence' : (evidence.length > 0 ? 'read-only' : 'no-evidence'),
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function toolEvidencePath(memoryRoot) {
|
|
525
|
+
return relFile(memoryRoot, TOOL_EVIDENCE_REL);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** 追加工具证据行(写类调用准入用;按 sessionId+turn+name+path 幂等)。 */
|
|
529
|
+
export function appendToolEvidence(input = {}) {
|
|
530
|
+
const root = rootOf(input.memoryRoot);
|
|
531
|
+
const sessionId = String(input.sessionId ?? '').trim();
|
|
532
|
+
const turn = Number(input.turn);
|
|
533
|
+
const name = String(input.name ?? '').trim();
|
|
534
|
+
if (sessionId === '' || !Number.isInteger(turn) || name === '') {
|
|
535
|
+
throw landError('E_HG_LAND_BAD_INPUT', 'appendToolEvidence 需要 sessionId + turn + name');
|
|
536
|
+
}
|
|
537
|
+
const at = toIso(input.at ?? input.now ?? Date.now());
|
|
538
|
+
const row = {
|
|
539
|
+
schema: TOOL_EVIDENCE_SCHEMA,
|
|
540
|
+
at,
|
|
541
|
+
sessionId,
|
|
542
|
+
turn,
|
|
543
|
+
name,
|
|
544
|
+
path: typeof input.path === 'string' ? input.path : null,
|
|
545
|
+
write: input.write !== false,
|
|
546
|
+
};
|
|
547
|
+
const file = toolEvidencePath(root);
|
|
548
|
+
const key = [sessionId, turn, name, row.path ?? ''].join('|');
|
|
549
|
+
const existing = readToolEvidence({ memoryRoot: root, sinceMs: 0, limit: 100000 });
|
|
550
|
+
if (existing.some((item) => [item.sessionId, item.turn, item.name, item.path ?? ''].join('|') === key)) {
|
|
551
|
+
return { ok: true, written: false, row, file };
|
|
552
|
+
}
|
|
553
|
+
const release = acquireLandLock(root);
|
|
554
|
+
try {
|
|
555
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
556
|
+
fs.appendFileSync(file, `${JSON.stringify(row)}\n`, 'utf8');
|
|
557
|
+
return { ok: true, written: true, row, file };
|
|
558
|
+
} finally {
|
|
559
|
+
release();
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** 读工具证据(sinceMs 之后;坏行抛 E_HG_LAND_LOG_CORRUPT)。 */
|
|
564
|
+
export function readToolEvidence(input = {}) {
|
|
565
|
+
const file = toolEvidencePath(rootOf(input.memoryRoot));
|
|
566
|
+
const sinceMs = Number.isFinite(input.sinceMs) ? input.sinceMs : 0;
|
|
567
|
+
const limit = Number.isFinite(input.limit) ? input.limit : 1000;
|
|
568
|
+
let text = '';
|
|
569
|
+
try {
|
|
570
|
+
text = fs.readFileSync(file, 'utf8');
|
|
571
|
+
} catch (error) {
|
|
572
|
+
if (error?.code === 'ENOENT') return [];
|
|
573
|
+
throw landError('E_HG_LAND_READ', `tool-evidence 读取失败:${error?.message ?? error}`);
|
|
574
|
+
}
|
|
575
|
+
const rows = [];
|
|
576
|
+
for (const line of text.split('\n')) {
|
|
577
|
+
if (line.trim() === '') continue;
|
|
578
|
+
let row;
|
|
579
|
+
try {
|
|
580
|
+
row = JSON.parse(line);
|
|
581
|
+
} catch {
|
|
582
|
+
throw landError('E_HG_LAND_LOG_CORRUPT', 'tool-evidence 存在非法 JSON 行');
|
|
583
|
+
}
|
|
584
|
+
const atMs = Date.parse(String(row?.at ?? ''));
|
|
585
|
+
if (Number.isFinite(atMs) && atMs >= sinceMs) rows.push(row);
|
|
586
|
+
if (rows.length >= limit) break;
|
|
587
|
+
}
|
|
588
|
+
return rows;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* 落盘判定 + 自动 journal 的唯一入口。
|
|
593
|
+
* 输入:{ memoryRoot, sessionId, turn, toolCalls?, sinceMs?, now? }
|
|
594
|
+
* 输出:{ ok, row, duplicate, idempotentHits, journal }
|
|
595
|
+
*/
|
|
596
|
+
export function landTurn(input = {}) {
|
|
597
|
+
const root = rootOf(input.memoryRoot);
|
|
598
|
+
const sessionId = String(input.sessionId ?? '').trim();
|
|
599
|
+
const turn = Number(input.turn);
|
|
600
|
+
if (sessionId === '' || !Number.isInteger(turn) || turn < 0) {
|
|
601
|
+
throw landError('E_HG_LAND_BAD_INPUT', `landTurn 需要 sessionId + 非负整数 turn(收到 ${sessionId || '<empty>'}:${String(input.turn)})`);
|
|
602
|
+
}
|
|
603
|
+
const nowMs = nowMsOf(input.now);
|
|
604
|
+
const sinceMs = Number.isFinite(input.sinceMs) ? input.sinceMs : nowMs - LAND_EVIDENCE_WINDOW_MS;
|
|
605
|
+
const collected = collectLandEvidence({ memoryRoot: root, sessionId, turn, toolCalls: input.toolCalls, sinceMs, now: nowMs });
|
|
606
|
+
const capKey = landIdempotencyKey(sessionId, turn);
|
|
607
|
+
const appended = appendLandLog({
|
|
608
|
+
memoryRoot: root,
|
|
609
|
+
sessionId,
|
|
610
|
+
turn,
|
|
611
|
+
landed: collected.landed,
|
|
612
|
+
evidence: collected.evidence,
|
|
613
|
+
action: collected.action,
|
|
614
|
+
reason: collected.reason,
|
|
615
|
+
capKey,
|
|
616
|
+
at: new Date(nowMs).toISOString(),
|
|
617
|
+
});
|
|
618
|
+
let journal = null;
|
|
619
|
+
if (!collected.landed) {
|
|
620
|
+
try {
|
|
621
|
+
journal = appendAutoLandJournal({
|
|
622
|
+
memoryRoot: root,
|
|
623
|
+
atMs: nowMs,
|
|
624
|
+
text: `${AUTO_LAND_MARK} · ${sessionId} · turn ${turn} · ${collected.evidence.length > 0 ? '只读/无落盘证据' : '无工具证据'}`,
|
|
625
|
+
capKey,
|
|
626
|
+
});
|
|
627
|
+
} catch (error) {
|
|
628
|
+
journal = { ok: false, code: error?.code ?? 'E_HG_LAND_JOURNAL', message: String(error?.message ?? error) };
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
if (collected.landed) {
|
|
632
|
+
for (const call of (Array.isArray(input.toolCalls) ? input.toolCalls : [])) {
|
|
633
|
+
const name = String(call?.tool ?? call?.name ?? '');
|
|
634
|
+
if (classifyToolCall(name).write) {
|
|
635
|
+
try {
|
|
636
|
+
appendToolEvidence({
|
|
637
|
+
memoryRoot: root,
|
|
638
|
+
sessionId,
|
|
639
|
+
turn,
|
|
640
|
+
name,
|
|
641
|
+
path: typeof call?.path === 'string' ? call.path : null,
|
|
642
|
+
at: new Date(nowMs).toISOString(),
|
|
643
|
+
});
|
|
644
|
+
} catch {
|
|
645
|
+
/* 工具证据是辅助账:不因它失败改判 landed(land-log 已是权威证据) */
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
return {
|
|
651
|
+
ok: true,
|
|
652
|
+
row: appended.row,
|
|
653
|
+
duplicate: appended.duplicate === true,
|
|
654
|
+
idempotentHits: appended.idempotentHits ?? 0,
|
|
655
|
+
journal,
|
|
656
|
+
evidence: collected.evidence,
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* 写守卫包装:备份失败 / 落盘失败时抛结构化错误,不写卡。
|
|
662
|
+
* 签名与既有实现一致:withWriteEvidence(toolName, fn, options)。
|
|
663
|
+
*
|
|
664
|
+
* 集成契约(批 A 的双路由按落盘门调用:`landWithWriteEvidence(name, legacy)`):
|
|
665
|
+
* - `fn` 同步时必须同步返回——工具入口不能从值变成 Promise;
|
|
666
|
+
* - `options.memoryRoot` 缺省(双路由现状)时不做备份/工具证据账,只透传调用结果;
|
|
667
|
+
* 落盘证据由 turn/end 的 landTurn 统一采集,此处不重复记账、不阻断工具。
|
|
668
|
+
*/
|
|
669
|
+
export function withWriteEvidence(toolName, fn, options = {}) {
|
|
670
|
+
const name = String(toolName ?? '').trim();
|
|
671
|
+
if (name === '' || typeof fn !== 'function') {
|
|
672
|
+
throw landError('E_HG_LAND_BAD_INPUT', 'withWriteEvidence(toolName, fn) 需要工具名与函数');
|
|
673
|
+
}
|
|
674
|
+
let root = null;
|
|
675
|
+
try {
|
|
676
|
+
root = rootOf(options.memoryRoot);
|
|
677
|
+
} catch {
|
|
678
|
+
root = null;
|
|
679
|
+
}
|
|
680
|
+
const rel = typeof options.path === 'string' && options.path !== '' ? options.path.split(path.sep).join('/') : null;
|
|
681
|
+
let backup = null;
|
|
682
|
+
if (root && rel) {
|
|
683
|
+
const target = path.resolve(root, rel);
|
|
684
|
+
if (target.startsWith(root) && fs.existsSync(target)) {
|
|
685
|
+
try {
|
|
686
|
+
const content = fs.readFileSync(target);
|
|
687
|
+
const backupDir = path.join(root, '.longlive', 'hardgate', 'write-backup');
|
|
688
|
+
fs.mkdirSync(backupDir, { recursive: true });
|
|
689
|
+
backup = path.join(backupDir, `${sha256Hex(content).slice(0, 16)}-${path.basename(target)}`);
|
|
690
|
+
fs.writeFileSync(backup, content);
|
|
691
|
+
} catch (error) {
|
|
692
|
+
throw landError('E_HG_LAND_WRITE_BACKUP', `写前备份失败,拒绝写卡:${error?.message ?? error}`);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const recordEvidence = () => {
|
|
697
|
+
if (!root || !rel) return;
|
|
698
|
+
try {
|
|
699
|
+
appendToolEvidence({
|
|
700
|
+
memoryRoot: root,
|
|
701
|
+
sessionId: options.sessionId,
|
|
702
|
+
turn: options.turn,
|
|
703
|
+
name,
|
|
704
|
+
path: rel,
|
|
705
|
+
write: true,
|
|
706
|
+
at: options.now,
|
|
707
|
+
});
|
|
708
|
+
} catch {
|
|
709
|
+
/* 工具证据辅助账 */
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
const rollback = () => {
|
|
713
|
+
if (!backup || !root || !rel) return;
|
|
714
|
+
try {
|
|
715
|
+
fs.copyFileSync(backup, path.resolve(root, rel));
|
|
716
|
+
} catch {
|
|
717
|
+
/* 恢复尽力而为;原错误优先 */
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
let result;
|
|
721
|
+
try {
|
|
722
|
+
result = fn();
|
|
723
|
+
} catch (error) {
|
|
724
|
+
rollback();
|
|
725
|
+
throw error;
|
|
726
|
+
}
|
|
727
|
+
if (result && typeof result.then === 'function') {
|
|
728
|
+
return result.then(
|
|
729
|
+
(value) => {
|
|
730
|
+
recordEvidence();
|
|
731
|
+
return value;
|
|
732
|
+
},
|
|
733
|
+
(error) => {
|
|
734
|
+
rollback();
|
|
735
|
+
throw error;
|
|
736
|
+
},
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
recordEvidence();
|
|
740
|
+
return result;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
export const __test = { canonicalJson, landRowSha, sha256Hex };
|