dsh-compaction-weave 0.0.0-stage → 0.3.4
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 +103 -0
- package/LICENSE +21 -0
- package/README.en.md +145 -0
- package/README.md +148 -2
- package/cordis.patch.yml +19 -0
- package/docs/architecture.md +84 -0
- package/docs/benchmarks/published-0.3.2-rc.1-tests.json +576 -0
- package/docs/benchmarks/rc2-documentation.json +41 -0
- package/docs/benchmarks/rc2-linux-tests.json +590 -0
- package/docs/benchmarks/rc2-live-and-cost.json +746 -0
- package/docs/benchmarks/rc3-host-compatibility.json +2314 -0
- package/docs/benchmarks/rc4-tests.json +617 -0
- package/docs/benchmarks/review35-compression.json +117 -0
- package/docs/benchmarks/v0.3.2-live-four-way.json +3495 -0
- package/docs/benchmarks/v0.3.2-tests.json +590 -0
- package/docs/configuration.md +131 -0
- package/docs/development.md +95 -0
- package/docs/en/architecture.md +75 -0
- package/docs/en/configuration.md +131 -0
- package/docs/en/development.md +92 -0
- package/docs/en/feedback.md +47 -0
- package/docs/en/principles.md +235 -0
- package/docs/en/testing.md +368 -0
- package/docs/en/troubleshooting.md +60 -0
- package/docs/feedback.md +47 -0
- package/docs/images/principles-context.en.svg +77 -0
- package/docs/images/principles-context.zh.svg +77 -0
- package/docs/images/principles-pipeline.en.svg +93 -0
- package/docs/images/principles-pipeline.zh.svg +93 -0
- package/docs/images/principles-recovery.en.svg +46 -0
- package/docs/images/principles-recovery.zh.svg +46 -0
- package/docs/principles.md +235 -0
- package/docs/test-results.json +634 -0
- package/docs/testing.md +358 -0
- package/docs/troubleshooting.md +60 -0
- package/lib/abort.js +13 -0
- package/lib/action-state.js +60 -0
- package/lib/atomic-replace.js +18 -0
- package/lib/attachments.js +76 -0
- package/lib/audit-reject.js +161 -0
- package/lib/audit.js +939 -0
- package/lib/cache-policy.js +71 -0
- package/lib/client.js +696 -0
- package/lib/command-compact.js +38 -0
- package/lib/command-heartbeat.js +61 -0
- package/lib/config.js +596 -0
- package/lib/constraint-scope.js +37 -0
- package/lib/continuation-budget.js +69 -0
- package/lib/continuation-pending.js +57 -0
- package/lib/continuation-progress.js +46 -0
- package/lib/continuation.js +287 -0
- package/lib/engine-entry.js +103 -0
- package/lib/engine.js +2485 -0
- package/lib/failure-diagnostics.js +220 -0
- package/lib/history-source.js +74 -0
- package/lib/history.js +712 -0
- package/lib/idle-compaction.js +64 -0
- package/lib/index.js +611 -0
- package/lib/instruction-source.js +163 -0
- package/lib/journal.js +164 -0
- package/lib/manual-error.js +179 -0
- package/lib/memory-policy.js +383 -0
- package/lib/meter.js +387 -0
- package/lib/observation-mask.js +390 -0
- package/lib/proactive.js +108 -0
- package/lib/progress-facts.js +347 -0
- package/lib/progress-state.js +30 -0
- package/lib/prompt.js +194 -0
- package/lib/reconstruct.js +72 -0
- package/lib/reference-input.js +107 -0
- package/lib/region.js +972 -0
- package/lib/source-provenance.js +58 -0
- package/lib/source-recovery.js +22 -0
- package/lib/source-refs.js +137 -0
- package/lib/state.js +46 -0
- package/lib/storage-path.js +42 -0
- package/lib/summary-budget.js +187 -0
- package/lib/summary-config.js +308 -0
- package/lib/summary-progress.js +56 -0
- package/lib/summary-retry.js +27 -0
- package/lib/summary-timeout.js +68 -0
- package/lib/summary.js +476 -0
- package/lib/tools.js +341 -0
- package/lib/transaction-host.js +252 -0
- package/lib/transaction.js +285 -0
- package/lib/validate.js +503 -0
- package/lib/version.js +3 -0
- package/lib/window.js +120 -0
- package/lib/work-report.js +55 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +71 -4
package/lib/validate.js
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
// 摘要与检查点的**提交前确定性校验**。
|
|
2
|
+
//
|
|
3
|
+
// 为什么必须有这一层:模板里写满"必须九节""必须列出每一条用户消息",
|
|
4
|
+
// 但那些只是给模型的请求。模型回一句 `Done.`,模板一个字都不管用 ——
|
|
5
|
+
// 校验缺失时它会照样被当成合格摘要提交,用户原话就此消失。
|
|
6
|
+
// 这类损失不可逆:surface 一旦替换,原文只剩归档,模型再也读不到。
|
|
7
|
+
//
|
|
8
|
+
// 两层检查的可信来源不同:
|
|
9
|
+
// 1. `validateSummaryStructure` 只能检查**模型给的**摘要正文 ——
|
|
10
|
+
// 九个小节必须齐全、必须按编号顺序、每个编号只能出现一次。
|
|
11
|
+
// 2. `validateCheckpointCoverage` 检查**我们自己拼出来的**完整检查点 ——
|
|
12
|
+
// 被压区间里每一条用户原话都必须逐字出现在里面。
|
|
13
|
+
// 这条不依赖模型守规矩:原话是 `collectRecentUserMessages` 直接从事件里
|
|
14
|
+
// 取的,模型再怎么概括也改不掉它。校验时还会额外核对"来源全集",
|
|
15
|
+
// 避免"选错了保留列表"时自己跟自己对得上。
|
|
16
|
+
//
|
|
17
|
+
// 任何一条不通过就抛错,让事务走"安全失败"路径:不替换 surface,保留原上下文。
|
|
18
|
+
|
|
19
|
+
/** 与 `prompt.js` 的 EN_SECTIONS / ZH_SECTIONS 一一对应。 */
|
|
20
|
+
const EN_SECTION_TITLES = [
|
|
21
|
+
'Primary Request and Intent',
|
|
22
|
+
'Key Technical Concepts',
|
|
23
|
+
'Files and Code Sections',
|
|
24
|
+
'Errors and Fixes',
|
|
25
|
+
'Problem Solving',
|
|
26
|
+
'All User Messages',
|
|
27
|
+
'Pending Tasks',
|
|
28
|
+
'Work Completed',
|
|
29
|
+
'Context for Continuing Work',
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
const ZH_SECTION_TITLES = [
|
|
33
|
+
'用户的核心请求与意图',
|
|
34
|
+
'关键技术概念',
|
|
35
|
+
'涉及的文件与代码',
|
|
36
|
+
'错误与修复',
|
|
37
|
+
'问题解决过程',
|
|
38
|
+
'全部用户消息',
|
|
39
|
+
'待办任务',
|
|
40
|
+
'已完成的工作',
|
|
41
|
+
'继续工作所需的上下文',
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
/** 第 6 节(All User Messages)在九节里的下标(0 基)。 */
|
|
45
|
+
const USER_MESSAGE_SECTION = 5;
|
|
46
|
+
|
|
47
|
+
function escapeRegExp(text) {
|
|
48
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 扫出所有 `## N. <title>` 形态的标题行,附带它在正文里的偏移。
|
|
53
|
+
*
|
|
54
|
+
* ⚠️ 不能用"每个标题单独 `regex.test`"来判齐全。那样只看得到"存在",
|
|
55
|
+
* 看不到"在第几位、出现了几次":把九节按 9→1 倒着写、每节只写 `(none)`,
|
|
56
|
+
* 九个正则全部命中,一份完全颠倒的空壳照样通过。顺序和唯一性必须单独查。
|
|
57
|
+
*
|
|
58
|
+
* @param {string} text
|
|
59
|
+
* @param {readonly string[]} titles
|
|
60
|
+
* @returns {{ index: number, title: string, at: number, bodyAt: number }[]}
|
|
61
|
+
*/
|
|
62
|
+
function isClosingFence(line, fence) {
|
|
63
|
+
if (!fence) return false;
|
|
64
|
+
const trimmed = line.replace(/^ {0,3}/, '').replace(/[ \t]+$/, '');
|
|
65
|
+
if (trimmed.length < fence.length) return false;
|
|
66
|
+
for (let i = 0; i < trimmed.length; i += 1) {
|
|
67
|
+
if (trimmed[i] !== fence.ch) return false;
|
|
68
|
+
}
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function findHeadings(text, titles) {
|
|
73
|
+
const found = [];
|
|
74
|
+
let fence = null;
|
|
75
|
+
const lines = text.match(/[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+$/g) ?? [];
|
|
76
|
+
let offset = 0;
|
|
77
|
+
for (const raw of lines) {
|
|
78
|
+
const line = raw.replace(/(?:\r\n|\r|\n)$/, '');
|
|
79
|
+
const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line);
|
|
80
|
+
if (fence !== null) {
|
|
81
|
+
if (isClosingFence(line, fence)) fence = null;
|
|
82
|
+
} else if (marker && !(marker[1][0] === '`' && line.slice(marker[0].length).includes('`'))) {
|
|
83
|
+
fence = { ch: marker[1][0], length: marker[1].length };
|
|
84
|
+
} else {
|
|
85
|
+
const match = /^ {0,3}##[ \t]+(\d+)\.\s*(.*?)\s*$/.exec(line);
|
|
86
|
+
if (match) {
|
|
87
|
+
const number = Number(match[1]);
|
|
88
|
+
if (number >= 1 && number <= titles.length && match[2] === titles[number - 1]) {
|
|
89
|
+
found.push({ index: number, title: match[2], at: offset, bodyAt: offset + line.length });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
offset += raw.length;
|
|
94
|
+
}
|
|
95
|
+
return found;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Render originals deterministically; arbitrary headings/fences in user text remain data. */
|
|
99
|
+
export function renderVerbatimUserMessages(messages) {
|
|
100
|
+
if (!messages.length) return 'No user messages in this span.';
|
|
101
|
+
return messages.map((item, index) => {
|
|
102
|
+
const blocks = Array.isArray(item.blocks) ? item.blocks : [{ type: 'text', text: item.text ?? '' }];
|
|
103
|
+
return `### User message ${index + 1} (seq ${item.seq})\n` + blocks.map((block, i) => {
|
|
104
|
+
const text = String(block.text ?? '');
|
|
105
|
+
let longest = 2;
|
|
106
|
+
for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length);
|
|
107
|
+
const fence = '`'.repeat(longest + 1);
|
|
108
|
+
return `Block ${i + 1}\n${fence}text\n${text}\n${fence}`;
|
|
109
|
+
}).join('\n\n');
|
|
110
|
+
}).join('\n\n');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Section six is generated from the independent source set, never trusted to model copying. */
|
|
114
|
+
export function materializeUserMessageSection(text, expected, language = 'en') {
|
|
115
|
+
const check = validateSummaryStructure(text, { language });
|
|
116
|
+
if (!check.ok) { const e = new Error(check.message); e.code = check.code; throw e; }
|
|
117
|
+
const headings = findHeadings(text, language === 'zh' ? ZH_SECTION_TITLES : EN_SECTION_TITLES);
|
|
118
|
+
const sixth = headings.find(h => h.index === 6), seventh = headings.find(h => h.index === 7);
|
|
119
|
+
return text.slice(0, sixth.bodyAt) + '\n\n' + renderVerbatimUserMessages(expected) + '\n\n' + text.slice(seventh.at);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Only the source-verified sixth section is excluded from prose contradiction checks. */
|
|
123
|
+
export function summaryProse(text) {
|
|
124
|
+
text = String(text ?? '');
|
|
125
|
+
for (const titles of [EN_SECTION_TITLES, ZH_SECTION_TITLES]) {
|
|
126
|
+
const headings = findHeadings(text, titles);
|
|
127
|
+
const sixth = headings.find(h => h.index === 6), seventh = headings.find(h => h.index === 7);
|
|
128
|
+
if (sixth && seventh && seventh.at > sixth.at) return text.slice(0, sixth.at) + text.slice(seventh.at);
|
|
129
|
+
}
|
|
130
|
+
return text;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const CONTINUATION_SECTION_TITLES = ['Goal', 'State', 'Next', 'Uncertain'];
|
|
134
|
+
|
|
135
|
+
function topLevelJsonKeys(source) {
|
|
136
|
+
let depth = 0;
|
|
137
|
+
let inString = false;
|
|
138
|
+
let escape = false;
|
|
139
|
+
let expectKey = false;
|
|
140
|
+
let captureStart = -1;
|
|
141
|
+
const keys = [];
|
|
142
|
+
for (let i = 0; i < source.length; i += 1) {
|
|
143
|
+
const ch = source[i];
|
|
144
|
+
if (inString) {
|
|
145
|
+
if (escape) escape = false;
|
|
146
|
+
else if (ch === '\\') escape = true;
|
|
147
|
+
else if (ch === '"') {
|
|
148
|
+
inString = false;
|
|
149
|
+
if (captureStart >= 0) {
|
|
150
|
+
keys.push(JSON.parse(source.slice(captureStart, i + 1)));
|
|
151
|
+
captureStart = -1;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (ch === '"') {
|
|
157
|
+
inString = true;
|
|
158
|
+
if (depth === 1 && expectKey) {
|
|
159
|
+
captureStart = i;
|
|
160
|
+
expectKey = false;
|
|
161
|
+
}
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
if (ch === '{' || ch === '[') {
|
|
165
|
+
if (depth === 0 && ch === '{') {
|
|
166
|
+
depth = 1;
|
|
167
|
+
expectKey = true;
|
|
168
|
+
} else {
|
|
169
|
+
depth += 1;
|
|
170
|
+
}
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (ch === '}' || ch === ']') {
|
|
174
|
+
depth -= 1;
|
|
175
|
+
if (depth === 0) break;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (ch === ',' && depth === 1) expectKey = true;
|
|
179
|
+
}
|
|
180
|
+
return keys;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Unwraps a strict top-level JSON dictionary matching the 9 required checkpoint
|
|
185
|
+
* headings (or 4 continuation headings) in exact order back into Markdown.
|
|
186
|
+
*/
|
|
187
|
+
export function unwrapJsonSectionMap(rawText, options = {}) {
|
|
188
|
+
if (typeof rawText !== 'string') return rawText;
|
|
189
|
+
let candidate = rawText.trim();
|
|
190
|
+
const fenced = /^```(?:json)?\s*\r?\n([\s\S]*?)\r?\n```\s*$/i.exec(candidate);
|
|
191
|
+
if (fenced) candidate = fenced[1].trim();
|
|
192
|
+
if (!candidate.startsWith('{') || !candidate.endsWith('}')) return rawText;
|
|
193
|
+
|
|
194
|
+
let rawKeys;
|
|
195
|
+
let parsed;
|
|
196
|
+
try {
|
|
197
|
+
rawKeys = topLevelJsonKeys(candidate);
|
|
198
|
+
parsed = JSON.parse(candidate);
|
|
199
|
+
} catch {
|
|
200
|
+
return rawText;
|
|
201
|
+
}
|
|
202
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return rawText;
|
|
203
|
+
const entries = Object.entries(parsed);
|
|
204
|
+
if (
|
|
205
|
+
rawKeys.length !== entries.length ||
|
|
206
|
+
new Set(rawKeys).size !== rawKeys.length ||
|
|
207
|
+
rawKeys.includes('__proto__') ||
|
|
208
|
+
rawKeys.some((k, idx) => k !== entries[idx][0])
|
|
209
|
+
) {
|
|
210
|
+
return rawText;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const normalizeBody = (val) => {
|
|
214
|
+
const norm = (s) => s.replace(/\r\n|\r/g, '\n').trim();
|
|
215
|
+
if (typeof val === 'string') return norm(val);
|
|
216
|
+
if (Array.isArray(val) && val.every((item) => typeof item === 'string')) return val.map((item) => norm(item)).join('\n');
|
|
217
|
+
return null;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const visitUnfencedLines = (bodyText, onLine) => {
|
|
221
|
+
let fence = null;
|
|
222
|
+
for (const raw of String(bodyText ?? '').split(/\r\n|\r|\n/)) {
|
|
223
|
+
if (fence !== null) {
|
|
224
|
+
if (isClosingFence(raw, fence)) fence = null;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const marker = /^ {0,3}(`{3,}|~{3,})/.exec(raw);
|
|
228
|
+
if (marker && !(marker[1][0] === '`' && raw.slice(marker[0].length).includes('`'))) {
|
|
229
|
+
fence = { ch: marker[1][0], length: marker[1].length };
|
|
230
|
+
if (onLine) onLine(null);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (onLine && onLine(raw) === false) return false;
|
|
234
|
+
}
|
|
235
|
+
return fence === null;
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const hasBalancedFences = (bodyText) => visitUnfencedLines(bodyText, null);
|
|
239
|
+
|
|
240
|
+
const hasBalancedFencesAndNoLevel2Heading = (bodyText) => {
|
|
241
|
+
let prevNonBlank = false;
|
|
242
|
+
return visitUnfencedLines(bodyText, (raw) => {
|
|
243
|
+
if (raw === null) {
|
|
244
|
+
prevNonBlank = false;
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
if (/^ {0,3}#{1,2}(?:[ \t]+|$)/.test(raw)) return false;
|
|
248
|
+
if (prevNonBlank && /^ {0,3}(?:=+|-+)[ \t]*$/.test(raw)) return false;
|
|
249
|
+
prevNonBlank = raw.trim().length > 0 && !/^ {0,3}(?:>|\*(?:\s*\*){2,}\s*$)/.test(raw);
|
|
250
|
+
return true;
|
|
251
|
+
});
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
const extractContHeadings = (bodyText) => {
|
|
255
|
+
const headings = [];
|
|
256
|
+
const balanced = visitUnfencedLines(bodyText, (raw) => {
|
|
257
|
+
if (raw === null) return true;
|
|
258
|
+
const m = /^ {0,3}##[ \t]+(.+?)[ \t]*$/.exec(raw);
|
|
259
|
+
if (m) headings.push(`## ${m[1]}`);
|
|
260
|
+
return true;
|
|
261
|
+
});
|
|
262
|
+
return balanced ? headings : null;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
const titles = options.language === 'zh' ? ZH_SECTION_TITLES : EN_SECTION_TITLES;
|
|
266
|
+
const expectedContHeadings = CONTINUATION_SECTION_TITLES.map((t) => `## ${t}`);
|
|
267
|
+
|
|
268
|
+
if (entries.length === 1 && typeof entries[0][1] === 'string') {
|
|
269
|
+
const inner = entries[0][1].replace(/\r\n|\r/g, '\n').trim();
|
|
270
|
+
if (!hasBalancedFences(inner)) return rawText;
|
|
271
|
+
const verified = findHeadings(inner, titles).map((h) => h.index);
|
|
272
|
+
if (
|
|
273
|
+
validateSummaryStructure(inner, options).ok === true &&
|
|
274
|
+
JSON.stringify(verified) === JSON.stringify([1, 2, 3, 4, 5, 6, 7, 8, 9])
|
|
275
|
+
) {
|
|
276
|
+
return inner;
|
|
277
|
+
}
|
|
278
|
+
const contHeadings = extractContHeadings(inner);
|
|
279
|
+
if (contHeadings && JSON.stringify(contHeadings) === JSON.stringify(expectedContHeadings)) {
|
|
280
|
+
return inner;
|
|
281
|
+
}
|
|
282
|
+
return rawText;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (entries.length === titles.length) {
|
|
286
|
+
const sections = [];
|
|
287
|
+
for (let i = 0; i < titles.length; i += 1) {
|
|
288
|
+
const [key, value] = entries[i];
|
|
289
|
+
const headingRe = new RegExp(`^(?:##[ \\t]+)?${i + 1}\\.\\s*${escapeRegExp(titles[i])}$`);
|
|
290
|
+
const body = headingRe.test(String(key).trim()) ? normalizeBody(value) : null;
|
|
291
|
+
if (body === null || !hasBalancedFencesAndNoLevel2Heading(body)) return rawText;
|
|
292
|
+
sections.push(`## ${i + 1}. ${titles[i]}\n${body}`);
|
|
293
|
+
}
|
|
294
|
+
const assembled = sections.join('\n\n');
|
|
295
|
+
if (validateSummaryStructure(assembled, options).ok !== true) return rawText;
|
|
296
|
+
const verified = findHeadings(assembled, titles).map((h) => h.index);
|
|
297
|
+
if (JSON.stringify(verified) !== JSON.stringify([1, 2, 3, 4, 5, 6, 7, 8, 9])) return rawText;
|
|
298
|
+
return assembled;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (entries.length === CONTINUATION_SECTION_TITLES.length) {
|
|
302
|
+
const sections = [];
|
|
303
|
+
for (let i = 0; i < CONTINUATION_SECTION_TITLES.length; i += 1) {
|
|
304
|
+
const [key, value] = entries[i];
|
|
305
|
+
const headingRe = new RegExp(`^(?:##[ \\t]+)?${escapeRegExp(CONTINUATION_SECTION_TITLES[i])}$`);
|
|
306
|
+
const body = headingRe.test(String(key).trim()) ? normalizeBody(value) : null;
|
|
307
|
+
if (body === null || !hasBalancedFencesAndNoLevel2Heading(body)) return rawText;
|
|
308
|
+
sections.push(`## ${CONTINUATION_SECTION_TITLES[i]}\n${body}`);
|
|
309
|
+
}
|
|
310
|
+
const assembled = sections.join('\n\n');
|
|
311
|
+
const contHeadings = extractContHeadings(assembled);
|
|
312
|
+
if (!contHeadings || JSON.stringify(contHeadings) !== JSON.stringify(expectedContHeadings)) return rawText;
|
|
313
|
+
return assembled;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return rawText;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* 摘要正文必须包含全部九个小节,**按编号顺序**、**每个编号恰好一次**,
|
|
321
|
+
* 且第六节必须有实际内容(不能只写 `(none)`)。
|
|
322
|
+
*
|
|
323
|
+
* 第六节是"用户原话"的落脚点:检查点里虽然另有一段逐字原话,
|
|
324
|
+
* 但模型读摘要时看的就是这一节。整节写成 `(none)` 等于把"用户要什么"
|
|
325
|
+
* 从摘要里删掉,只留一堆技术笔记。
|
|
326
|
+
*
|
|
327
|
+
* @param {string} summaryText 模型返回的摘要正文
|
|
328
|
+
* @param {{ language?: 'zh'|'en' }} [options]
|
|
329
|
+
* @returns {{ ok: true, sections: number } | { ok: false, code: string, message: string }}
|
|
330
|
+
*/
|
|
331
|
+
export function validateSummaryStructure(summaryText, options = {}) {
|
|
332
|
+
const text = typeof summaryText === 'string' ? summaryText : '';
|
|
333
|
+
if (text.trim().length === 0) {
|
|
334
|
+
return { ok: false, code: 'EMPTY_SUMMARY', message: 'the summary is empty' };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const titles = options.language === 'zh' ? ZH_SECTION_TITLES : EN_SECTION_TITLES;
|
|
338
|
+
const headings = findHeadings(text, titles);
|
|
339
|
+
|
|
340
|
+
const seen = new Map();
|
|
341
|
+
const duplicates = [];
|
|
342
|
+
for (const heading of headings) {
|
|
343
|
+
const count = (seen.get(heading.index) ?? 0) + 1;
|
|
344
|
+
seen.set(heading.index, count);
|
|
345
|
+
if (count === 2) duplicates.push(heading.index);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const missing = [];
|
|
349
|
+
for (let number = 1; number <= titles.length; number += 1) {
|
|
350
|
+
if (!seen.has(number)) missing.push(`${number}. ${titles[number - 1]}`);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (missing.length > 0) {
|
|
354
|
+
return {
|
|
355
|
+
ok: false,
|
|
356
|
+
code: 'SUMMARY_STRUCTURE_INVALID',
|
|
357
|
+
message: `the summary is missing ${missing.length} required section(s): ${missing.join('; ')}`,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
if (duplicates.length > 0) {
|
|
361
|
+
return {
|
|
362
|
+
ok: false,
|
|
363
|
+
code: 'SUMMARY_STRUCTURE_INVALID',
|
|
364
|
+
message: `the summary repeats section(s) ${duplicates.join(', ')}; each section must appear exactly once`,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// 顺序:第一次出现的编号序列必须严格递增。
|
|
369
|
+
const order = headings.map((heading) => heading.index);
|
|
370
|
+
for (let position = 1; position < order.length; position += 1) {
|
|
371
|
+
if (order[position] <= order[position - 1]) {
|
|
372
|
+
return {
|
|
373
|
+
ok: false,
|
|
374
|
+
code: 'SUMMARY_STRUCTURE_INVALID',
|
|
375
|
+
message: `the summary sections are out of order (found ${order[position - 1]} before ${order[position]}); sections must follow 1..${titles.length}`,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// 第六节正文:取该标题行结束到下一个标题之间的内容。
|
|
381
|
+
const userHeading = headings.find((heading) => heading.index === USER_MESSAGE_SECTION + 1);
|
|
382
|
+
const nextHeading = headings.find((heading) => heading.at > userHeading.at);
|
|
383
|
+
const sectionBody = text
|
|
384
|
+
.slice(userHeading.bodyAt, nextHeading === undefined ? text.length : nextHeading.at)
|
|
385
|
+
.trim();
|
|
386
|
+
const bare = sectionBody.replace(/^[-*\d.、\s]+/, '').trim();
|
|
387
|
+
const meaningless = bare.length === 0 || /^(\(none\)|\(无\)|none|n\/a|na|无|没有|暂无|略|待补充|-+|—+|…+|\.\.\.)$/i.test(bare);
|
|
388
|
+
if (meaningless) {
|
|
389
|
+
return {
|
|
390
|
+
ok: false,
|
|
391
|
+
code: 'SUMMARY_STRUCTURE_INVALID',
|
|
392
|
+
message: `section ${USER_MESSAGE_SECTION + 1} (${titles[USER_MESSAGE_SECTION]}) is empty; it must list the user messages`,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return { ok: true, sections: titles.length, userSectionBody: sectionBody };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 第六节必须**逐条**交代来源区间里的每一条用户消息。
|
|
401
|
+
*
|
|
402
|
+
* 只查"这一节非空"是不够的:写一句 `用户希望继续` 也是非空,但三条用户要求
|
|
403
|
+
* 里有两条根本没被提到,下一个模型读摘要时不会有任何线索知道它们存在。
|
|
404
|
+
*
|
|
405
|
+
* 只接受逐字原话按来源顺序出现;引擎以确定性渲染器生成最终清单。
|
|
406
|
+
* 单独 seq 引用不等于逐字原文,不再放行。
|
|
407
|
+
*
|
|
408
|
+
* ⚠️ 曾经这里有一条"整节只要写了 `<preserved-user-messages>` 就放行"的豁免。
|
|
409
|
+
* 它站不住:那等于说"保留段存在"可以替代"摘要交代过"。而保留段只保证原话
|
|
410
|
+
* 还在,管不了模型在摘要里把用户的要求理解成什么 —— 用户写「不要删生产数据」,
|
|
411
|
+
* 摘要写「删掉生产数据」,保留段一个字不差地躺着,豁免照样放行,两份矛盾
|
|
412
|
+
* 的指令一起进检查点。所以这条豁免被删除:**逐条**就是逐条。
|
|
413
|
+
*
|
|
414
|
+
* ⚠️ 比对用的是**来源全集**,不是我们自己挑出来的保留列表:后者挑漏了,
|
|
415
|
+
* 两边一起漏,校验会自己跟自己对上。
|
|
416
|
+
*
|
|
417
|
+
* @param {string} sectionBody 第六节正文
|
|
418
|
+
* @param {readonly {seq:number, blocks?:{type:'text',text:string}[], text?:string}[]} expected
|
|
419
|
+
* @returns {{ ok: true, listed: number } | { ok: false, code: string, message: string }}
|
|
420
|
+
*/
|
|
421
|
+
export function validateUserMessageSection(sectionBody, expected) {
|
|
422
|
+
const list = Array.isArray(expected) ? expected : [];
|
|
423
|
+
const body = typeof sectionBody === 'string' ? sectionBody : '';
|
|
424
|
+
if (list.length === 0) return { ok: true, listed: 0 };
|
|
425
|
+
|
|
426
|
+
if (body.trim() === renderVerbatimUserMessages(list).trim()) return { ok: true, listed: list.length };
|
|
427
|
+
// Raw quoted lists remain accepted only when all original blocks occur in source order.
|
|
428
|
+
let cursor = 0;
|
|
429
|
+
for (const item of list) {
|
|
430
|
+
const parts = Array.isArray(item.blocks) ? item.blocks.map(b => b.text) : [item.text ?? ''];
|
|
431
|
+
for (const part of parts) {
|
|
432
|
+
if (typeof part !== 'string') return { ok: false, code: 'SUMMARY_STRUCTURE_INVALID', message: 'invalid source text block' };
|
|
433
|
+
const at = body.indexOf(part, cursor);
|
|
434
|
+
if (at < 0) return { ok: false, code: 'SUMMARY_STRUCTURE_INVALID', message: `section 6 must reproduce every user message verbatim and in order (missing seq ${item.seq}); seq references alone are insufficient` };
|
|
435
|
+
cursor = at + part.length;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return { ok: true, listed: list.length };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* 拼好的检查点里,必须逐字包含被压区间里的每一条用户原话。
|
|
443
|
+
*
|
|
444
|
+
* 这是"用户原话不丢"的**兜底**:即使模型在摘要里把某条请求概括错了,
|
|
445
|
+
* 原话仍然躺在 `<preserved-user-messages>` 里,下一个模型读得到。
|
|
446
|
+
* 所以这里比对的是最终要写进 surface 的 `checkpointBlocks`,
|
|
447
|
+
* 而不是模型返回的 `summaryText`。
|
|
448
|
+
*
|
|
449
|
+
* ⚠️ `expected` 是**来源全集**,不能省。只比对 `preserved`(我们自己挑出来的
|
|
450
|
+
* 列表)等于让自己给自己判卷:挑漏了一条,两边一起漏,校验照样通过。
|
|
451
|
+
* 调用方必须把"区间里真实存在的用户消息"也传进来,两边取并集来查。
|
|
452
|
+
*
|
|
453
|
+
* @param {readonly {type:string, text:string}[]} checkpointBlocks
|
|
454
|
+
* @param {readonly {seq:number, blocks?:{type:'text',text:string}[], text?:string}[]} preserved
|
|
455
|
+
* @param {{ expected?: readonly {seq:number, blocks?:{type:'text',text:string}[], text?:string}[] }} [options]
|
|
456
|
+
* @returns {{ ok: true, covered: number } | { ok: false, code: string, message: string }}
|
|
457
|
+
*/
|
|
458
|
+
export function validateCheckpointCoverage(checkpointBlocks, preserved, options = {}) {
|
|
459
|
+
const required = [];
|
|
460
|
+
const pushAll = (list) => {
|
|
461
|
+
if (!Array.isArray(list)) return;
|
|
462
|
+
for (const item of list) if (item && typeof item === 'object') required.push(item);
|
|
463
|
+
};
|
|
464
|
+
pushAll(preserved);
|
|
465
|
+
pushAll(options.expected);
|
|
466
|
+
if (required.length === 0) return { ok: true, covered: 0 };
|
|
467
|
+
|
|
468
|
+
const haystack = (Array.isArray(checkpointBlocks) ? checkpointBlocks : [])
|
|
469
|
+
.map((block) => (block && typeof block.text === 'string' ? block.text : ''))
|
|
470
|
+
.join('\n');
|
|
471
|
+
|
|
472
|
+
const missing = [];
|
|
473
|
+
for (const item of required) {
|
|
474
|
+
const parts =
|
|
475
|
+
Array.isArray(item.blocks) && item.blocks.length > 0
|
|
476
|
+
? item.blocks.map((block) => block?.text).filter((value) => typeof value === 'string')
|
|
477
|
+
: typeof item.text === 'string'
|
|
478
|
+
? [item.text]
|
|
479
|
+
: [];
|
|
480
|
+
// 来源事件里被摊平后只剩空白的内容没什么可校验的,跳过而不是判失败。
|
|
481
|
+
const meaningful = parts.filter((part) => part.trim().length > 0);
|
|
482
|
+
if (meaningful.length === 0) continue;
|
|
483
|
+
// ⚠️ 逐块比对,不能把多块 join 起来比。检查点渲染时块之间会插入
|
|
484
|
+
// `--- seq N block i ---` 分隔行,join 出来的整串永远不可能作为子串出现,
|
|
485
|
+
// 那样多块消息会被判成"没覆盖",好好的压缩被无谓地拦下来。
|
|
486
|
+
const present = meaningful.every((part) => haystack.includes(part));
|
|
487
|
+
if (!present && !missing.includes(typeof item.seq === 'number' ? item.seq : -1)) {
|
|
488
|
+
missing.push(typeof item.seq === 'number' ? item.seq : -1);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
if (missing.length > 0) {
|
|
493
|
+
return {
|
|
494
|
+
ok: false,
|
|
495
|
+
code: 'CHECKPOINT_COVERAGE_INCOMPLETE',
|
|
496
|
+
message:
|
|
497
|
+
`${missing.length} user message(s) from the compacted span are not reproduced verbatim ` +
|
|
498
|
+
`in the checkpoint (seq ${missing.join(', ')})`,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
return { ok: true, covered: required.length };
|
|
503
|
+
}
|
package/lib/version.js
ADDED
package/lib/window.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// L1:窗口确定性。
|
|
2
|
+
//
|
|
3
|
+
// 这是 bili 最严重的问题之一:同一会话中途,`deepseek-flash` 的窗口被判成
|
|
4
|
+
// 917504 / 868928 / 1000000 / 750000 四个值来回跳,一次会话里跳了 353 次。
|
|
5
|
+
// 窗口一变,阈值就变,压缩决策随之失效。
|
|
6
|
+
//
|
|
7
|
+
// window 是会话首次解析的固定答案;safetyWindow 是独立的保守预算,后续只收紧。
|
|
8
|
+
// 引擎在 SessionStateStore 的写锁内解析并持久化,跨对象/进程保持首次答案。
|
|
9
|
+
// 配置映射优先决定 window;适配器较小的容量始终限制 safetyWindow。
|
|
10
|
+
// windowClampMin 仅作用于 fallback,不抬高适配器明示的小窗口。
|
|
11
|
+
let cache = new WeakMap();
|
|
12
|
+
const persistent = new Map(); // bounded process cache; not the durable source of truth
|
|
13
|
+
|
|
14
|
+
/** 供测试与"会话被彻底删除"时清场。 */
|
|
15
|
+
export function forgetLockedWindow(sessionId, provider, model) {
|
|
16
|
+
persistent.delete(JSON.stringify([sessionId]));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 供测试用:清掉所有按逻辑标识保存的锁定值。 */
|
|
20
|
+
export function resetWindowCache() {
|
|
21
|
+
persistent.clear();
|
|
22
|
+
cache = new WeakMap();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function keyOf(provider, model) {
|
|
26
|
+
return `${provider ?? '?'}/${model ?? '?'}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 从适配器声明里取窗口。`resolveModelInfo` 的返回结构在不同版本里
|
|
31
|
+
* 可能是 `info.context.contextWindow` 或 `info.contextWindow`,两种都认。
|
|
32
|
+
* @param {unknown} info
|
|
33
|
+
* @returns {number|undefined}
|
|
34
|
+
*/
|
|
35
|
+
export function contextWindowOf(info) {
|
|
36
|
+
if (!info || typeof info !== 'object') return undefined;
|
|
37
|
+
const candidates = [
|
|
38
|
+
info.context?.contextWindow,
|
|
39
|
+
info.contextWindow,
|
|
40
|
+
info.context?.window,
|
|
41
|
+
info.window,
|
|
42
|
+
info.model?.contextWindow,
|
|
43
|
+
];
|
|
44
|
+
for (const value of candidates) {
|
|
45
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 从适配器声明里取默认输出上限。
|
|
52
|
+
* @param {unknown} info
|
|
53
|
+
* @returns {number|undefined}
|
|
54
|
+
*/
|
|
55
|
+
export function defaultMaxTokensOf(info) {
|
|
56
|
+
if (!info || typeof info !== 'object') return undefined;
|
|
57
|
+
const candidates = [
|
|
58
|
+
info.defaultMaxTokens,
|
|
59
|
+
info.context?.defaultMaxTokens,
|
|
60
|
+
info.model?.defaultMaxTokens,
|
|
61
|
+
info.maxTokens,
|
|
62
|
+
];
|
|
63
|
+
for (const value of candidates) {
|
|
64
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 解析并锁定一个会话的上下文窗口。
|
|
71
|
+
*
|
|
72
|
+
* @param {object} args
|
|
73
|
+
* @param {object} args.session 会话对象(用作 WeakMap 键)
|
|
74
|
+
* @param {string|undefined} args.provider
|
|
75
|
+
* @param {string|undefined} args.model
|
|
76
|
+
* @param {number|undefined} args.adapterWindow 适配器声明的窗口
|
|
77
|
+
* @param {Readonly<Record<string, number>>} args.providerMap 配置里的显式映射
|
|
78
|
+
* @param {number} args.fallback
|
|
79
|
+
* @param {number} args.clampMin
|
|
80
|
+
* @returns {{ window: number, source: 'config'|'adapter'|'fallback'|'locked', firstResolved: number }}
|
|
81
|
+
*/
|
|
82
|
+
export function lockWindow(args) {
|
|
83
|
+
const { session, provider, model, adapterWindow, providerMap, fallback, clampMin } = args;
|
|
84
|
+
if (!session || typeof session !== 'object') throw new Error('window locking requires a session');
|
|
85
|
+
const stable = typeof session.id === 'string' ? JSON.stringify([session.id]) : undefined;
|
|
86
|
+
let previous = args.persisted ?? (stable ? persistent.get(stable) : cache.get(session)?.locked);
|
|
87
|
+
const mapped = providerMap?.[keyOf(provider, model)];
|
|
88
|
+
const trusted = firstKnown(mapped, adapterWindow);
|
|
89
|
+
const source = typeof mapped === 'number' && Number.isFinite(mapped) && mapped > 0 ? 'config' : trusted !== undefined ? 'adapter' : 'fallback';
|
|
90
|
+
const candidate = trusted ?? Math.max(fallback, clampMin);
|
|
91
|
+
const safetyCandidate = typeof adapterWindow === 'number' && Number.isFinite(adapterWindow) && adapterWindow > 0 ? Math.min(candidate, adapterWindow) : candidate;
|
|
92
|
+
if (!(Number.isFinite(candidate) && candidate > 0)) throw new Error('invalid context window');
|
|
93
|
+
if (previous && (!Number.isFinite(previous.window) || !Number.isFinite(previous.safetyWindow) || !(previous.window > 0) || !(previous.safetyWindow > 0) || previous.safetyWindow > previous.window || previous.firstResolved !== previous.window)) throw new Error('invalid durable context window');
|
|
94
|
+
// window is the immutable session answer. safetyWindow is a separate conservative budget.
|
|
95
|
+
const record = previous
|
|
96
|
+
? { ...previous, safetyWindow: Math.min(previous.safetyWindow, safetyCandidate), source: 'locked' }
|
|
97
|
+
: { window: candidate, firstResolved: candidate, safetyWindow: safetyCandidate, source };
|
|
98
|
+
cache.set(session, { locked: record });
|
|
99
|
+
if (stable) { persistent.set(stable, record); if (persistent.size > 1024) persistent.delete(persistent.keys().next().value); }
|
|
100
|
+
return { ...record };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 取第一个「可信」的窗口值:显式映射优先,其次适配器声明。 */
|
|
104
|
+
function firstKnown(mapped, adapterWindow) {
|
|
105
|
+
if (typeof mapped === 'number' && Number.isFinite(mapped) && mapped > 0) return mapped;
|
|
106
|
+
if (typeof adapterWindow === 'number' && Number.isFinite(adapterWindow) && adapterWindow > 0) {
|
|
107
|
+
return adapterWindow;
|
|
108
|
+
}
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 读取一个会话已经锁定的窗口,不触发解析。
|
|
114
|
+
* @param {object} session
|
|
115
|
+
* @param {string|undefined} provider
|
|
116
|
+
* @param {string|undefined} model
|
|
117
|
+
*/
|
|
118
|
+
export function peekLockedWindow(session, provider, model) {
|
|
119
|
+
return (typeof session?.id === 'string' ? persistent.get(JSON.stringify([session.id])) : cache.get(session)?.locked)?.window;
|
|
120
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// A small exact latest work report complements generated notes. It is assistant
|
|
2
|
+
// evidence, never a user requirement or a claim of independent verification.
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {instructionText} from './instruction-source.js';
|
|
5
|
+
import {hasProgressSignals} from './progress-state.js';
|
|
6
|
+
const MAX_REPORT_BYTES=3072;
|
|
7
|
+
const hash=blocks=>createHash('sha256').update(JSON.stringify(blocks)).digest('hex');
|
|
8
|
+
const failure=()=>Object.assign(new Error('Latest work report source cannot be verified.'),{code:'WORK_REPORT_SOURCE_UNAVAILABLE'});
|
|
9
|
+
function read(session,seq) {
|
|
10
|
+
const event=session.eventAt(seq);if(event?.type!=='assistant/message')throw failure();
|
|
11
|
+
const message=session.deriveEventMessage(event),content=message?.content;
|
|
12
|
+
if(!Array.isArray(content))return null;
|
|
13
|
+
const blocks=content.filter(b=>b.type==='text').map(b=>({type:'text',text:b.text}));
|
|
14
|
+
if(blocks.some(b=>typeof b.text!=='string'))throw failure();
|
|
15
|
+
return {seq,blocks,text:blocks.map(b=>b.text).join('\n'),sha256:hash(blocks)};
|
|
16
|
+
}
|
|
17
|
+
export function collectWorkReport(session,seqs) {
|
|
18
|
+
let latest=null;
|
|
19
|
+
for(const seq of seqs){
|
|
20
|
+
const event=session.eventAt(seq);let report;
|
|
21
|
+
if(event?.type==='assistant/message'){
|
|
22
|
+
report=read(session,seq);
|
|
23
|
+
if(!report||!hasProgressSignals(instructionText(report)))continue;
|
|
24
|
+
}else{
|
|
25
|
+
const ref=event?.type==='user/message'&&event.data?.source?.kind==='compact-checkpoint'?event.data.source.workReport:null;
|
|
26
|
+
if(!ref)continue;
|
|
27
|
+
if(!Number.isSafeInteger(ref.seq)||ref.seq<0||ref.seq>=seq||typeof ref.sha256!=='string')throw failure();
|
|
28
|
+
report=read(session,ref.seq);if(!report||report.sha256!==ref.sha256)throw failure();
|
|
29
|
+
}
|
|
30
|
+
if(!latest||report.seq>latest.seq)latest=report;
|
|
31
|
+
}
|
|
32
|
+
// Keep the newest source even when its text is too large to repeat. Dropping
|
|
33
|
+
// the reference would let an older checkpoint resurrect a stale exact report
|
|
34
|
+
// on the next merge. Oversized reports carry identity, never partial prose.
|
|
35
|
+
if(!latest)return null;
|
|
36
|
+
return Buffer.byteLength(latest.text,'utf8')<=MAX_REPORT_BYTES?latest:{seq:latest.seq,sha256:latest.sha256,omitted:true};
|
|
37
|
+
}
|
|
38
|
+
// Do not append an obsolete verbatim status beside newer retained progress.
|
|
39
|
+
// Its complete text is still in the summarizer input/archive, and its source
|
|
40
|
+
// identity survives. Only overlapping work fields can establish supersession.
|
|
41
|
+
export function scopeWorkReport(report,progress) {
|
|
42
|
+
if(!report)return report;
|
|
43
|
+
const prior=(progress?.history??[]).filter(f=>f.seq===report.seq);
|
|
44
|
+
const newer=(progress?.effective??[]).filter(f=>f.seq>report.seq&&prior.some(p=>p.key===f.key&&p.scope===f.scope));
|
|
45
|
+
if(!newer.length)return report;
|
|
46
|
+
return {seq:report.seq,sha256:report.sha256,omitted:true,supersededBy:Math.max(...newer.map(f=>f.seq))};
|
|
47
|
+
}
|
|
48
|
+
export const workReportRef=report=>report?{seq:report.seq,sha256:report.sha256}:null;
|
|
49
|
+
export function renderWorkReport(report) {
|
|
50
|
+
if(!report)return '';
|
|
51
|
+
if(report.supersededBy!==undefined)return `Historical assistant work report source seq ${report.seq}; overlapping progress has a newer original source at seq ${report.supersededBy}. Its verbatim status is not repeated here. Keep non-superseded details from the local notes or archive; use the newer original for current status. This is historical assistant evidence, not new permission.`;
|
|
52
|
+
if(report.omitted===true)return `Latest assistant work report WITHIN THIS SPAN is source seq ${report.seq}; later messages outside the span may have newer progress. Its full text exceeds the verbatim allowance; this does not make facts elsewhere unknown. Consult the generated notes or archived source for its content. Earlier report excerpts are older evidence, not proof of current status. Reconcile status for the same work item using this newer source; do not invent its contents. This is historical assistant evidence, not new permission; later user instructions still govern.`;
|
|
53
|
+
const longest=Math.max(2,...[...report.text.matchAll(/`+/g)].map(m=>m[0].length)),fence='`'.repeat(longest+1);
|
|
54
|
+
return `Latest assistant work report WITHIN THIS SPAN, source seq ${report.seq} (verbatim; not independently re-verified by the compactor). For the SAME named object and operation, newer observations supersede older status only. A plan or attempted execution does not prove success; completing an artifact does not establish passing tests. Later original messages outside this span remain authoritative; this excerpt cannot override them. Preserve its stated uncertainty; later user instructions still govern. This is historical assistant evidence, not new permission.\n${fence}text\n${report.text}\n${fence}`;
|
|
55
|
+
}
|