@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,110 @@
|
|
|
1
|
+
// N02 · 当前线(current line)
|
|
2
|
+
//
|
|
3
|
+
// 从记忆根取「我刚站哪儿」的一行,供硬门注入块的 `当前线:…` 行使用。
|
|
4
|
+
// 读源优先级(只读,绝不写):
|
|
5
|
+
// 1) flow/current.md 的「我正在做什么 / 下一步 / 卡在哪」首条非空行
|
|
6
|
+
// 2) STATE.md 的「我在哪」节首条非空行
|
|
7
|
+
// 预算分节沿用 handover.js 的 allocateBudget / compactSection(单一实现,
|
|
8
|
+
// 不在这里复写预算逻辑)。任何缺失都返回显式的 UNSET,而不是编一行假的。
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
allocateBudget,
|
|
15
|
+
compactSection,
|
|
16
|
+
parseState,
|
|
17
|
+
truncateChars,
|
|
18
|
+
} from '../identity/handover.js';
|
|
19
|
+
|
|
20
|
+
export const CURRENT_LINE_MAX_CHARS = 80;
|
|
21
|
+
export const UNSET = Symbol('hg.current-line.unset');
|
|
22
|
+
|
|
23
|
+
export class HardGateUnimplementedError extends Error {
|
|
24
|
+
constructor(moduleName, detail = '') {
|
|
25
|
+
super(`E_HG_${String(moduleName).toUpperCase()}_UNIMPLEMENTED${detail ? `: ${detail}` : ''}`);
|
|
26
|
+
this.code = `E_HG_${String(moduleName).toUpperCase()}_UNIMPLEMENTED`;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function firstMeaningfulLine(markdown) {
|
|
31
|
+
for (const raw of String(markdown ?? '').split(/\r?\n/)) {
|
|
32
|
+
const line = raw
|
|
33
|
+
.trim()
|
|
34
|
+
.replace(/^[-*+]\s+/u, '')
|
|
35
|
+
.replace(/^#{1,6}\s+/u, '')
|
|
36
|
+
.replace(/^\d+[.)]\s+/u, '')
|
|
37
|
+
.trim();
|
|
38
|
+
if (line === '' || line.startsWith('<!--') || line.startsWith('```')) continue;
|
|
39
|
+
return line;
|
|
40
|
+
}
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readTextIfAny(filePath) {
|
|
45
|
+
try {
|
|
46
|
+
return fs.readFileSync(filePath, 'utf8');
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 读当前线。返回 {text, chars, source, truncated};没有可用内容返回 UNSET。
|
|
54
|
+
* @param {{memoryRoot?: string, maxChars?: number}} [options]
|
|
55
|
+
*/
|
|
56
|
+
export function readCurrentLine(options = {}) {
|
|
57
|
+
const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
|
|
58
|
+
? path.resolve(options.memoryRoot.trim())
|
|
59
|
+
: null;
|
|
60
|
+
if (!memoryRoot) return UNSET;
|
|
61
|
+
const maxChars = Number.isFinite(options.maxChars)
|
|
62
|
+
? Math.max(8, Math.floor(options.maxChars))
|
|
63
|
+
: CURRENT_LINE_MAX_CHARS;
|
|
64
|
+
|
|
65
|
+
const flowText = readTextIfAny(path.join(memoryRoot, 'flow', 'current.md'));
|
|
66
|
+
if (flowText !== null) {
|
|
67
|
+
const sections = [];
|
|
68
|
+
const parsedFlow = parseState(flowText);
|
|
69
|
+
sections.push(...(parsedFlow.sections ?? []));
|
|
70
|
+
for (const heading of ['我正在做什么', '下一步', '卡在哪']) {
|
|
71
|
+
const section = sections.find((item) => String(item?.title ?? '').includes(heading));
|
|
72
|
+
const line = firstMeaningfulLine(section?.content ?? '');
|
|
73
|
+
if (line !== '') {
|
|
74
|
+
const cut = truncateChars(line, maxChars);
|
|
75
|
+
return { text: cut.text, chars: Array.from(cut.text).length, source: 'flow/current.md', truncated: cut.truncated };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const fallback = firstMeaningfulLine(flowText);
|
|
79
|
+
if (fallback !== '') {
|
|
80
|
+
const cut = truncateChars(fallback, maxChars);
|
|
81
|
+
return { text: cut.text, chars: Array.from(cut.text).length, source: 'flow/current.md', truncated: cut.truncated };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const stateText = readTextIfAny(path.join(memoryRoot, 'STATE.md'));
|
|
86
|
+
if (stateText !== null) {
|
|
87
|
+
const parsed = parseState(stateText);
|
|
88
|
+
const where = compactSection(parsed.sections, '我在哪', maxChars);
|
|
89
|
+
if (where.found && where.text.trim() !== '') {
|
|
90
|
+
const line = firstMeaningfulLine(where.text);
|
|
91
|
+
if (line !== '') {
|
|
92
|
+
const cut = truncateChars(line, maxChars);
|
|
93
|
+
return { text: cut.text, chars: Array.from(cut.text).length, source: 'STATE.md#我在哪', truncated: cut.truncated };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return UNSET;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 渲染注入块里的当前线行;没有当前线时返回空串(不编造)。 */
|
|
101
|
+
export function renderCurrentLine(memoryRoot) {
|
|
102
|
+
const line = readCurrentLine({ memoryRoot });
|
|
103
|
+
if (line === UNSET) return '';
|
|
104
|
+
return `当前线:${line.text}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 预算分节(暴露 handover 的单一实现,供后续 C 面复用)。 */
|
|
108
|
+
export function splitBudgets(parts, total) {
|
|
109
|
+
return allocateBudget(parts, total);
|
|
110
|
+
}
|
package/src/recall/edges.js
CHANGED
|
@@ -29,6 +29,8 @@ export const EXPAND_PRIORITY = Object.freeze({
|
|
|
29
29
|
conflicts_with: 1,
|
|
30
30
|
superseded_by: 2,
|
|
31
31
|
answers_with: 3,
|
|
32
|
+
derived_from: 4,
|
|
33
|
+
supersedes: 5,
|
|
32
34
|
});
|
|
33
35
|
// 历史查询词判定统一走 src/memory/lifecycle.js 的 isHistoricalQuery(D9 单一实现)。
|
|
34
36
|
|
|
@@ -336,22 +338,31 @@ export function expandEdges(baseItems, {
|
|
|
336
338
|
const items = [];
|
|
337
339
|
const seen = new Set(basePaths);
|
|
338
340
|
const dropped = [];
|
|
341
|
+
const dropCounts = { missingCard: 0, historical: 0, archived: 0, budget: 0 };
|
|
339
342
|
let tokens = 0;
|
|
340
343
|
let injected = 0;
|
|
341
344
|
for (const candidate of candidates) {
|
|
342
345
|
if (seen.has(candidate.target)) continue;
|
|
343
346
|
const card = cardsByPath.get(candidate.target);
|
|
344
|
-
if (!card) { dropped.push({ path: candidate.target, reason: 'missing-card' }); continue; }
|
|
347
|
+
if (!card) { dropCounts.missingCard += 1; dropped.push({ path: candidate.target, reason: 'missing-card' }); continue; }
|
|
345
348
|
const lifecycle = lifecycleOf ? lifecycleOf(candidate.target) : null;
|
|
346
349
|
if (lifecycle === 'historical' && !allowHistory) {
|
|
350
|
+
dropCounts.historical += 1;
|
|
347
351
|
dropped.push({ path: candidate.target, reason: 'historical' });
|
|
348
352
|
continue;
|
|
349
353
|
}
|
|
354
|
+
// M21 归档修边:archived/forgotten 目标不再注入(历史查询也不放行归档卡)。
|
|
355
|
+
const targetStatus = card?.fields?.status ?? card?.status ?? 'active';
|
|
356
|
+
if (targetStatus === 'archived' || targetStatus === 'forgotten') {
|
|
357
|
+
dropCounts.archived += 1;
|
|
358
|
+
dropped.push({ path: candidate.target, reason: 'archived' });
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
350
361
|
const title = String(card.title ?? card.fields?.title ?? candidate.target);
|
|
351
362
|
const excerpt = relationSentence(candidate.edge, card);
|
|
352
363
|
const text = `- 《${title}》(${candidate.target})\n${excerpt}`;
|
|
353
364
|
const cost = estimateTokens(text);
|
|
354
|
-
if (tokens + cost > budget) { dropped.push({ path: candidate.target, reason: 'budget' }); continue; }
|
|
365
|
+
if (tokens + cost > budget) { dropCounts.budget += 1; dropped.push({ path: candidate.target, reason: 'budget' }); continue; }
|
|
355
366
|
tokens += cost;
|
|
356
367
|
injected += 1;
|
|
357
368
|
seen.add(candidate.target);
|
|
@@ -375,5 +386,13 @@ export function expandEdges(baseItems, {
|
|
|
375
386
|
walked: walked.size,
|
|
376
387
|
injected,
|
|
377
388
|
dropped,
|
|
389
|
+
counts: {
|
|
390
|
+
walked: walked.size,
|
|
391
|
+
injected,
|
|
392
|
+
droppedHistorical: dropCounts.historical,
|
|
393
|
+
droppedArchived: dropCounts.archived,
|
|
394
|
+
droppedMissingCard: dropCounts.missingCard,
|
|
395
|
+
droppedBudget: dropCounts.budget,
|
|
396
|
+
},
|
|
378
397
|
};
|
|
379
398
|
}
|
package/src/recall/explain.mjs
CHANGED
|
@@ -205,6 +205,9 @@ export function buildRecallLogRecord({
|
|
|
205
205
|
injectedItems = null,
|
|
206
206
|
query = '',
|
|
207
207
|
elapsedMs = null,
|
|
208
|
+
// B3 C5:本轮注入块的实际字符数与估算 token(字符车道口径,1 token ≈ 2 字符)。
|
|
209
|
+
injectedChars = null,
|
|
210
|
+
injectedTokens = null,
|
|
208
211
|
forced = false,
|
|
209
212
|
why: whyOverride = null,
|
|
210
213
|
trigger: triggerOverride = null,
|
|
@@ -225,6 +228,10 @@ export function buildRecallLogRecord({
|
|
|
225
228
|
// 注意 Number(null) === 0:缺省(null/undefined/'')必须落 null,不能落 0。
|
|
226
229
|
const elapsedRaw = elapsedMs === null || elapsedMs === undefined || elapsedMs === '' ? null : Number(elapsedMs);
|
|
227
230
|
const elapsed = Number.isFinite(elapsedRaw) && elapsedRaw >= 0 ? Math.round(elapsedRaw) : null;
|
|
231
|
+
const injectedCharsRaw = injectedChars === null || injectedChars === undefined || injectedChars === '' ? null : Number(injectedChars);
|
|
232
|
+
const injectedCharsValue = Number.isFinite(injectedCharsRaw) && injectedCharsRaw >= 0 ? Math.round(injectedCharsRaw) : null;
|
|
233
|
+
const injectedTokensRaw = injectedTokens === null || injectedTokens === undefined || injectedTokens === '' ? null : Number(injectedTokens);
|
|
234
|
+
const injectedTokensValue = Number.isFinite(injectedTokensRaw) && injectedTokensRaw >= 0 ? Math.round(injectedTokensRaw) : null;
|
|
228
235
|
let outcome = 'zero-hit';
|
|
229
236
|
if (error === true) outcome = 'error';
|
|
230
237
|
else if (factoryUnavailable === true) outcome = 'factory-unavailable';
|
|
@@ -245,6 +252,9 @@ export function buildRecallLogRecord({
|
|
|
245
252
|
forced: forced === true,
|
|
246
253
|
query: summarizeQuery(query),
|
|
247
254
|
elapsedMs: elapsed,
|
|
255
|
+
// B3 C5:injected 行必须能读到 token/延迟;字符数是本轮真正的注入块大小。
|
|
256
|
+
injectedChars: injectedCharsValue,
|
|
257
|
+
injectedTokens: injectedTokensValue,
|
|
248
258
|
outcome,
|
|
249
259
|
archiveUnavailable: archiveUnavailable === true,
|
|
250
260
|
link: summarizeLinkStat(link),
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// N04 · hardgate 链式日志(gate-log / land-log 同构)
|
|
2
|
+
//
|
|
3
|
+
// 契约(DESIGN v0.5.1 §6 A1 / §7 B):
|
|
4
|
+
// <memoryRoot>/.longlive/hardgate/gate-log.jsonl
|
|
5
|
+
// <memoryRoot>/.longlive/hardgate/gate-log-head.json
|
|
6
|
+
// 每行 {schema,at,sessionId,turn,gate,decision,reason,evidence[],sha,prevSha};
|
|
7
|
+
// sha = sha256(canonical({schema,at,sessionId,turn,gate,decision,reason,evidence}))
|
|
8
|
+
// prevSha = 前一行的 sha;首行 null。
|
|
9
|
+
// 2.0.0 B3:行内可选携带注入度量 {injectedChars,injectedTokens,elapsedMs};只在本行真的
|
|
10
|
+
// 有该字段时进入 sha 域(旧行逐字不变,链校验/回放保持兼容)。
|
|
11
|
+
// head 文件 = {rows, tailSha, updatedAt},每次 append 同锁更新。
|
|
12
|
+
//
|
|
13
|
+
// 任何写入失败都抛错(fail-closed):调用方要么让本轮硬门显式失败,要么把错误
|
|
14
|
+
// 记进 stderr/日志——禁止静默当成功。读取失败时调用方自己决定是否降级。
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
|
|
20
|
+
export const HARDGATE_DIRNAME = 'hardgate';
|
|
21
|
+
export const GATE_LOG_SCHEMA = 'hardgate-gate-log/v1';
|
|
22
|
+
export const LAND_LOG_SCHEMA = 'land-gate/v1';
|
|
23
|
+
export const GATE_LOG_FILE = 'gate-log.jsonl';
|
|
24
|
+
export const GATE_LOG_HEAD_FILE = 'gate-log-head.json';
|
|
25
|
+
export const LAND_LOG_FILE = 'land-log.jsonl';
|
|
26
|
+
export const LAND_LOG_HEAD_FILE = 'land-log-head.json';
|
|
27
|
+
|
|
28
|
+
export const GATE_DECISIONS = Object.freeze(['ok', 'zero-hit', 'disabled', 'fail', 'warn', 'skip']);
|
|
29
|
+
|
|
30
|
+
// gate-reason 草案:B4「每次注入必带 reason code(无 reason fail-closed)」+ B3 C4(每行非空
|
|
31
|
+
// reason)。写器层兜底:调用方显式给非空 reason 就原样保留;没给/给空串时,按 decision 取
|
|
32
|
+
// 一个确定性的非空 reason,绝不落空串。不变量:写出的每一行 reason 都是非空字符串。
|
|
33
|
+
export const DEFAULT_GATE_LOG_REASON = Object.freeze({
|
|
34
|
+
ok: 'hit',
|
|
35
|
+
'zero-hit': 'zero-hit',
|
|
36
|
+
disabled: 'disabled',
|
|
37
|
+
fail: 'fail',
|
|
38
|
+
warn: 'warn',
|
|
39
|
+
skip: 'skip',
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
export function normalizeGateLogReason(input = {}) {
|
|
43
|
+
const explicit = [input.reason, input.reasonCode, input.reason_code].find(
|
|
44
|
+
(value) => typeof value === 'string' && value.trim() !== '',
|
|
45
|
+
);
|
|
46
|
+
if (explicit !== undefined) return explicit.trim();
|
|
47
|
+
const decision = typeof input.decision === 'string' && input.decision.trim() !== ''
|
|
48
|
+
? input.decision.trim()
|
|
49
|
+
: 'ok';
|
|
50
|
+
return DEFAULT_GATE_LOG_REASON[decision] ?? decision;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// B3 C4:可选的注入度量字段(与 src/recall/gate-metrics.mjs 的 GATE_METRIC_KEYS 同口径;
|
|
54
|
+
// 本地常量避免 gate-log → gate-metrics 的单向依赖被测试替身打断)。
|
|
55
|
+
const GATE_METRIC_KEYS = Object.freeze(['injectedChars', 'injectedTokens', 'elapsedMs']);
|
|
56
|
+
|
|
57
|
+
function hardgateDir(memoryRoot) {
|
|
58
|
+
if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
|
|
59
|
+
throw hardgateError('E_HG_GATELOG_NO_ROOT', 'gate-log 需要 memoryRoot');
|
|
60
|
+
}
|
|
61
|
+
return path.join(path.resolve(memoryRoot), '.longlive', HARDGATE_DIRNAME);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function hardgateError(code, message) {
|
|
65
|
+
const error = new Error(message);
|
|
66
|
+
error.code = code;
|
|
67
|
+
return error;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 与夹具 harness 完全一致的 canonical JSON:键名按码点升序,数组保序,无空白。 */
|
|
71
|
+
export function canonicalJson(value) {
|
|
72
|
+
if (value === undefined) return 'null';
|
|
73
|
+
if (value === null || typeof value !== 'object') {
|
|
74
|
+
if (typeof value === 'number' && !Number.isFinite(value)) return 'null';
|
|
75
|
+
return JSON.stringify(value);
|
|
76
|
+
}
|
|
77
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
|
|
78
|
+
const keys = Object.keys(value).sort();
|
|
79
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function sha256(value) {
|
|
83
|
+
return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function gateLogPaths(memoryRoot) {
|
|
87
|
+
const dir = hardgateDir(memoryRoot);
|
|
88
|
+
return {
|
|
89
|
+
dir,
|
|
90
|
+
logFile: path.join(dir, GATE_LOG_FILE),
|
|
91
|
+
headFile: path.join(dir, GATE_LOG_HEAD_FILE),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function landLogPaths(memoryRoot) {
|
|
96
|
+
const dir = hardgateDir(memoryRoot);
|
|
97
|
+
return {
|
|
98
|
+
dir,
|
|
99
|
+
logFile: path.join(dir, LAND_LOG_FILE),
|
|
100
|
+
headFile: path.join(dir, LAND_LOG_HEAD_FILE),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function readHeadState(headFile) {
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(fs.readFileSync(headFile, 'utf8'));
|
|
107
|
+
if (parsed && typeof parsed === 'object') {
|
|
108
|
+
return {
|
|
109
|
+
rows: Number.isFinite(parsed.rows) ? parsed.rows : 0,
|
|
110
|
+
tailSha: typeof parsed.tailSha === 'string' ? parsed.tailSha : null,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
/* head 缺失/坏:靠日志末行重建 */
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function lastRowOf(logFile) {
|
|
120
|
+
try {
|
|
121
|
+
const text = fs.readFileSync(logFile, 'utf8');
|
|
122
|
+
const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '');
|
|
123
|
+
if (lines.length === 0) return null;
|
|
124
|
+
return JSON.parse(lines[lines.length - 1]);
|
|
125
|
+
} catch {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function writeHead(headFile, rows, tailSha) {
|
|
131
|
+
const payload = JSON.stringify({
|
|
132
|
+
rows,
|
|
133
|
+
tailSha,
|
|
134
|
+
updatedAt: new Date().toISOString(),
|
|
135
|
+
});
|
|
136
|
+
const tmp = `${headFile}.tmp-${process.pid}-${Date.now()}`;
|
|
137
|
+
fs.writeFileSync(tmp, `${payload}\n`, 'utf8');
|
|
138
|
+
fs.renameSync(tmp, headFile);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* B3 C4:gate-log 行的注入度量。只接受有限数值;null/undefined/'' 视为「本行没有」,
|
|
143
|
+
* 不进 sha 域(旧行兼容:旧行没有这三个字段时域与 sha 一字不变)。
|
|
144
|
+
*/
|
|
145
|
+
function metricValue(value) {
|
|
146
|
+
if (value === null || value === undefined || value === '') return null;
|
|
147
|
+
const n = Number(value);
|
|
148
|
+
return Number.isFinite(n) ? n : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** B3:三个可选度量字段的顺序固定,append 与 verify 用同一份域构造。 */
|
|
152
|
+
function metricDomainFields(input) {
|
|
153
|
+
const fields = {};
|
|
154
|
+
for (const key of GATE_METRIC_KEYS) {
|
|
155
|
+
const value = metricValue(input?.[key]);
|
|
156
|
+
if (value !== null) fields[key] = value;
|
|
157
|
+
}
|
|
158
|
+
return fields;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 往链式日志追加一行。返回写入的完整行(含 sha/prevSha)。
|
|
163
|
+
* 同进程内同步写;跨进程并发由调用方(capture-host)串行化。
|
|
164
|
+
*/
|
|
165
|
+
export function appendChainedRow(paths, schema, input = {}) {
|
|
166
|
+
const evidence = Array.isArray(input.evidence) ? input.evidence.map((item) => String(item)) : [];
|
|
167
|
+
const domain = {
|
|
168
|
+
schema,
|
|
169
|
+
at: typeof input.at === 'string' ? input.at : new Date().toISOString(),
|
|
170
|
+
sessionId: input.sessionId ?? null,
|
|
171
|
+
turn: Number.isFinite(input.turn) ? input.turn : null,
|
|
172
|
+
gate: input.gate ?? 'recall',
|
|
173
|
+
decision: input.decision ?? 'ok',
|
|
174
|
+
reason: normalizeGateLogReason(input),
|
|
175
|
+
evidence,
|
|
176
|
+
// 2.0.0 W3b:A6 五码族要能被 gate-log 读回(D19 N3 读 row.code)。可选字段:
|
|
177
|
+
// 旧行没有它 → 域与 sha 都不变,链校验/回放保持兼容。
|
|
178
|
+
...(typeof input.code === 'string' && input.code !== '' ? { code: input.code } : {}),
|
|
179
|
+
// 2.0.0 B3:每轮注入度量(字符/token/延迟)。旧行没有 → 域与 sha 不变。
|
|
180
|
+
...metricDomainFields(input),
|
|
181
|
+
};
|
|
182
|
+
const rowSha = sha256(canonicalJson(domain));
|
|
183
|
+
const head = readHeadState(paths.headFile);
|
|
184
|
+
const last = head === null ? lastRowOf(paths.logFile) : null;
|
|
185
|
+
const previous = head ?? {
|
|
186
|
+
rows: last ? 1 : 0,
|
|
187
|
+
tailSha: typeof last?.sha === 'string' ? last.sha : null,
|
|
188
|
+
};
|
|
189
|
+
const row = {
|
|
190
|
+
...domain,
|
|
191
|
+
sha: rowSha,
|
|
192
|
+
prevSha: previous.tailSha ?? null,
|
|
193
|
+
};
|
|
194
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
195
|
+
fs.appendFileSync(paths.logFile, `${JSON.stringify(row)}\n`, 'utf8');
|
|
196
|
+
writeHead(paths.headFile, previous.rows + 1, rowSha);
|
|
197
|
+
return row;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function appendGateLog(memoryRoot, input = {}) {
|
|
201
|
+
return appendChainedRow(gateLogPaths(memoryRoot), GATE_LOG_SCHEMA, input);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function appendLandLog(memoryRoot, input = {}) {
|
|
205
|
+
return appendChainedRow(landLogPaths(memoryRoot), LAND_LOG_SCHEMA, input);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function readRows(logFile) {
|
|
209
|
+
let text;
|
|
210
|
+
try {
|
|
211
|
+
text = fs.readFileSync(logFile, 'utf8');
|
|
212
|
+
} catch {
|
|
213
|
+
return [];
|
|
214
|
+
}
|
|
215
|
+
const rows = [];
|
|
216
|
+
for (const line of text.split(/\r?\n/)) {
|
|
217
|
+
if (line.trim() === '') continue;
|
|
218
|
+
try {
|
|
219
|
+
const parsed = JSON.parse(line);
|
|
220
|
+
if (parsed && typeof parsed === 'object') rows.push(parsed);
|
|
221
|
+
} catch {
|
|
222
|
+
/* 坏行忽略:verify 会按行数对不上报错 */
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return rows;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 独立校验:逐行重算 sha、prevSha 链与 head 锚。返回 {ok, rows, head, errors}。
|
|
230
|
+
* 只读;不修文件。
|
|
231
|
+
*/
|
|
232
|
+
export function verifyChainedLogPaths(logFile, headFile) {
|
|
233
|
+
const rows = readRows(logFile);
|
|
234
|
+
const errors = [];
|
|
235
|
+
let previous = null;
|
|
236
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
237
|
+
const row = rows[index];
|
|
238
|
+
const expected = sha256(canonicalJson({
|
|
239
|
+
schema: row.schema,
|
|
240
|
+
at: row.at,
|
|
241
|
+
sessionId: row.sessionId ?? null,
|
|
242
|
+
turn: row.turn ?? null,
|
|
243
|
+
gate: row.gate,
|
|
244
|
+
decision: row.decision,
|
|
245
|
+
reason: row.reason,
|
|
246
|
+
evidence: Array.isArray(row.evidence) ? row.evidence : [],
|
|
247
|
+
...(typeof row.code === 'string' && row.code !== '' ? { code: row.code } : {}),
|
|
248
|
+
// 2.0.0 B3:重算域与 appendChainedRow 同口径(只补本行真的有的度量)。
|
|
249
|
+
...metricDomainFields(row),
|
|
250
|
+
}));
|
|
251
|
+
if (row.sha !== expected) errors.push(`row ${index + 1}: sha 不匹配`);
|
|
252
|
+
if (index === 0 ? row.prevSha !== null : row.prevSha !== previous) {
|
|
253
|
+
errors.push(`row ${index + 1}: prevSha 断裂`);
|
|
254
|
+
}
|
|
255
|
+
previous = row.sha;
|
|
256
|
+
}
|
|
257
|
+
let head = null;
|
|
258
|
+
try {
|
|
259
|
+
head = JSON.parse(fs.readFileSync(headFile, 'utf8'));
|
|
260
|
+
} catch {
|
|
261
|
+
errors.push('head 文件缺失或不可解析');
|
|
262
|
+
}
|
|
263
|
+
if (head) {
|
|
264
|
+
if (head.rows !== rows.length) errors.push(`head.rows=${head.rows} 与行数 ${rows.length} 不一致`);
|
|
265
|
+
if ((head.tailSha ?? null) !== (previous ?? null)) errors.push('head.tailSha 与末行 sha 不一致');
|
|
266
|
+
}
|
|
267
|
+
return { ok: errors.length === 0, rows, head, errors };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function verifyGateLog(memoryRoot) {
|
|
271
|
+
const paths = gateLogPaths(memoryRoot);
|
|
272
|
+
return verifyChainedLogPaths(paths.logFile, paths.headFile);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function readGateLog(memoryRoot) {
|
|
276
|
+
const paths = gateLogPaths(memoryRoot);
|
|
277
|
+
return { ...paths, rows: readRows(paths.logFile) };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export { hardgateError };
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// B3 已落 worktree · gate-log 机制补丁的纯函数层(2026-11-29 接线;供 brain 判决与 L3/L7 判据复用)
|
|
2
|
+
//
|
|
3
|
+
// 现状问题(实测 2026-11-29,memoryRoot 下两本日志):
|
|
4
|
+
// - gate-log 当日 16 行:3 行 reason 为空、0 行带 token、0 行带延迟;11 行 decision=skip
|
|
5
|
+
// (10 条 SUBAGENT + 1 条 hg.d12.skip),L2/L7 的 skip=0 判据必 FAIL。
|
|
6
|
+
// - recall-log 当日 293 行:227 条 outcome=gate-skip(安装前 legacy 链),按当天仍计 skip。
|
|
7
|
+
//
|
|
8
|
+
// 本模块提供:机制裁决所需的纯函数(M/L7 判据的重放)、gate 行度量字段的生成/校验、
|
|
9
|
+
// recall 日志行判据重放。写盘仍由 worktree 的 src/recall/gate-log.mjs(appendGateLog)负责,
|
|
10
|
+
// 补丁只在 appendChainedRow 的 sha 域里增加 GATE_METRIC_KEYS 三个可选字段并让 verify 同步比对。
|
|
11
|
+
|
|
12
|
+
export const GATE_LOG_SCHEMA = 'hardgate-gate-log/v1';
|
|
13
|
+
|
|
14
|
+
// L7 的字段解析顺序(与 checks/L7-budget-injection.mjs 保持一致)
|
|
15
|
+
export const GATE_REASON_KEYS = Object.freeze(['reason', 'reasonCode', 'reason_code', 'why', 'gateReason']);
|
|
16
|
+
export const GATE_TOKEN_KEYS = Object.freeze(['injectedTokens', 'tokens', 'estimatedTokens', 'inputTokens', 'hintTokens', 'injected_tokens']);
|
|
17
|
+
export const GATE_LATENCY_KEYS = Object.freeze(['elapsedMs', 'latencyMs', 'durationMs', 'tookMs', 'ms']);
|
|
18
|
+
|
|
19
|
+
// L7 的 skip 行判定:扫这些字段,或 skipped/blocked === true
|
|
20
|
+
export const GATE_SKIP_RE = /(gate-skip|blocked|dropped|skip|skip-policy|policy-skip)/i;
|
|
21
|
+
export const GATE_SKIP_FIELDS = Object.freeze(['outcome', 'why', 'decision', 'action', 'status', 'gate', 'reason', 'reasonCode']);
|
|
22
|
+
|
|
23
|
+
// B3 下召回注入行的判决空间:没有 skip;disabled/warn/fail 都带明确原因码。
|
|
24
|
+
export const GATE_RECALL_DECISIONS = Object.freeze(['ok', 'zero-hit', 'disabled', 'fail', 'warn']);
|
|
25
|
+
|
|
26
|
+
// 本补丁给 gate 行增加、并纳入 sha 域的三个度量字段。
|
|
27
|
+
export const GATE_METRIC_KEYS = Object.freeze(['injectedChars', 'injectedTokens', 'elapsedMs']);
|
|
28
|
+
|
|
29
|
+
function codedError(code, message, detail) {
|
|
30
|
+
const error = new Error(`${code} ${message}`);
|
|
31
|
+
error.code = code;
|
|
32
|
+
if (detail !== undefined) error.detail = detail;
|
|
33
|
+
return error;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function firstString(row, keys) {
|
|
37
|
+
for (const key of keys) {
|
|
38
|
+
const value = row?.[key];
|
|
39
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim();
|
|
40
|
+
}
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function gateRowReason(row) {
|
|
45
|
+
return firstString(row, GATE_REASON_KEYS);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function gateRowToken(row) {
|
|
49
|
+
for (const key of GATE_TOKEN_KEYS) {
|
|
50
|
+
const value = Number(row?.[key]);
|
|
51
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function gateRowLatency(row) {
|
|
57
|
+
for (const key of GATE_LATENCY_KEYS) {
|
|
58
|
+
const value = Number(row?.[key]);
|
|
59
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function isSkipGateRow(row) {
|
|
65
|
+
if (row?.skipped === true || row?.blocked === true) return true;
|
|
66
|
+
for (const field of GATE_SKIP_FIELDS) {
|
|
67
|
+
const value = row?.[field];
|
|
68
|
+
if (typeof value === 'string' && GATE_SKIP_RE.test(value)) return true;
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function rowDayKey(row) {
|
|
74
|
+
for (const key of ['at', 'ts', 'time', 'timestamp', 'date']) {
|
|
75
|
+
const value = row?.[key];
|
|
76
|
+
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) return value.slice(0, 10);
|
|
77
|
+
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
|
78
|
+
}
|
|
79
|
+
return '';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function todayDayKey(now = new Date()) {
|
|
83
|
+
const date = now instanceof Date ? now : new Date(now);
|
|
84
|
+
const year = date.getFullYear();
|
|
85
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
86
|
+
const day = String(date.getDate()).padStart(2, '0');
|
|
87
|
+
return `${year}-${month}-${day}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 由注入结果构造 gate/recall 共用度量:字符数、token 估算(2 字/token,与预算口径一致)、耗时。
|
|
91
|
+
export function buildGateMetrics(input = {}) {
|
|
92
|
+
const chars = Math.max(0, Math.floor(Number(input.injectedChars) || 0));
|
|
93
|
+
const elapsedMs = Math.max(0, Math.floor(Number(input.elapsedMs) || 0));
|
|
94
|
+
return { injectedChars: chars, injectedTokens: Math.ceil(chars / 2), elapsedMs };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function withGateMetrics(row, metrics) {
|
|
98
|
+
const base = { ...(row ?? {}) };
|
|
99
|
+
if (!metrics) return base;
|
|
100
|
+
const built = buildGateMetrics(metrics);
|
|
101
|
+
for (const key of GATE_METRIC_KEYS) base[key] = built[key];
|
|
102
|
+
return base;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function gateMetricFields(row) {
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const key of GATE_METRIC_KEYS) {
|
|
108
|
+
const value = Number(row?.[key]);
|
|
109
|
+
if (Number.isFinite(value)) out[key] = value;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// gate-log.mjs 的 appendChainedRow 补丁用:只把有限数值字段并入 sha 域。
|
|
115
|
+
export function applyGateMetricsToDomain(domain, metrics) {
|
|
116
|
+
const base = { ...(domain ?? {}) };
|
|
117
|
+
if (!metrics) return base;
|
|
118
|
+
const built = buildGateMetrics(metrics);
|
|
119
|
+
for (const key of GATE_METRIC_KEYS) base[key] = built[key];
|
|
120
|
+
return base;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function assertGateRow(row, options = {}) {
|
|
124
|
+
const requireReason = options.requireReason !== false;
|
|
125
|
+
const requireMetrics = options.requireMetrics === true;
|
|
126
|
+
if (requireReason && gateRowReason(row) === '') {
|
|
127
|
+
throw codedError('E_HG_GATE_ROW_REASON', 'gate 行必须有非空 reason', { row });
|
|
128
|
+
}
|
|
129
|
+
if (requireMetrics && (gateRowToken(row) === null || gateRowLatency(row) === null)) {
|
|
130
|
+
throw codedError('E_HG_GATE_ROW_METRICS', '召回注入 gate 行必须带 injectedTokens 与 elapsedMs', { row });
|
|
131
|
+
}
|
|
132
|
+
return row;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function gateLogRatio(rows) {
|
|
136
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
137
|
+
return {
|
|
138
|
+
rows: list.length,
|
|
139
|
+
withReason: list.filter((row) => gateRowReason(row) !== '').length,
|
|
140
|
+
withToken: list.filter((row) => gateRowToken(row) !== null).length,
|
|
141
|
+
withLatency: list.filter((row) => gateRowLatency(row) !== null).length,
|
|
142
|
+
skipRows: list.filter(isSkipGateRow).length,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// L7 判据 b 的纯函数重放(gate-log):当日行>0、每行有 reason、≥1 行带 token、≥1 行带延迟、skip=0。
|
|
147
|
+
export function l7GateLogVerdict(rows, options = {}) {
|
|
148
|
+
const day = String(options.day ?? todayDayKey());
|
|
149
|
+
const todayRows = (Array.isArray(rows) ? rows : []).filter((row) => rowDayKey(row) === day);
|
|
150
|
+
const skipRows = todayRows.filter(isSkipGateRow);
|
|
151
|
+
const reasonsMissing = todayRows.filter((row) => gateRowReason(row) === '').length;
|
|
152
|
+
const withToken = todayRows.filter((row) => gateRowToken(row) !== null).length;
|
|
153
|
+
const withLatency = todayRows.filter((row) => gateRowLatency(row) !== null).length;
|
|
154
|
+
return {
|
|
155
|
+
day,
|
|
156
|
+
todayRows: todayRows.length,
|
|
157
|
+
reasonsMissing,
|
|
158
|
+
withToken,
|
|
159
|
+
withLatency,
|
|
160
|
+
skipRows: skipRows.length,
|
|
161
|
+
skipReasons: skipRows.map((row) => ({ gate: row?.gate, decision: row?.decision, reason: gateRowReason(row) })),
|
|
162
|
+
pass: todayRows.length > 0 && reasonsMissing === 0 && withToken >= 1 && withLatency >= 1 && skipRows.length === 0,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// L7 判据 c 的纯函数重放(recall-log):当日行>0、skip=0、injected 行带 token、≥1 行带延迟。
|
|
167
|
+
export function l7RecallLogVerdict(rows, options = {}) {
|
|
168
|
+
const day = String(options.day ?? todayDayKey());
|
|
169
|
+
const todayRows = (Array.isArray(rows) ? rows : []).filter((row) => rowDayKey(row) === day);
|
|
170
|
+
const skipRows = todayRows.filter(isSkipGateRow);
|
|
171
|
+
const injectedRows = todayRows.filter((row) => Number(row?.injectedCount) > 0 || row?.injected === true);
|
|
172
|
+
const injectedMissingToken = injectedRows.filter((row) => gateRowToken(row) === null).length;
|
|
173
|
+
const withLatency = todayRows.filter((row) => gateRowLatency(row) !== null).length;
|
|
174
|
+
return {
|
|
175
|
+
day,
|
|
176
|
+
todayRows: todayRows.length,
|
|
177
|
+
injectedRows: injectedRows.length,
|
|
178
|
+
injectedMissingToken,
|
|
179
|
+
withLatency,
|
|
180
|
+
skipRows: skipRows.length,
|
|
181
|
+
pass: todayRows.length > 0 && skipRows.length === 0 && injectedMissingToken === 0 && withLatency >= 1,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function assertNoSkipRows(rows, label = 'gate-log') {
|
|
186
|
+
const skipRows = (Array.isArray(rows) ? rows : []).filter(isSkipGateRow);
|
|
187
|
+
if (skipRows.length > 0) {
|
|
188
|
+
throw codedError('E_HG_GATE_SKIP_ROWS', `${label} 出现 skip 行 ${skipRows.length} 条`, { skipRows });
|
|
189
|
+
}
|
|
190
|
+
return rows;
|
|
191
|
+
}
|