@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
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
verifyProtectedFile,
|
|
34
34
|
writeProtectedJson,
|
|
35
35
|
} from '../role/writeprotect.js';
|
|
36
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
36
37
|
|
|
37
38
|
export const FRAME_SCHEMA = 'working-frame/v1';
|
|
38
39
|
export const FRAME_TTL_MS = 30 * 60 * 1000;
|
|
@@ -40,6 +41,17 @@ export const TOPIC_SIMILARITY_THRESHOLD = 0.35;
|
|
|
40
41
|
export const INJECTION_ORDER = Object.freeze(['boot', 'shared', 'working', 'recall']);
|
|
41
42
|
export const CLOCK_TOLERANCE_MS = 5000;
|
|
42
43
|
|
|
44
|
+
// —— D12 工作帧四字段(§4 ①;阈值只来自计划:80/80/5/80/540/300/4 KiB/256 KiB)——
|
|
45
|
+
export const WORKING_FIELDS = Object.freeze(['lastUserTask', 'nextStep', 'touchedFiles', 'lastDecision']);
|
|
46
|
+
export const WORKING_FIELD_MAX_CHARS = 80;
|
|
47
|
+
export const WORKING_TOUCHED_FILES_MAX = 5;
|
|
48
|
+
export const WORKING_TOUCHED_TOTAL_CHARS = 300;
|
|
49
|
+
export const WORKING_FOCUS_TOTAL_CHARS = 540;
|
|
50
|
+
export const WORKING_INJECT_MAX_CHARS = 300;
|
|
51
|
+
export const WORKING_UNSET = Object.freeze({ unset: true });
|
|
52
|
+
export const WORKING_AUDIT_MIGRATE_BYTES = 256 * 1024;
|
|
53
|
+
export const WORKING_AUDIT_ROTATE_MAX = 3;
|
|
54
|
+
|
|
43
55
|
export class WorkingFrameError extends Error {
|
|
44
56
|
constructor(code, message, detail = undefined) {
|
|
45
57
|
super(message);
|
|
@@ -139,6 +151,104 @@ export function entitiesFromText(text, limit = 8) {
|
|
|
139
151
|
return out;
|
|
140
152
|
}
|
|
141
153
|
|
|
154
|
+
/**
|
|
155
|
+
* D12: real-user message filter — injected blocks (auto recall / boot / shared) never
|
|
156
|
+
* become the working task. Keeps the 4-field extraction honest.
|
|
157
|
+
*/
|
|
158
|
+
export function isRealUserMessage(message) {
|
|
159
|
+
if (!isHumanMessage(message)) return false;
|
|
160
|
+
if (isInjectedMessage(message)) return false;
|
|
161
|
+
return !textOfMessage(message).trimStart().startsWith(AUTO_TEXT_MARK);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function clipWorkingText(value, max = WORKING_FIELD_MAX_CHARS) {
|
|
165
|
+
const text = String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
166
|
+
if (text === '') return '';
|
|
167
|
+
return text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}…`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const WORKING_TOOL_VERBS = 'read|write|edit|open|update|patch|apply_patch|create|delete|glob|grep|ls|stat';
|
|
171
|
+
const WORKING_TOOL_RE = new RegExp(`(?:^|\\s)(?:${WORKING_TOOL_VERBS})\\s+(?:"([^"]+)"|'([^']+)'|(\\S+))`, 'gi');
|
|
172
|
+
|
|
173
|
+
function looksLikePath(token) {
|
|
174
|
+
const value = String(token ?? '').trim().replace(/^[('"\[]+|[)'".,;:\]]+$/g, '');
|
|
175
|
+
if (value === '' || value.length > 200) return false;
|
|
176
|
+
return /[\\/]/.test(value) || /\.(?:js|mjs|cjs|ts|tsx|jsx|json|jsonl|md|txt|ps1|py|css|html|yml|yaml)$/i.test(value);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** touchedFiles: basenames of paths passed to tool verbs, first-appearance order, ≤5, total ≤300. */
|
|
180
|
+
export function touchedFilesFromMessages(messages) {
|
|
181
|
+
const out = [];
|
|
182
|
+
const seen = new Set();
|
|
183
|
+
let total = 0;
|
|
184
|
+
for (const message of Array.isArray(messages) ? messages : []) {
|
|
185
|
+
if (!message || typeof message !== 'object') continue;
|
|
186
|
+
if (message.role !== 'tool' && message.role !== 'toolResult') continue;
|
|
187
|
+
const text = textOfMessage(message);
|
|
188
|
+
if (text === '') continue;
|
|
189
|
+
WORKING_TOOL_RE.lastIndex = 0;
|
|
190
|
+
let match;
|
|
191
|
+
while ((match = WORKING_TOOL_RE.exec(text)) !== null) {
|
|
192
|
+
const target = match[1] ?? match[2] ?? match[3] ?? '';
|
|
193
|
+
if (!looksLikePath(target)) continue;
|
|
194
|
+
const base = String(target).replace(/[\\/]+$/, '').split(/[\\/]/).pop();
|
|
195
|
+
if (!base || seen.has(base)) continue;
|
|
196
|
+
const cost = base.length + (out.length > 0 ? 1 : 0);
|
|
197
|
+
if (out.length >= WORKING_TOUCHED_FILES_MAX) break;
|
|
198
|
+
if (total + cost > WORKING_TOUCHED_TOTAL_CHARS) break;
|
|
199
|
+
seen.add(base);
|
|
200
|
+
out.push(base);
|
|
201
|
+
total += cost;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function extractWorkingLine(text, pattern) {
|
|
208
|
+
const match = pattern.exec(String(text ?? ''));
|
|
209
|
+
return match ? clipWorkingText(match[1]) : '';
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const NEXT_STEP_RE = /(?:下一步|接下来|接着|然后)[::,,、\s]*([^\n。;;]{1,120})/;
|
|
213
|
+
const DECISION_RE = /(?:决定|决策|采用|选定|选择)[::,,、\s]*([^\n。;;]{1,120})/;
|
|
214
|
+
|
|
215
|
+
/** Pure extractor for the 4 working fields (null/absent → explicit unset marker, never ''). */
|
|
216
|
+
export function extractWorkingFields(messages = []) {
|
|
217
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
218
|
+
let lastUser = null;
|
|
219
|
+
let lastAssistant = null;
|
|
220
|
+
for (const message of list) {
|
|
221
|
+
if (isRealUserMessage(message)) lastUser = message;
|
|
222
|
+
const role = String(message?.role ?? '');
|
|
223
|
+
if (role === 'assistant' || role === 'ai') lastAssistant = message;
|
|
224
|
+
}
|
|
225
|
+
const userText = lastUser ? textOfMessage(lastUser) : '';
|
|
226
|
+
const assistantText = lastAssistant ? textOfMessage(lastAssistant) : '';
|
|
227
|
+
return {
|
|
228
|
+
lastUserTask: clipWorkingText(userText) || WORKING_UNSET,
|
|
229
|
+
nextStep: extractWorkingLine(assistantText, NEXT_STEP_RE) || WORKING_UNSET,
|
|
230
|
+
touchedFiles: touchedFilesFromMessages(list),
|
|
231
|
+
lastDecision: extractWorkingLine(assistantText, DECISION_RE) || WORKING_UNSET,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function normalizeWorkingFields(input) {
|
|
236
|
+
const source = input && typeof input === 'object' ? input : {};
|
|
237
|
+
return {
|
|
238
|
+
lastUserTask: source.lastUserTask ?? WORKING_UNSET,
|
|
239
|
+
nextStep: source.nextStep ?? WORKING_UNSET,
|
|
240
|
+
touchedFiles: Array.isArray(source.touchedFiles) ? source.touchedFiles.slice(0, WORKING_TOUCHED_FILES_MAX) : (source.touchedFiles ?? WORKING_UNSET),
|
|
241
|
+
lastDecision: source.lastDecision ?? WORKING_UNSET,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function workingFieldText(value) {
|
|
246
|
+
if (value === undefined || value === null) return '';
|
|
247
|
+
if (Array.isArray(value)) return value.filter((item) => item !== undefined && item !== null && item !== WORKING_UNSET).join('、');
|
|
248
|
+
if (typeof value === 'object') return value.unset === true ? '' : '';
|
|
249
|
+
return String(value).trim();
|
|
250
|
+
}
|
|
251
|
+
|
|
142
252
|
/**
|
|
143
253
|
* EA-05: real per-turn focus updater — extracts the last human message and records
|
|
144
254
|
* this turn's focus into the frame stack (so the NEXT turn can inject it).
|
|
@@ -151,14 +261,16 @@ export function updateFrameFromMessages({ store, sessionId, messages, turn = 0 }
|
|
|
151
261
|
}
|
|
152
262
|
const query = human ? textOfMessage(human) : '';
|
|
153
263
|
if (query.trim() === '') return { ok: false, code: 'E_NO_HUMAN_MESSAGE' };
|
|
264
|
+
const fields = extractWorkingFields(list);
|
|
154
265
|
const result = store.updateFocus({
|
|
155
266
|
sessionId,
|
|
156
267
|
entities: entitiesFromText(query),
|
|
157
268
|
anchors: [],
|
|
158
269
|
turn: Number.isInteger(turn) && turn >= 0 ? turn : 0,
|
|
159
270
|
query,
|
|
271
|
+
fields,
|
|
160
272
|
});
|
|
161
|
-
return { ...result, query };
|
|
273
|
+
return { ...result, query, fields };
|
|
162
274
|
}
|
|
163
275
|
|
|
164
276
|
/**
|
|
@@ -251,8 +363,94 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
251
363
|
return bootWall + elapsed;
|
|
252
364
|
}
|
|
253
365
|
|
|
366
|
+
// §4 ①:skip 事件内存级去重(同一 session+code 只落一次,防刷盘);门事件一律走生产 gate-log。
|
|
367
|
+
const skipNotified = new Set();
|
|
368
|
+
function gateEvent(sessionId, event, decision, reason, detail = {}) {
|
|
369
|
+
try {
|
|
370
|
+
appendGateLog(memoryRoot, {
|
|
371
|
+
sessionId: sessionId ?? null,
|
|
372
|
+
turn: Number.isInteger(detail.turn) ? detail.turn : 0,
|
|
373
|
+
gate: event,
|
|
374
|
+
decision,
|
|
375
|
+
reason,
|
|
376
|
+
evidence: Array.isArray(detail.evidence) ? detail.evidence : [],
|
|
377
|
+
});
|
|
378
|
+
} catch {
|
|
379
|
+
/* gate log must never block injection */
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
function notifySkip(sessionId, code, detail = {}) {
|
|
383
|
+
const key = `${safeSessionId(sessionId)}|${code}`;
|
|
384
|
+
if (skipNotified.has(key)) return;
|
|
385
|
+
skipNotified.add(key);
|
|
386
|
+
// B3 C3:门事件不允许写 skip(gate-log 当日 skip 必须为 0)。帧过期是告警事实,
|
|
387
|
+
// 记 warn + 稳定原因码;事件名同步改成 hg.d12.frame-expired(旧名不再出现)。
|
|
388
|
+
gateEvent(sessionId, 'hg.d12.frame-expired', 'warn', String(code), { turn: detail.turn ?? 0, evidence: [] });
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// §4 ①:audit.jsonl 首启迁移(>256 KiB 先复制+记录副本 sha,再按行切 ≤256 KiB 分片,rotate≤3)。
|
|
392
|
+
// 失败 fail closed:原 live 文件一字不动。
|
|
393
|
+
let auditMigrated = false;
|
|
394
|
+
function sha256Bytes(buffer) {
|
|
395
|
+
return crypto.createHash('sha256').update(buffer).digest('hex');
|
|
396
|
+
}
|
|
397
|
+
function migrateAuditOnce() {
|
|
398
|
+
if (auditMigrated) return;
|
|
399
|
+
auditMigrated = true;
|
|
400
|
+
try {
|
|
401
|
+
const stat = fs.statSync(paths.audit);
|
|
402
|
+
const liveBytes = stat.size;
|
|
403
|
+
if (!stat.isFile() || liveBytes <= WORKING_AUDIT_MIGRATE_BYTES) return;
|
|
404
|
+
const live = fs.readFileSync(paths.audit);
|
|
405
|
+
const liveSha = sha256Bytes(live);
|
|
406
|
+
const stamp = nowIso(now).replace(/[:.]/g, '-');
|
|
407
|
+
const copyFile = path.join(paths.dir, `audit.migrate-${stamp}.jsonl`);
|
|
408
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
409
|
+
fs.copyFileSync(paths.audit, copyFile);
|
|
410
|
+
const copyBuffer = fs.readFileSync(copyFile);
|
|
411
|
+
const copyBytes = copyBuffer.length;
|
|
412
|
+
const copySha = sha256Bytes(copyBuffer);
|
|
413
|
+
if (copySha !== liveSha) return; // fail closed: copy mismatch, keep original
|
|
414
|
+
const chunks = [];
|
|
415
|
+
let current = '';
|
|
416
|
+
let currentBytes = 0;
|
|
417
|
+
for (const line of live.toString('utf8').split('\n')) {
|
|
418
|
+
if (line === '') continue;
|
|
419
|
+
const lineBytes = Buffer.byteLength(line, 'utf8') + 1;
|
|
420
|
+
if (current !== '' && currentBytes + lineBytes > WORKING_AUDIT_MIGRATE_BYTES) {
|
|
421
|
+
chunks.push(current);
|
|
422
|
+
current = `${line}\n`;
|
|
423
|
+
currentBytes = lineBytes;
|
|
424
|
+
} else {
|
|
425
|
+
current += `${line}\n`;
|
|
426
|
+
currentBytes += lineBytes;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (current !== '') chunks.push(current);
|
|
430
|
+
if (chunks.length < 2) return;
|
|
431
|
+
const keep = chunks.slice(-WORKING_AUDIT_ROTATE_MAX);
|
|
432
|
+
for (let index = 0; index < keep.length; index += 1) {
|
|
433
|
+
const isLive = index === keep.length - 1;
|
|
434
|
+
const name = isLive ? 'audit.jsonl' : `audit.${keep.length - 1 - index}.jsonl`;
|
|
435
|
+
writeAtomic(path.join(paths.dir, name), keep[index]);
|
|
436
|
+
}
|
|
437
|
+
for (const name of fs.readdirSync(paths.dir)) {
|
|
438
|
+
const match = /^audit\.(\d+)\.jsonl$/.exec(name);
|
|
439
|
+
if (match && Number(match[1]) >= WORKING_AUDIT_ROTATE_MAX) {
|
|
440
|
+
try { fs.unlinkSync(path.join(paths.dir, name)); } catch { /* rotation cleanup best effort */ }
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
gateEvent(null, 'hg.working.audit.migrate', 'warn', 'audit-migrated', {
|
|
444
|
+
evidence: [`liveBytes=${liveBytes}`, `liveSha=${liveSha}`, `copyBytes=${copyBytes}`, `copySha=${copySha}`],
|
|
445
|
+
});
|
|
446
|
+
} catch {
|
|
447
|
+
/* migration is fail-closed: leave the original audit file untouched */
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
254
451
|
function audit(event, detail) {
|
|
255
452
|
try {
|
|
453
|
+
migrateAuditOnce();
|
|
256
454
|
fs.mkdirSync(path.dirname(paths.audit), { recursive: true });
|
|
257
455
|
fs.appendFileSync(paths.audit, `${JSON.stringify({ schema: 'working-frame-audit/v1', at: nowIso(now), event, ...detail })}\n`, 'utf8');
|
|
258
456
|
} catch {
|
|
@@ -319,7 +517,7 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
319
517
|
return { ok: true, path: file, frame: value };
|
|
320
518
|
}
|
|
321
519
|
|
|
322
|
-
function newFrame({ sessionId, entities = [], anchors = [], turn = 0, frameNo = 1, prevFrameId = null }) {
|
|
520
|
+
function newFrame({ sessionId, entities = [], anchors = [], turn = 0, frameNo = 1, prevFrameId = null, fields = null }) {
|
|
323
521
|
const wall = nowMs(now);
|
|
324
522
|
return {
|
|
325
523
|
schema: FRAME_SCHEMA,
|
|
@@ -330,6 +528,7 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
330
528
|
focus: {
|
|
331
529
|
entities: [...new Set(entities.filter((entity) => typeof entity === 'string' && entity.trim() !== ''))].slice(0, 30),
|
|
332
530
|
anchors: Array.isArray(anchors) ? anchors.slice(0, 20) : [],
|
|
531
|
+
...normalizeWorkingFields(fields),
|
|
333
532
|
},
|
|
334
533
|
ttlMs,
|
|
335
534
|
lastUsedAtMs: wall,
|
|
@@ -400,7 +599,7 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
400
599
|
}
|
|
401
600
|
}
|
|
402
601
|
|
|
403
|
-
function updateFocusUnlocked({ sessionId, entities = [], anchors = [], turn = 0, query = '' }) {
|
|
602
|
+
function updateFocusUnlocked({ sessionId, entities = [], anchors = [], turn = 0, query = '', fields = null }) {
|
|
404
603
|
const loaded = load(sessionId);
|
|
405
604
|
const wall = nowMs(now);
|
|
406
605
|
// §16.8 A:帧被篡改/缺侧车 → fail closed,绝不把坏帧当有效帧继续写。
|
|
@@ -408,7 +607,7 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
408
607
|
return { ok: false, code: loaded.code ?? 'E_INTEGRITY_TAMPER', message: loaded.message ?? '帧完整性校验失败' };
|
|
409
608
|
}
|
|
410
609
|
if (!loaded.present) {
|
|
411
|
-
const frame = newFrame({ sessionId: safeSessionId(sessionId), entities, anchors, turn, frameNo: 1 });
|
|
610
|
+
const frame = newFrame({ sessionId: safeSessionId(sessionId), entities, anchors, turn, frameNo: 1, fields });
|
|
412
611
|
save(sessionId, frame);
|
|
413
612
|
return { ok: true, switched: true, reason: 'new', frame };
|
|
414
613
|
}
|
|
@@ -427,16 +626,22 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
427
626
|
turn,
|
|
428
627
|
frameNo: (current.frameNo ?? 1) + 1,
|
|
429
628
|
prevFrameId: current.frameId ?? null,
|
|
629
|
+
fields,
|
|
430
630
|
});
|
|
431
631
|
save(sessionId, frame);
|
|
432
632
|
return { ok: true, switched: true, reason: expired ? 'expired' : 'topic-switch', archiveFile, frame };
|
|
433
633
|
}
|
|
434
634
|
const mergedEntities = [...new Set([...(current.focus?.entities ?? []), ...entities])].slice(0, 30);
|
|
435
635
|
const mergedAnchors = [...(current.focus?.anchors ?? []), ...anchors];
|
|
636
|
+
const fieldSource = fields ?? current.focus ?? {};
|
|
436
637
|
const next = {
|
|
437
638
|
...current,
|
|
438
639
|
turnRange: [current.turnRange?.[0] ?? 0, Math.max(current.turnRange?.[1] ?? 0, Number.isInteger(turn) ? turn : 0)],
|
|
439
|
-
focus: {
|
|
640
|
+
focus: {
|
|
641
|
+
entities: mergedEntities,
|
|
642
|
+
anchors: mergedAnchors.slice(0, 20),
|
|
643
|
+
...normalizeWorkingFields(fieldSource),
|
|
644
|
+
},
|
|
440
645
|
lastUsedAtMs: wall,
|
|
441
646
|
lastUsedAt: new Date(wall).toISOString(),
|
|
442
647
|
updatedAt: new Date(wall).toISOString(),
|
|
@@ -447,22 +652,67 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
447
652
|
return { ok: true, switched: false, reason: 'merged', frame: next };
|
|
448
653
|
}
|
|
449
654
|
|
|
655
|
+
/**
|
|
656
|
+
* D12 injection renderer: 4 fields on top of focus/anchors, ≤300 chars.
|
|
657
|
+
* Drop order (whole item): lastUserTask → nextStep → touchedFiles → lastDecision.
|
|
658
|
+
*/
|
|
659
|
+
function renderInjectionText(frame) {
|
|
660
|
+
const focus = frame?.focus ?? {};
|
|
661
|
+
const entities = (focus.entities ?? []).slice(0, 8);
|
|
662
|
+
const turnRange = Array.isArray(frame?.turnRange) ? `${frame.turnRange[0]}-${frame.turnRange[1]}` : '?';
|
|
663
|
+
const head = `【工作帧】焦点:${entities.length > 0 ? entities.join('、') : '(无)'}(轮次 ${turnRange})`;
|
|
664
|
+
const anchorLines = (focus.anchors ?? []).map((anchor) => anchor?.oneLine).filter(Boolean).slice(0, 4);
|
|
665
|
+
const fixed = [head];
|
|
666
|
+
if (anchorLines.length > 0) fixed.push(`锚点:${anchorLines.join(';')}`);
|
|
667
|
+
const labels = { lastUserTask: '任务', nextStep: '下一步', touchedFiles: '改动', lastDecision: '决定' };
|
|
668
|
+
const present = {};
|
|
669
|
+
for (const name of WORKING_FIELDS) {
|
|
670
|
+
const text = workingFieldText(focus[name]);
|
|
671
|
+
if (text !== '') present[name] = `${labels[name]}:${text}`;
|
|
672
|
+
}
|
|
673
|
+
const before = WORKING_FIELDS.reduce((sum, name) => sum + (present[name] ? present[name].length : 0), 0);
|
|
674
|
+
const dropOrder = [...WORKING_FIELDS];
|
|
675
|
+
const dropped = [];
|
|
676
|
+
const render = () => [...fixed, ...WORKING_FIELDS.filter((name) => present[name]).map((name) => present[name])].join('\n');
|
|
677
|
+
let text = render();
|
|
678
|
+
while (text.length > WORKING_INJECT_MAX_CHARS && dropOrder.length > 0) {
|
|
679
|
+
const name = dropOrder.shift();
|
|
680
|
+
if (present[name]) {
|
|
681
|
+
delete present[name];
|
|
682
|
+
dropped.push(name);
|
|
683
|
+
text = render();
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (text.length > WORKING_INJECT_MAX_CHARS) text = `${text.slice(0, WORKING_INJECT_MAX_CHARS - 1)}…`;
|
|
687
|
+
return { text, dropped, before, after: text.length };
|
|
688
|
+
}
|
|
689
|
+
|
|
450
690
|
/** Injection decision: unexpired frame only; rollback fails closed; never delete. */
|
|
451
691
|
function frameForInjection({ sessionId, caller = null }) {
|
|
452
692
|
const loaded = load(sessionId);
|
|
453
|
-
if (!loaded.present)
|
|
454
|
-
|
|
693
|
+
if (!loaded.present) {
|
|
694
|
+
notifySkip(sessionId, 'E_NO_FRAME', { turn: 0 });
|
|
695
|
+
return { inject: false, code: 'E_NO_FRAME' };
|
|
696
|
+
}
|
|
697
|
+
if (loaded.frame === null) {
|
|
698
|
+
const code = loaded.code ?? 'E_INTEGRITY_TAMPER';
|
|
699
|
+
notifySkip(sessionId, code, { turn: 0 });
|
|
700
|
+
return { inject: false, code };
|
|
701
|
+
}
|
|
455
702
|
const frame = loaded.frame;
|
|
703
|
+
const turn = Array.isArray(frame.turnRange) ? frame.turnRange[1] : 0;
|
|
456
704
|
if (caller !== null) {
|
|
457
705
|
try {
|
|
458
706
|
assertFrameReadable(frame, caller);
|
|
459
707
|
} catch (error) {
|
|
708
|
+
notifySkip(sessionId, error.code ?? 'E_FRAME_PRIVATE', { turn });
|
|
460
709
|
return { inject: false, code: error.code ?? 'E_FRAME_PRIVATE', message: error.message };
|
|
461
710
|
}
|
|
462
711
|
}
|
|
463
712
|
try {
|
|
464
713
|
clockGuard(frame);
|
|
465
714
|
} catch (error) {
|
|
715
|
+
notifySkip(sessionId, error.code, { turn });
|
|
466
716
|
return { inject: false, code: error.code, message: error.message };
|
|
467
717
|
}
|
|
468
718
|
if (isExpired(frame)) {
|
|
@@ -474,9 +724,21 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
474
724
|
}
|
|
475
725
|
audit('frame.stale', { sessionId: safeSessionId(sessionId), frameId: frame.frameId ?? null });
|
|
476
726
|
}
|
|
727
|
+
notifySkip(sessionId, 'E_FRAME_EXPIRED', { turn });
|
|
477
728
|
return { inject: false, code: 'E_FRAME_EXPIRED', frame };
|
|
478
729
|
}
|
|
479
|
-
|
|
730
|
+
const rendered = renderInjectionText(frame);
|
|
731
|
+
if (rendered.dropped.length > 0) {
|
|
732
|
+
gateEvent(sessionId, 'hg.d12.truncate', 'warn', 'field-budget', {
|
|
733
|
+
turn,
|
|
734
|
+
evidence: [
|
|
735
|
+
`dropped=${rendered.dropped.join(',')}`,
|
|
736
|
+
`before=${rendered.before}`,
|
|
737
|
+
`after=${rendered.after}`,
|
|
738
|
+
],
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
return { inject: true, frame, text: rendered.text, dropped: rendered.dropped };
|
|
480
742
|
}
|
|
481
743
|
|
|
482
744
|
/** ≤300 chars block; truncated in that order: anchors → entities. */
|
|
@@ -508,6 +770,7 @@ export function createWorkingFrameStore(options = {}) {
|
|
|
508
770
|
updateFocus,
|
|
509
771
|
frameForInjection,
|
|
510
772
|
renderBlock,
|
|
773
|
+
renderInjectionText,
|
|
511
774
|
isExpired,
|
|
512
775
|
topicChanged,
|
|
513
776
|
archive,
|
package/src/metrics/classify.mjs
CHANGED
|
@@ -16,7 +16,9 @@
|
|
|
16
16
|
|
|
17
17
|
import { classificationPluginLabels } from '../adapters/registry.js';
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
// 2.0.0 起 auto-recall 注入块头是 `【自动想起 · recallId=…】`(零命中同头),
|
|
20
|
+
// 这里只保留前缀,继续兼容历史 `【自动想起】` 正文标记。
|
|
21
|
+
export const RECALL_HEADER = '【自动想起';
|
|
20
22
|
export const CONCLUSION_HEADER = '【开机卡】';
|
|
21
23
|
|
|
22
24
|
/**
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// B7b 草案:冷档三键归一化(2.0.0 W3b ⑧,raw 透传,不新增 schemastery 节点)。
|
|
2
|
+
//
|
|
3
|
+
// 契约(V0.5.2-RETENTION-PATCH §3、B37-SCOPE):
|
|
4
|
+
// recall.archiveRoot 冷档根(如 J 盘 longlive-archive/retention 或等价的冷盘根)
|
|
5
|
+
// recall.archiveStatePath 状态文件路径(缺省 <memoryRoot>/.longlive/archive-state.json)
|
|
6
|
+
// recall.archiveFailOpen 冷档不可用时 recall 是否放行(缺省 false = 安全语义;只影响 read,不放行任何删除)
|
|
7
|
+
//
|
|
8
|
+
// 现状事实(2026-11-29 22:55 核读 worktree):
|
|
9
|
+
// src/features.js L823-835 已把这三个键从 raw config 透传到 recallConfig;
|
|
10
|
+
// src/features.js L874-891 又把 archiveRoot/archiveStatePath 传给 autoMaintenance;
|
|
11
|
+
// src/config.js 没有这三个叶子(153 节点锁),所以本模块也不注册 schema 节点,
|
|
12
|
+
// 只提供纯归一化,供 retention/cold-gate 与测试使用。
|
|
13
|
+
//
|
|
14
|
+
// 本文件不 import 任何回写模块:纯函数 + 读环境变量,便于单测。
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
|
|
17
|
+
export const ARCHIVE_CONFIG_SCHEMA = 'archive-config/v1';
|
|
18
|
+
export const ARCHIVE_STATE_REL = '.longlive/archive-state.json';
|
|
19
|
+
export const ARCHIVE_CONFIG_ENV = Object.freeze({
|
|
20
|
+
root: 'HG_ARCHIVE_ROOT',
|
|
21
|
+
statePath: 'HG_ARCHIVE_STATE_PATH',
|
|
22
|
+
failOpen: 'HG_ARCHIVE_FAIL_OPEN',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function text(value) {
|
|
26
|
+
if (typeof value !== 'string') return null;
|
|
27
|
+
const trimmed = value.trim();
|
|
28
|
+
return trimmed === '' ? null : trimmed;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function envText(env, key) {
|
|
32
|
+
if (!env || typeof env !== 'object') return null;
|
|
33
|
+
return text(env[key]);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function boolOr(value, fallback) {
|
|
37
|
+
if (typeof value === 'boolean') return value;
|
|
38
|
+
if (typeof value === 'string') {
|
|
39
|
+
const lowered = value.trim().toLowerCase();
|
|
40
|
+
if (lowered === 'true' || lowered === '1' || lowered === 'yes' || lowered === 'on') return true;
|
|
41
|
+
if (lowered === 'false' || lowered === '0' || lowered === 'no' || lowered === 'off') return false;
|
|
42
|
+
}
|
|
43
|
+
return fallback;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 归一化冷档三键。输入可以是整个 config(含 recall 块)或只有 recall 块。
|
|
48
|
+
* 返回 {schema, configured, archiveRoot, archiveStatePath, archiveFailOpen, warnings, sources}。
|
|
49
|
+
* 缺省:archiveRoot=null → configured=false(未配置冷档,按 2.0.0 旧行为处理,不静默造目录)。
|
|
50
|
+
* archiveFailOpen 非布尔/非可识别字符串 → false + warning,绝不默认放行。
|
|
51
|
+
*/
|
|
52
|
+
export function normalizeArchiveConfig(raw = {}, { env = process.env } = {}) {
|
|
53
|
+
const warnings = [];
|
|
54
|
+
let recall = {};
|
|
55
|
+
if (raw && typeof raw === 'object') {
|
|
56
|
+
recall = raw.recall && typeof raw.recall === 'object' ? raw.recall : raw;
|
|
57
|
+
}
|
|
58
|
+
const sources = { archiveRoot: 'config', archiveStatePath: 'config', archiveFailOpen: 'default' };
|
|
59
|
+
|
|
60
|
+
let archiveRoot = text(recall.archiveRoot);
|
|
61
|
+
if (archiveRoot === null) {
|
|
62
|
+
const fromEnv = envText(env, ARCHIVE_CONFIG_ENV.root);
|
|
63
|
+
if (fromEnv !== null) {
|
|
64
|
+
archiveRoot = fromEnv;
|
|
65
|
+
sources.archiveRoot = 'env';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let archiveStatePath = text(recall.archiveStatePath);
|
|
70
|
+
if (archiveStatePath === null) {
|
|
71
|
+
const fromEnv = envText(env, ARCHIVE_CONFIG_ENV.statePath);
|
|
72
|
+
if (fromEnv !== null) {
|
|
73
|
+
archiveStatePath = fromEnv;
|
|
74
|
+
sources.archiveStatePath = 'env';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let archiveFailOpen = false;
|
|
79
|
+
if (recall.archiveFailOpen !== undefined) {
|
|
80
|
+
const parsed = boolOr(recall.archiveFailOpen, null);
|
|
81
|
+
if (parsed === null) {
|
|
82
|
+
warnings.push({ code: 'archiveFailOpen-invalid', value: recall.archiveFailOpen });
|
|
83
|
+
archiveFailOpen = false;
|
|
84
|
+
} else {
|
|
85
|
+
archiveFailOpen = parsed;
|
|
86
|
+
sources.archiveFailOpen = 'config';
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
const fromEnv = envText(env, ARCHIVE_CONFIG_ENV.failOpen);
|
|
90
|
+
if (fromEnv !== null) {
|
|
91
|
+
const parsed = boolOr(fromEnv, null);
|
|
92
|
+
if (parsed === null) {
|
|
93
|
+
warnings.push({ code: 'archiveFailOpen-invalid-env', value: fromEnv });
|
|
94
|
+
} else {
|
|
95
|
+
archiveFailOpen = parsed;
|
|
96
|
+
sources.archiveFailOpen = 'env';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
schema: ARCHIVE_CONFIG_SCHEMA,
|
|
103
|
+
configured: archiveRoot !== null,
|
|
104
|
+
archiveRoot,
|
|
105
|
+
archiveStatePath,
|
|
106
|
+
archiveFailOpen,
|
|
107
|
+
warnings,
|
|
108
|
+
sources,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 状态文件绝对路径:显式 archiveStatePath 优先;否则 <memoryRoot>/.longlive/archive-state.json。 */
|
|
113
|
+
export function resolveArchiveStatePath(memoryRoot, cfg = {}) {
|
|
114
|
+
const explicit = text(cfg.archiveStatePath);
|
|
115
|
+
if (explicit !== null) return path.isAbsolute(explicit) ? explicit : path.join(memoryRoot, explicit);
|
|
116
|
+
const root = text(memoryRoot);
|
|
117
|
+
if (root === null) return null;
|
|
118
|
+
return path.join(root, ARCHIVE_STATE_REL);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 冷副本目标路径:<archiveRoot>/<layer>/<rel>(P5 契约)。rel 必须是相对记忆根的 POSIX 相对路径。 */
|
|
122
|
+
export function coldCopyPath(archiveRoot, layer, rel) {
|
|
123
|
+
const root = text(archiveRoot);
|
|
124
|
+
if (root === null) throw new Error('coldCopyPath: archiveRoot 缺失');
|
|
125
|
+
const cleanRel = String(rel ?? '').replace(/\\/g, '/').replace(/^\.?\//, '');
|
|
126
|
+
if (cleanRel === '' || cleanRel.split('/').some((seg) => seg === '..' || seg === '')) {
|
|
127
|
+
throw new Error(`coldCopyPath: 非法相对路径 ${rel}`);
|
|
128
|
+
}
|
|
129
|
+
return path.join(root, layer, ...cleanRel.split('/'));
|
|
130
|
+
}
|