@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
package/src/memory/reinforce.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// stripped; any mismatch restores the pre-write backup and throws.
|
|
7
7
|
|
|
8
8
|
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
9
10
|
|
|
10
11
|
import { memoryRootFromConfig, resolveInside, relativePath, memoryError } from './paths.js';
|
|
11
12
|
import {
|
|
@@ -16,9 +17,103 @@ import {
|
|
|
16
17
|
appendAudit, backupFile, restoreBackup, writeFileAtomic,
|
|
17
18
|
} from './state.js';
|
|
18
19
|
import { manifestPath, refreshManifest } from './manifest.js';
|
|
20
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
19
21
|
|
|
20
22
|
export const MAX_STRENGTH = 9;
|
|
21
23
|
|
|
24
|
+
// —— D16 指令加权(X5 落盘门):卡正文里的「记住 / 重要 / 永远」把 salience +1(cap 5,只升),
|
|
25
|
+
// 并追加 emphasis.jsonl(≤1,000 行 / 180d)。「不重要 / 别记住 / 不用记」等否定表达优先,只当忽略。
|
|
26
|
+
export const SALIENCE_MAX = 5;
|
|
27
|
+
export const EMPHASIS_SCHEMA = 'hardgate-emphasis/v1';
|
|
28
|
+
export const EMPHASIS_REL = '.longlive/hardgate/emphasis.jsonl';
|
|
29
|
+
export const EMPHASIS_MAX_ROWS = 1000;
|
|
30
|
+
export const EMPHASIS_RETENTION_DAYS = 180;
|
|
31
|
+
export const EMPHASIS_KEYWORDS = Object.freeze(['记住', '重要', '永远']);
|
|
32
|
+
export const EMPHASIS_NEGATIONS = Object.freeze(['不重要', '别记住', '不用记', '不必记', '不永远', '不要记', '别再提醒']);
|
|
33
|
+
export const EMPHASIS_GATE_EVENT = 'hg.d16.fail';
|
|
34
|
+
|
|
35
|
+
const EMPHASIS_DAY_MS = 24 * 60 * 60 * 1000;
|
|
36
|
+
|
|
37
|
+
/** 探针:本模块已支持 emphasis 落盘门(d16 夹具据此判定是否 PREREQ)。 */
|
|
38
|
+
export function emphasisSupported() {
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 否定优先:正文先查否定表达,命中即忽略,避免「不重要」里的「重要」误升。 */
|
|
43
|
+
export function detectEmphasis(body) {
|
|
44
|
+
const text = typeof body === 'string' ? body : '';
|
|
45
|
+
for (const word of EMPHASIS_NEGATIONS) {
|
|
46
|
+
if (text.includes(word)) return { emphasis: false, keyword: null, negated: true };
|
|
47
|
+
}
|
|
48
|
+
for (const word of EMPHASIS_KEYWORDS) {
|
|
49
|
+
if (text.includes(word)) return { emphasis: true, keyword: word, negated: false };
|
|
50
|
+
}
|
|
51
|
+
return { emphasis: false, keyword: null, negated: false };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function gateFail(root, code, message) {
|
|
55
|
+
try {
|
|
56
|
+
appendGateLog(root, {
|
|
57
|
+
sessionId: null,
|
|
58
|
+
turn: 0,
|
|
59
|
+
gate: EMPHASIS_GATE_EVENT,
|
|
60
|
+
decision: 'fail',
|
|
61
|
+
reason: code,
|
|
62
|
+
evidence: [String(message ?? '')],
|
|
63
|
+
});
|
|
64
|
+
} catch {
|
|
65
|
+
// 门事件写失败不得遮蔽原始错误。
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function emphasisPathOf(root) {
|
|
70
|
+
return path.join(root, ...EMPHASIS_REL.split('/'));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 追加一行 emphasis 记录;账本写失败按 §19 只记 hg.state.emphasis.fail,不阻断记忆写。 */
|
|
74
|
+
function appendEmphasisRow(root, row, now) {
|
|
75
|
+
try {
|
|
76
|
+
const file = emphasisPathOf(root);
|
|
77
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
78
|
+
const rows = [];
|
|
79
|
+
if (fs.existsSync(file)) {
|
|
80
|
+
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
81
|
+
if (line.trim() === '') continue;
|
|
82
|
+
try {
|
|
83
|
+
rows.push(JSON.parse(line));
|
|
84
|
+
} catch {
|
|
85
|
+
// 坏行按不可信丢弃,不让账本损坏阻断增益写入。
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const cutoff = now.getTime() - EMPHASIS_RETENTION_DAYS * EMPHASIS_DAY_MS;
|
|
90
|
+
const kept = rows.filter((item) => {
|
|
91
|
+
const at = Date.parse(String(item?.at ?? ''));
|
|
92
|
+
return !(Number.isFinite(at) && at < cutoff);
|
|
93
|
+
});
|
|
94
|
+
kept.push(row);
|
|
95
|
+
const tail = kept.length > EMPHASIS_MAX_ROWS ? kept.slice(kept.length - EMPHASIS_MAX_ROWS) : kept;
|
|
96
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
97
|
+
fs.writeFileSync(tmp, tail.map((item) => JSON.stringify(item)).join('\n') + '\n', 'utf8');
|
|
98
|
+
fs.renameSync(tmp, file);
|
|
99
|
+
return file;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
try {
|
|
102
|
+
appendGateLog(root, {
|
|
103
|
+
sessionId: null,
|
|
104
|
+
turn: 0,
|
|
105
|
+
gate: 'hg.state.emphasis.fail',
|
|
106
|
+
decision: 'fail',
|
|
107
|
+
reason: 'EMPHASIS_LEDGER_APPEND_FAILED',
|
|
108
|
+
evidence: [String(error?.message ?? error)],
|
|
109
|
+
});
|
|
110
|
+
} catch {
|
|
111
|
+
// 状态门同样不阻断。
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
22
117
|
/** memory_reinforce: `path` is required; everything else has safe defaults. */
|
|
23
118
|
export function memoryReinforce(args = {}, config = {}) {
|
|
24
119
|
const root = memoryRootFromConfig(config);
|
|
@@ -33,14 +128,20 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
33
128
|
try {
|
|
34
129
|
stat = fs.lstatSync(abs);
|
|
35
130
|
} catch (error) {
|
|
131
|
+
gateFail(root, 'E_CARD_NOT_FOUND', abs);
|
|
36
132
|
throw memoryError('E_CARD_NOT_FOUND', `找不到记忆卡:${abs}`, error);
|
|
37
133
|
}
|
|
38
134
|
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
135
|
+
gateFail(root, 'E_NOT_A_CARD', abs);
|
|
39
136
|
throw memoryError('E_NOT_A_CARD', `不是普通文件,拒绝改写:${abs}`);
|
|
40
137
|
}
|
|
41
138
|
|
|
42
139
|
const original = fs.readFileSync(abs, 'utf8');
|
|
43
140
|
const parsed = parseFrontmatter(original);
|
|
141
|
+
const emphasis = detectEmphasis(parsed.body);
|
|
142
|
+
const salienceBefore = parsed.fields.salience;
|
|
143
|
+
// 只升不降:命中关键词 salience +1 且 cap 5;未命中/否定命中一列不动。
|
|
144
|
+
const salienceAfter = emphasis.emphasis ? Math.min(SALIENCE_MAX, salienceBefore + 1) : salienceBefore;
|
|
44
145
|
const before = {
|
|
45
146
|
strength: parsed.fields.strength,
|
|
46
147
|
last_used: parsed.fields.last_used,
|
|
@@ -53,6 +154,7 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
53
154
|
last_used: today,
|
|
54
155
|
revisions: parsed.fields.revisions + 1,
|
|
55
156
|
};
|
|
157
|
+
if (emphasis.emphasis && salienceAfter !== salienceBefore) next.salience = salienceAfter;
|
|
56
158
|
const reason = typeof args.reason === 'string' && args.reason.trim()
|
|
57
159
|
? args.reason.trim().replace(/[\r\n]+/g, ' ').slice(0, 120)
|
|
58
160
|
: '被真实使用';
|
|
@@ -75,6 +177,9 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
75
177
|
if (reparsed.fields.revisions !== next.revisions) {
|
|
76
178
|
problems.push(`revisions ${reparsed.fields.revisions} != ${next.revisions}`);
|
|
77
179
|
}
|
|
180
|
+
if (emphasis.emphasis && reparsed.fields.salience !== salienceAfter) {
|
|
181
|
+
problems.push(`salience ${reparsed.fields.salience} != ${salienceAfter}`);
|
|
182
|
+
}
|
|
78
183
|
if (normalizedBody(parsed.body) !== normalizedBody(reparsed.body)) {
|
|
79
184
|
problems.push('正文段被改动');
|
|
80
185
|
}
|
|
@@ -89,8 +194,10 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
89
194
|
try {
|
|
90
195
|
restoreBackup(root, backup.path, abs);
|
|
91
196
|
} catch (restoreError) {
|
|
197
|
+
gateFail(root, 'E_ROLLBACK_FAILED', abs);
|
|
92
198
|
throw memoryError('E_ROLLBACK_FAILED', `写后读回/解析失败且无法从备份恢复:${abs}`, restoreError);
|
|
93
199
|
}
|
|
200
|
+
gateFail(root, 'E_REINFORCE_VERIFY', abs);
|
|
94
201
|
throw memoryError(
|
|
95
202
|
'E_REINFORCE_VERIFY',
|
|
96
203
|
`写后读回/解析/校验失败,已回滚:${abs}${error instanceof Error && error.code ? `(${error.code})` : ''}`,
|
|
@@ -101,8 +208,10 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
101
208
|
try {
|
|
102
209
|
restoreBackup(root, backup.path, abs);
|
|
103
210
|
} catch (restoreError) {
|
|
211
|
+
gateFail(root, 'E_ROLLBACK_FAILED', abs);
|
|
104
212
|
throw memoryError('E_ROLLBACK_FAILED', `写后校验失败且回滚失败:${abs}`, restoreError);
|
|
105
213
|
}
|
|
214
|
+
gateFail(root, 'E_REINFORCE_VERIFY', problems.join(';'));
|
|
106
215
|
throw memoryError('E_REINFORCE_VERIFY', `写后校验失败,已回滚:${problems.join(';')}`);
|
|
107
216
|
}
|
|
108
217
|
|
|
@@ -113,6 +222,23 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
113
222
|
now,
|
|
114
223
|
});
|
|
115
224
|
|
|
225
|
+
// D16:命中加权词才落 emphasis 账本(只升;写失败只记状态门,不阻断记忆写)。
|
|
226
|
+
let emphasisLedger = null;
|
|
227
|
+
if (emphasis.emphasis) {
|
|
228
|
+
emphasisLedger = appendEmphasisRow(root, {
|
|
229
|
+
schema: EMPHASIS_SCHEMA,
|
|
230
|
+
card: relativePath(root, abs),
|
|
231
|
+
keyword: emphasis.keyword,
|
|
232
|
+
salienceBefore,
|
|
233
|
+
salienceAfter,
|
|
234
|
+
capped: salienceBefore >= SALIENCE_MAX,
|
|
235
|
+
at: now.toISOString(),
|
|
236
|
+
day: today,
|
|
237
|
+
sessionId: typeof args.sessionId === 'string' ? args.sessionId : null,
|
|
238
|
+
turn: Number.isInteger(args.turn) ? args.turn : 0,
|
|
239
|
+
}, now);
|
|
240
|
+
}
|
|
241
|
+
|
|
116
242
|
// B3: keep an opted-in manifest honest after a legitimate card edit. The
|
|
117
243
|
// manifest is derived data, so a refresh failure must not fail the memory
|
|
118
244
|
// write itself; verifyManifest will report the now-stale entry instead.
|
|
@@ -130,16 +256,26 @@ export function memoryReinforce(args = {}, config = {}) {
|
|
|
130
256
|
path: abs,
|
|
131
257
|
rel: relativePath(root, abs),
|
|
132
258
|
before,
|
|
133
|
-
after: next,
|
|
259
|
+
after: { ...next, salience: salienceAfter, emphasis: emphasis.emphasis },
|
|
134
260
|
capped: parsed.fields.strength >= MAX_STRENGTH,
|
|
135
261
|
bodyIdentical: true,
|
|
136
262
|
revLine,
|
|
137
263
|
backup: backup.path,
|
|
138
264
|
backupRel: backup.rel,
|
|
139
265
|
sha256: backup.sha256,
|
|
266
|
+
emphasis: {
|
|
267
|
+
applied: emphasis.emphasis,
|
|
268
|
+
keyword: emphasis.keyword,
|
|
269
|
+
negated: emphasis.negated,
|
|
270
|
+
salienceBefore,
|
|
271
|
+
salienceAfter,
|
|
272
|
+
ledger: emphasisLedger,
|
|
273
|
+
},
|
|
140
274
|
manifest,
|
|
141
275
|
message:
|
|
142
276
|
`已加固 ${relativePath(root, abs)}:strength ${before.strength}→${next.strength}` +
|
|
143
|
-
`${next.strength === MAX_STRENGTH ? '(到顶 9)' : ''},last_used=${today},revisions ${before.revisions}→${next.revisions}
|
|
277
|
+
`${next.strength === MAX_STRENGTH ? '(到顶 9)' : ''},last_used=${today},revisions ${before.revisions}→${next.revisions}` +
|
|
278
|
+
`${emphasis.emphasis ? `,指令加权 salience ${salienceBefore}→${salienceAfter}(keyword=${emphasis.keyword})` : ''}` +
|
|
279
|
+
`;正文逐字节一致,备份 ${backup.rel}`,
|
|
144
280
|
};
|
|
145
281
|
}
|
package/src/memory/retention.js
CHANGED
|
@@ -18,6 +18,9 @@
|
|
|
18
18
|
import fs from 'node:fs';
|
|
19
19
|
import path from 'node:path';
|
|
20
20
|
|
|
21
|
+
// B7b 草案:冷层门禁(P5/P6)。retention.js 只做判定,不删文件。
|
|
22
|
+
import { evaluateRetentionColdGate } from '../retention/cold-gate.mjs';
|
|
23
|
+
|
|
21
24
|
export const RETENTION_SCHEMA = 'retention/v1';
|
|
22
25
|
export const RETENTION_LAYERS = Object.freeze(['L0', 'L1', 'L2', 'L3']);
|
|
23
26
|
export const PROTECTED_MANIFEST = '.longlive/protected.json';
|
|
@@ -107,6 +110,37 @@ export function assertDeletable({ memoryRoot, relPath }) {
|
|
|
107
110
|
throw error;
|
|
108
111
|
}
|
|
109
112
|
|
|
113
|
+
/**
|
|
114
|
+
* B7b:删除前冷档判定(只读)。返回 {allowed, code, reason, gate};不抛。
|
|
115
|
+
* - 未配置冷档:allowed=true(2.0.0 legacy 行为),但 reason='cold-archive-not-configured',
|
|
116
|
+
* 调用方必须写 gate-log 提示;
|
|
117
|
+
* - 已配置但未 migrated / 离线 / 状态坏:allowed=false,调用方不得删除、不得降级。
|
|
118
|
+
*/
|
|
119
|
+
export function isColdDeletionAllowed({ memoryRoot, relPath = null, config = null, now = new Date(), online, sha256 = null } = {}) {
|
|
120
|
+
if (relPath !== null) {
|
|
121
|
+
const gate = evaluateRetentionColdGate({ memoryRoot, config, now, online, requireConfigured: true });
|
|
122
|
+
if (gate.allowDeleting !== true) return { allowed: false, code: gate.code, reason: gate.reason, gate };
|
|
123
|
+
const check = assertDeletable({ memoryRoot, relPath });
|
|
124
|
+
return { allowed: true, code: null, reason: gate.reason, layer: check.layer, gate };
|
|
125
|
+
}
|
|
126
|
+
const gate = evaluateRetentionColdGate({ memoryRoot, config, now, online });
|
|
127
|
+
return { allowed: gate.allowDeleting === true, code: gate.code, reason: gate.reason, gate };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** B7b:assertDeletable 的冷档扩展版。先 A6 保护判定,再冷档判定;不通过一律抛错。 */
|
|
131
|
+
export function assertColdDeletable({ memoryRoot, relPath, config = null, now = new Date(), online } = {}) {
|
|
132
|
+
const gate = evaluateRetentionColdGate({ memoryRoot, config, now, online, requireConfigured: true });
|
|
133
|
+
if (gate.allowDeleting !== true) {
|
|
134
|
+
const error = new Error(`冷档未就绪,拒绝删除:${normRel(relPath)}(${gate.code ?? 'E_HG_RETENTION_UNMIGRATED'})`);
|
|
135
|
+
error.code = gate.code ?? 'E_HG_RETENTION_UNMIGRATED';
|
|
136
|
+
error.status = 403;
|
|
137
|
+
error.gate = gate;
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
const check = assertDeletable({ memoryRoot, relPath });
|
|
141
|
+
return { ok: true, layer: check.layer, gate };
|
|
142
|
+
}
|
|
143
|
+
|
|
110
144
|
/** Executed deletions always leave an audit row (action=archive) in audit/records.jsonl. */
|
|
111
145
|
export function auditRetentionRows({ memoryRoot, moved = [], auditKey = null, questionId = 'unknown' } = {}) {
|
|
112
146
|
const rows = [];
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// B3 已落 worktree · 每轮统一预算块(单一拆账,单位=字符/字;2026-11-29 接线于 src/recall/index.js composeInjectionTurnBudget)
|
|
2
|
+
//
|
|
3
|
+
// 规格依据:
|
|
4
|
+
// - DESIGN.v0.5.2 预算节(L103):per-turn 注入总上限 2,000 字;九项拆账;超限从尾裁剪;
|
|
5
|
+
// 余量 240 不得被单项挤占;2,000 字 ≈ 1,000 token;开机卡/深度档另账。
|
|
6
|
+
// - V0.5.2-MERGE-PLAN §10(L89-104):同一张九项表,合计 2,000。
|
|
7
|
+
// - checks/lib/breaking-map.json B3:tokens 990 / 240;sumTokens 九项;expectedSum 2000。
|
|
8
|
+
//
|
|
9
|
+
// 机械可识别性(L3/L7 的验收口径):
|
|
10
|
+
// - 九个数值必须在同一文件里各自独立出现(L3 的 countStandalone 正则 `(?<![\d,])V(?![\d,])`;
|
|
11
|
+
// L7 的 `(^|[^0-9])V([^0-9]|$)`),所以本文件每个数值都写成独立的 `= 数字;` 一行,
|
|
12
|
+
// 对象字面量只引用常量、不重复写裸数字。
|
|
13
|
+
// - 120 必须独立出现 ≥2 次(前瞻 120 + 复习 120),且唯一值和必须 = 2,000。
|
|
14
|
+
// - 本文件不得出现被废弃的旧预算值(1,600 / 1,680 / 2,060 / 2,233 / 4,000 裸数字),
|
|
15
|
+
// 旧值只在测试里作为反事实输入传入,不写进源码。
|
|
16
|
+
//
|
|
17
|
+
// 本模块只做「预算口径 + 裁剪 + 机械自审」,不 import 插件内其它模块,便于单文件搬进 worktree。
|
|
18
|
+
|
|
19
|
+
export const TURN_BUDGET_SCHEMA = 'turn-budget/v1';
|
|
20
|
+
|
|
21
|
+
export const TURN_BUDGET_TOTAL_CHARS = 2000;
|
|
22
|
+
export const TURN_BUDGET_RECALL_CHARS = 990;
|
|
23
|
+
export const TURN_BUDGET_WORKING_CHARS = 300;
|
|
24
|
+
export const TURN_BUDGET_PROSPECTIVE_CHARS = 120;
|
|
25
|
+
export const TURN_BUDGET_REVIEW_CHARS = 120;
|
|
26
|
+
export const TURN_BUDGET_ANTI_FABRICATION_CHARS = 50;
|
|
27
|
+
export const TURN_BUDGET_CONFLICT_CHARS = 40;
|
|
28
|
+
export const TURN_BUDGET_ACTIVITY_CHARS = 60;
|
|
29
|
+
export const TURN_BUDGET_ALERT_CHARS = 80;
|
|
30
|
+
export const TURN_BUDGET_MARGIN_CHARS = 240;
|
|
31
|
+
|
|
32
|
+
// 九项车道(顺序即注入顺序):召回 → 工作记忆 → 前瞻 → 复习 → 防编 → 冲突 → 活动 → 告警 → 余量。
|
|
33
|
+
export const TURN_BUDGET_LANE_ORDER = Object.freeze([
|
|
34
|
+
'recall',
|
|
35
|
+
'working',
|
|
36
|
+
'prospective',
|
|
37
|
+
'review',
|
|
38
|
+
'antiFabrication',
|
|
39
|
+
'conflict',
|
|
40
|
+
'activity',
|
|
41
|
+
'alert',
|
|
42
|
+
'margin',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
export const TURN_BUDGET_LANES = Object.freeze({
|
|
46
|
+
recall: TURN_BUDGET_RECALL_CHARS,
|
|
47
|
+
working: TURN_BUDGET_WORKING_CHARS,
|
|
48
|
+
prospective: TURN_BUDGET_PROSPECTIVE_CHARS,
|
|
49
|
+
review: TURN_BUDGET_REVIEW_CHARS,
|
|
50
|
+
antiFabrication: TURN_BUDGET_ANTI_FABRICATION_CHARS,
|
|
51
|
+
conflict: TURN_BUDGET_CONFLICT_CHARS,
|
|
52
|
+
activity: TURN_BUDGET_ACTIVITY_CHARS,
|
|
53
|
+
alert: TURN_BUDGET_ALERT_CHARS,
|
|
54
|
+
margin: TURN_BUDGET_MARGIN_CHARS,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// 超限从尾裁剪的顺序:先裁增值最低的车道;防编 / 告警 / 余量是保护车道,不参与裁剪。
|
|
58
|
+
export const TURN_BUDGET_TRIM_ORDER = Object.freeze([
|
|
59
|
+
'review',
|
|
60
|
+
'prospective',
|
|
61
|
+
'activity',
|
|
62
|
+
'conflict',
|
|
63
|
+
'working',
|
|
64
|
+
'recall',
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
export const TURN_BUDGET_PROTECTED_LANES = Object.freeze(['antiFabrication', 'alert', 'margin']);
|
|
68
|
+
|
|
69
|
+
// 供机械自审使用的九项取值(含重复 120;L7 要求独立 120 出现 ≥2 次)。
|
|
70
|
+
export const TURN_BUDGET_BLOCK_VALUES = Object.freeze([
|
|
71
|
+
TURN_BUDGET_RECALL_CHARS,
|
|
72
|
+
TURN_BUDGET_WORKING_CHARS,
|
|
73
|
+
TURN_BUDGET_PROSPECTIVE_CHARS,
|
|
74
|
+
TURN_BUDGET_REVIEW_CHARS,
|
|
75
|
+
TURN_BUDGET_ANTI_FABRICATION_CHARS,
|
|
76
|
+
TURN_BUDGET_CONFLICT_CHARS,
|
|
77
|
+
TURN_BUDGET_ACTIVITY_CHARS,
|
|
78
|
+
TURN_BUDGET_ALERT_CHARS,
|
|
79
|
+
TURN_BUDGET_MARGIN_CHARS,
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
function codedError(code, message, detail) {
|
|
83
|
+
const error = new Error(`${code} ${message}`);
|
|
84
|
+
error.code = code;
|
|
85
|
+
if (detail !== undefined) error.detail = detail;
|
|
86
|
+
return error;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function sumTurnBudgetLanes(lanes = TURN_BUDGET_LANES) {
|
|
90
|
+
return TURN_BUDGET_LANE_ORDER.reduce((sum, lane) => sum + Number(lanes?.[lane] ?? 0), 0);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function assertTurnBudgetIntegrity() {
|
|
94
|
+
const sum = sumTurnBudgetLanes(TURN_BUDGET_LANES);
|
|
95
|
+
if (sum !== TURN_BUDGET_TOTAL_CHARS) {
|
|
96
|
+
throw codedError('E_HG_TURN_BUDGET_SUM', `九项预算和 ${sum} ≠ ${TURN_BUDGET_TOTAL_CHARS}`, { sum, total: TURN_BUDGET_TOTAL_CHARS });
|
|
97
|
+
}
|
|
98
|
+
const invalid = TURN_BUDGET_LANE_ORDER.filter((lane) => !(Number(TURN_BUDGET_LANES[lane]) > 0));
|
|
99
|
+
if (invalid.length > 0) {
|
|
100
|
+
throw codedError('E_HG_TURN_BUDGET_LANE', `车道预算非正数:${invalid.join(',')}`, { invalid });
|
|
101
|
+
}
|
|
102
|
+
return { schema: TURN_BUDGET_SCHEMA, total: TURN_BUDGET_TOTAL_CHARS, lanes: { ...TURN_BUDGET_LANES } };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function getTurnBudgetCap(lane) {
|
|
106
|
+
return Number(TURN_BUDGET_LANES[lane] ?? 0);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 生成本轮预算清单:单车道只允许下调(overrides),不允许把某车道抬过基准后侵占余量。
|
|
110
|
+
export function createTurnBudgetManifest(overrides = {}) {
|
|
111
|
+
const caps = {};
|
|
112
|
+
for (const lane of TURN_BUDGET_LANE_ORDER) {
|
|
113
|
+
const base = getTurnBudgetCap(lane);
|
|
114
|
+
const requested = overrides?.[lane];
|
|
115
|
+
const cap = Number.isFinite(Number(requested)) ? Math.max(0, Math.min(base, Math.floor(Number(requested)))) : base;
|
|
116
|
+
caps[lane] = cap;
|
|
117
|
+
}
|
|
118
|
+
return { schema: TURN_BUDGET_SCHEMA, totalChars: TURN_BUDGET_TOTAL_CHARS, caps: Object.freeze(caps) };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function charLength(text) {
|
|
122
|
+
return Array.from(typeof text === 'string' ? text : String(text ?? '')).length;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 按 code point 裁剪(汉字/emoji 不会被切半),超限时补省略号,返回值自带「实际字数」。
|
|
126
|
+
export function trimToChars(text, maxChars, options = {}) {
|
|
127
|
+
const source = typeof text === 'string' ? text : String(text ?? '');
|
|
128
|
+
const limit = Math.max(0, Math.floor(Number(maxChars) || 0));
|
|
129
|
+
const points = Array.from(source);
|
|
130
|
+
if (points.length <= limit) return { text: source, chars: points.length, trimmed: false };
|
|
131
|
+
if (limit === 0) return { text: '', chars: 0, trimmed: true };
|
|
132
|
+
const ellipsis = String(options.ellipsis ?? '…');
|
|
133
|
+
const keep = Math.max(0, limit - Array.from(ellipsis).length);
|
|
134
|
+
const cut = points.slice(0, keep).join('') + ellipsis;
|
|
135
|
+
return { text: cut, chars: Array.from(cut).length, trimmed: true };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function measureTurnBlocks(blocks) {
|
|
139
|
+
return (Array.isArray(blocks) ? blocks : []).map((block) => {
|
|
140
|
+
const lane = String(block?.lane ?? '');
|
|
141
|
+
const source = typeof block?.text === 'string' ? block.text : '';
|
|
142
|
+
return { lane, text: source, chars: charLength(source) };
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// 把本轮各车道文本按预算合成一条注入消息。
|
|
147
|
+
// - 每条先压到本车道 cap;
|
|
148
|
+
// - 合计超过 totalChars 时按 TRIM_ORDER 从尾继续裁;
|
|
149
|
+
// - 余量 240 只做保留额度(freeChars 里体现),任何单项不得挤占;
|
|
150
|
+
// - margin 车道不是文本块,忽略并记为 reservedMargin。
|
|
151
|
+
export function composeTurnBlocks(blocks, options = {}) {
|
|
152
|
+
const manifest = options.manifest ?? createTurnBudgetManifest();
|
|
153
|
+
const totalChars = Number.isFinite(Number(options.totalChars))
|
|
154
|
+
? Math.max(0, Math.floor(Number(options.totalChars)))
|
|
155
|
+
: Number(manifest.totalChars ?? TURN_BUDGET_TOTAL_CHARS);
|
|
156
|
+
const reservedMargin = Number(manifest.caps?.margin ?? 0);
|
|
157
|
+
const measured = measureTurnBlocks(blocks).filter((part) => part.chars > 0 && part.lane !== 'margin');
|
|
158
|
+
if (measured.length === 0) {
|
|
159
|
+
return {
|
|
160
|
+
schema: TURN_BUDGET_SCHEMA,
|
|
161
|
+
text: '',
|
|
162
|
+
parts: [],
|
|
163
|
+
totalChars,
|
|
164
|
+
usedChars: 0,
|
|
165
|
+
freeChars: totalChars,
|
|
166
|
+
reservedMargin,
|
|
167
|
+
trimmedLanes: [],
|
|
168
|
+
overBudget: false,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
const parts = measured.map((part) => {
|
|
172
|
+
const cap = Number(manifest.caps?.[part.lane] ?? 0);
|
|
173
|
+
const holder = trimToChars(part.text, cap);
|
|
174
|
+
return { lane: part.lane, text: holder.text, chars: holder.chars, cap, trimmed: holder.trimmed };
|
|
175
|
+
});
|
|
176
|
+
const trimmedLanes = new Set(parts.filter((part) => part.trimmed).map((part) => part.lane));
|
|
177
|
+
const separators = Math.max(0, parts.length - 1) * 2; // 段间 '\n\n'
|
|
178
|
+
const budgetForParts = Math.max(0, totalChars - separators);
|
|
179
|
+
let used = parts.reduce((sum, part) => sum + part.chars, 0);
|
|
180
|
+
let over = Math.max(0, used - budgetForParts);
|
|
181
|
+
for (const lane of TURN_BUDGET_TRIM_ORDER) {
|
|
182
|
+
if (over <= 0) break;
|
|
183
|
+
const part = parts.find((candidate) => candidate.lane === lane && candidate.chars > 0);
|
|
184
|
+
if (!part) continue;
|
|
185
|
+
const target = Math.max(0, part.chars - over);
|
|
186
|
+
const holder = trimToChars(part.text, target);
|
|
187
|
+
part.text = holder.text;
|
|
188
|
+
part.chars = holder.chars;
|
|
189
|
+
part.trimmed = true;
|
|
190
|
+
used = parts.reduce((sum, candidate) => sum + candidate.chars, 0);
|
|
191
|
+
over = Math.max(0, used - budgetForParts);
|
|
192
|
+
trimmedLanes.add(lane);
|
|
193
|
+
}
|
|
194
|
+
const text = parts.filter((part) => part.chars > 0).map((part) => part.text).join('\n\n');
|
|
195
|
+
const composedChars = charLength(text);
|
|
196
|
+
return {
|
|
197
|
+
schema: TURN_BUDGET_SCHEMA,
|
|
198
|
+
text,
|
|
199
|
+
parts: parts.map(({ lane, chars, cap, trimmed }) => ({ lane, chars, cap, trimmed })),
|
|
200
|
+
totalChars,
|
|
201
|
+
usedChars: composedChars,
|
|
202
|
+
freeChars: Math.max(0, totalChars - composedChars),
|
|
203
|
+
reservedMargin,
|
|
204
|
+
trimmedLanes: [...trimmedLanes],
|
|
205
|
+
overBudget: composedChars > totalChars,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function assertTurnBudgetMessage(message, options = {}) {
|
|
210
|
+
const totalChars = Number.isFinite(Number(options.totalChars)) ? Math.max(0, Math.floor(Number(options.totalChars))) : TURN_BUDGET_TOTAL_CHARS;
|
|
211
|
+
const chars = charLength(message);
|
|
212
|
+
if (chars > totalChars) {
|
|
213
|
+
throw codedError('E_HG_TURN_BUDGET_OVERFLOW', `注入 ${chars} 字超上限 ${totalChars}`, { chars, totalChars });
|
|
214
|
+
}
|
|
215
|
+
return { chars, totalChars };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function assertInjectionWithinLane(message, lane = 'recall') {
|
|
219
|
+
const cap = getTurnBudgetCap(lane);
|
|
220
|
+
const chars = charLength(message);
|
|
221
|
+
if (chars > cap) {
|
|
222
|
+
throw codedError('E_HG_TURN_BUDGET_LANE_OVERFLOW', `车道 ${lane} 注入 ${chars} 字超上限 ${cap}`, { lane, chars, cap });
|
|
223
|
+
}
|
|
224
|
+
return { lane, chars, cap };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// DESIGN L103:2,000 字 ≈ 1,000 token(中文约 2 字/token),只用于报告与 gate-log 记录,不参与判分。
|
|
228
|
+
export function estimateTurnTokens(chars) {
|
|
229
|
+
const value = Math.max(0, Math.floor(Number(chars) || 0));
|
|
230
|
+
return Math.ceil(value / 2);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function countStandaloneL3(text, token) {
|
|
234
|
+
const re = new RegExp(`(?<![\\d,])${token}(?![\\d,])`, 'g');
|
|
235
|
+
return (String(text ?? '').match(re) ?? []).length;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function countStandaloneL7(text, token) {
|
|
239
|
+
const re = new RegExp(`(?:^|[^0-9])${token}(?:[^0-9]|$)`, 'gm');
|
|
240
|
+
return (String(text ?? '').match(re) ?? []).length;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// 机械自审:把 L3 / L7 对「统一预算块」的识别方式在本模块源文本上重放一遍。
|
|
244
|
+
// oldValues 由调用方传入(源码里不允许出现旧值,所以旧值清单不能写进本文件)。
|
|
245
|
+
export function auditBudgetBlockSource(sourceText, options = {}) {
|
|
246
|
+
const source = String(sourceText ?? '');
|
|
247
|
+
const values = TURN_BUDGET_BLOCK_VALUES.map((value) => Number(value));
|
|
248
|
+
const uniqueValues = [...new Set(values)];
|
|
249
|
+
const l3 = {};
|
|
250
|
+
const l7 = {};
|
|
251
|
+
for (const value of uniqueValues) {
|
|
252
|
+
l3[value] = countStandaloneL3(source, value);
|
|
253
|
+
l7[value] = countStandaloneL7(source, value);
|
|
254
|
+
}
|
|
255
|
+
// 两种求和口径必须分开记:L7 按数组(含重复 120)求和=2,000;L3 现状 `[...new Set(sumTokens)]` 去重后=1,880。
|
|
256
|
+
const l7Sum = values.reduce((total, value) => total + value, 0);
|
|
257
|
+
const l3UniqueSum = uniqueValues.reduce((total, value) => total + value, 0);
|
|
258
|
+
const oldValues = Array.isArray(options.oldValues) ? options.oldValues : [];
|
|
259
|
+
const oldValuesFound = oldValues
|
|
260
|
+
.map((value) => Number(value))
|
|
261
|
+
.filter((value) => Number.isFinite(value) && countStandaloneL7(source, value) > 0);
|
|
262
|
+
const missingL3 = uniqueValues.filter((value) => (l3[value] ?? 0) === 0);
|
|
263
|
+
const missingL7 = uniqueValues.filter((value) => (l7[value] ?? 0) === 0);
|
|
264
|
+
return {
|
|
265
|
+
// found 只代表「L7 口径」的机械块成立:九项独立出现、120 出现 ≥2、数组和 2,000、无旧值。
|
|
266
|
+
found: missingL3.length === 0 && missingL7.length === 0 && l7Sum === TURN_BUDGET_TOTAL_CHARS && (l7[120] ?? 0) >= 2 && oldValuesFound.length === 0,
|
|
267
|
+
l7Sum,
|
|
268
|
+
l3UniqueSum,
|
|
269
|
+
expectedSum: TURN_BUDGET_TOTAL_CHARS,
|
|
270
|
+
l7Passable: missingL7.length === 0 && l7Sum === TURN_BUDGET_TOTAL_CHARS && (l7[120] ?? 0) >= 2,
|
|
271
|
+
// 已知验收口 bug(报告第一章 P1):L3 去重求和 1,880 ≠ breaking-map.B3.expectedSum 2,000,
|
|
272
|
+
// 只改源码永远 PASS 不了,必须先由健康体检侧修 L3 的求和口径(或用例 expectedSum 改 1,880 并改规格)。
|
|
273
|
+
l3SumMatchesMap: l3UniqueSum === Number(options.l3ExpectedSum ?? TURN_BUDGET_TOTAL_CHARS),
|
|
274
|
+
missingL3,
|
|
275
|
+
missingL7,
|
|
276
|
+
count120L7: l7[120] ?? 0,
|
|
277
|
+
oldValuesFound,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function describeTurnBudget() {
|
|
282
|
+
return {
|
|
283
|
+
schema: TURN_BUDGET_SCHEMA,
|
|
284
|
+
totalChars: TURN_BUDGET_TOTAL_CHARS,
|
|
285
|
+
estimatedTokens: estimateTurnTokens(TURN_BUDGET_TOTAL_CHARS),
|
|
286
|
+
lanes: TURN_BUDGET_LANE_ORDER.map((lane) => ({ lane, chars: TURN_BUDGET_LANES[lane] })),
|
|
287
|
+
protectedLanes: [...TURN_BUDGET_PROTECTED_LANES],
|
|
288
|
+
trimOrder: [...TURN_BUDGET_TRIM_ORDER],
|
|
289
|
+
};
|
|
290
|
+
}
|