diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 0df8c5d4d5..57f4481f89 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -268,6 +268,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.nudgeModelDecided` | boolean | off (unset) | — | Model-decided nudge timing (#2228): an armed tier-1 nudge first asks the model — via a short side call over the session's cached prefix — whether compressing NOW helps the current task. A strict-JSON "yes" injects an explicit directive with a program-finalized span; "no", a malformed answer, or a timeout injects nothing this round. EMERGENCY arms and tier≥2 distillation always keep the legacy advisory. Off unless explicitly enabled. | | `compress.nudgeDecisionMaxTokens` | number | 200 | — | Output budget (tokens) of the model-decision side call used by nudgeModelDecided. Must be > 0. | | `compress.streamSummary` | boolean | false (unset) | — | Force preflight summarization to run as a streaming (SSE) call from the first attempt. The error-driven self-learn handles stream-mandating upstreams on its own (any 400 on a non-streaming summary triggers a one-shot SSE probe, #2494) but NEVER arms on gateway timeouts (e.g. Cloudflare HTTP 524): set this where such a gateway sits between bili and the origin, or simply to skip the one probe round-trip. | +| `compress.timestamps` | boolean | false (unset) | — | Render arrival timestamps (#4313): every rendered ref tag carries at="YYYY-MM-DD HH:mm" (UTC, minute precision) and each folded summary ends with the covered span's [folded A → B UTC] range, so a days-old plan stops competing with a minutes-old instruction on equal footing. History that predates the setting renders unmarked (times are frozen at first sight, never guessed). Enabling rewrites every already-rendered tag once — a one-time provider prefix-cache flush. | | `compress.preserveRecentMessages` | number | 3 | — | The most recent messages stay soft-protected from folds. | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | The most recent tokens stay soft-protected from folds. | | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. | @@ -1393,6 +1394,14 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Status:** ACTIVE (#2228) - **Description:** Output budget, in tokens, of the model-decision side call made when `nudgeModelDecided` is enabled. Must be > 0 (invalid values are rejected at config load). +#### `timestamps` + +- **Type:** `boolean` +- **Default:** `false` (unset) +- **Status:** ACTIVE (#4313) +- **Description:** Render arrival timestamps. When on, every rendered message ref tag carries the message's arrival time — `at="YYYY-MM-DD HH:mm"` (UTC, minute precision, frozen at first sight) — and each rendered summary carrier ends with the covered span's arrival-time range, `[folded 2026-10-22 06:14 → 2026-10-22 18:03 UTC]` (single point when the range collapses to one minute). The freeze is unconditional even while rendering is off, so enabling mid-session yields real arrival times for everything seen since deployment. History that predates the feature has no frozen time and renders UNMARKED — never guessed at. Maps to the kernel field `renderTimestamps` (acp-kernel ≥ 0.0.171). +- **Caveats:** enabling rewrites every already-rendered tag once — a one-time provider prefix-cache flush on the next turn. Keep it off for cache-critical long sessions unless the temporal signal matters. Available as a Web UI quick toggle. + #### `preserveRecentMessages` - **Type:** `number` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 31c54c69d6..dcf539f03b 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -268,6 +268,7 @@ | `compress.nudgeModelDecided` | boolean | off (unset) | — | 模型自决的压缩时机(#2228):tier-1 提醒触发时,先通过一次走会话缓存前缀的短 side call 问模型——以当前任务为前提,现在压缩是否划算。严格 JSON 的 "yes" 会注入带程序最终确定范围的明确压缩指令;"no"、格式错误或超时则本轮不注入任何内容。EMERGENCY 档与 tier≥2 蒸馏始终保留原有 advisory。默认关闭,需显式开启。 | | `compress.nudgeDecisionMaxTokens` | number | 200 | — | nudgeModelDecided 所用模型决策 side call 的输出预算(token)。必须 > 0。 | | `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。 | +| `compress.timestamps` | boolean | false (unset) | — | 渲染消息到达时间(#4313):每个已渲染的 ref 标签带 at="YYYY-MM-DD HH:mm"(UTC、分钟精度),每条折叠摘要末尾带覆盖区间的 [folded A → B UTC] 时间范围,让几天前的旧方案不再与几分钟前的新指令“看起来同时发生”。早于本设置开启的历史不打标(时间在首次看到时冻结,从不倒填猜测)。开启会把已渲染标签一次性重写——即一次性 provider 前缀缓存冲刷。 | | `compress.preserveRecentMessages` | number | 3 | — | 最近的消息软保护、免于折叠。 | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最近的 token 软保护、免于折叠。 | | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 | @@ -1396,6 +1397,14 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 - **状态:** ACTIVE (#2228) - **说明:** `nudgeModelDecided` 开启时,模型决策 side call 的输出预算(token)。必须 > 0(非法值在配置加载时被拒绝)。 +#### `timestamps` + +- **类型:** `boolean` +- **默认:** `false`(不设) +- **状态:** ACTIVE(#4313) +- **说明:** 渲染消息到达时间戳。开启后,每个已渲染的消息 ref 标签携带该消息的到达时间 `at="YYYY-MM-DD HH:mm"`(UTC、分钟精度、首见即冻结),每条渲染出的摘要载体末尾带覆盖区间的到达时间范围 `[folded 2026-10-22 06:14 → 2026-10-22 18:03 UTC]`(区间塌缩为一分钟时为单点形式)。时间冻结在渲染关闭时也无条件进行,因此中途开启能拿到部署以来所有消息的真实到达时间。早于本功能的历史消息没有冻结时间、不打标——绝不猜时间。映射到内核字段 `renderTimestamps`(acp-kernel ≥ 0.0.171)。 +- **注意:** 开启会一次性改写所有已渲染标签——下一轮产生一次性的服务商前缀缓存冲刷。对前缀缓存敏感的长会话,除非确实需要时间信号,建议保持关闭。Web UI 快捷开关已提供。 + #### `preserveRecentMessages` - **类型:** `number` diff --git a/kernel/package-lock.json b/kernel/package-lock.json index bbe88cba18..9a50787c32 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.170", + "version": "0.0.171", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.170", + "version": "0.0.171", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/kernel/package.json b/kernel/package.json index 28b2aac68f..37f51d6aef 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.170", + "version": "0.0.171", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index 5be1706e1d..4eeefbbda7 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -1056,15 +1056,33 @@ const assignRefsNode: PipelineNode = { const migratedRefs = refResult.migratedIds .map((id) => refResult.map.byRaw[id]) .filter((r): r is string => typeof r === "string" && r !== BLOCKED_REF); - const state = migratedRefs.length - ? { - ...io.state, - messageRefs: refResult.map, - renderDeferredRefs: [ - ...new Set([...(io.state.renderDeferredRefs ?? []), ...migratedRefs]), - ], - } - : { ...io.state, messageRefs: refResult.map }; + // #4313: freeze each ref's first-seen wall-clock alongside the ref map — + // refs are minted exactly once per message identity, so this is the + // message's arrival time. Unconditional (Config.renderTimestamps gates + // RENDERING only): enabling the flag mid-session yields real arrival + // times for everything seen since deployment, never "now" stamps on old + // messages. + let time = { ...(io.state.timeSnapshot ?? {}) }; + let timeChanged = false; + for (const message of io.messages) { + if (!message.id || message.id.startsWith(RETRIEVED_ID_PREFIX)) continue; + const ref = refResult.map.byRaw[message.id]; + if (!ref || ref === BLOCKED_REF || time[ref] !== undefined) continue; + time[ref] = Date.now(); + timeChanged = true; + } + const state = { + ...(migratedRefs.length + ? { + ...io.state, + messageRefs: refResult.map, + renderDeferredRefs: [ + ...new Set([...(io.state.renderDeferredRefs ?? []), ...migratedRefs]), + ], + } + : { ...io.state, messageRefs: refResult.map }), + ...(timeChanged ? { timeSnapshot: time } : {}), + }; return { ...io, state }; }, }; @@ -1085,6 +1103,7 @@ const pruneNode: PipelineNode = { ...io, messages: prune(io.messages, io.state, { isCompressTool: ctx.config.isCompressTool, + renderTimestamps: ctx.config.renderTimestamps === true, }), // #2663: keep the pre-prune resent array reachable so recommend can // judge foldability on the same input class applyCompression sees. diff --git a/kernel/src/prune.ts b/kernel/src/prune.ts index 8c5aae5f54..97bbb22c99 100644 --- a/kernel/src/prune.ts +++ b/kernel/src/prune.ts @@ -1,4 +1,5 @@ import { activeBlocks, coveredMessageIds } from "./state.js"; +import { formatUtcMinute } from "./time-fmt.js"; import type { CompressionState, CoreMessage } from "./types.js"; export const SUMMARY_HEADER = "[Compressed conversation section]"; @@ -109,6 +110,9 @@ export function isRenderedSummaryMessage( export interface PruneOptions { injectSummaries?: boolean; + /** #4313: append `[folded A → B UTC]` footers (arrival-time range of the + * block's anchor ids) to rendered summary carriers. */ + renderTimestamps?: boolean; /** * Chronological head anchoring for views with NO provider prefix cache at * stake (session handoff/restore docs). Default (false) is the pin-safe @@ -203,6 +207,7 @@ export function prune( ? lastUserIndex : messages.length, visibleCompressCallIds, + options.renderTimestamps === true, ) : []; // Summary ids of every block this session has ever created — active or @@ -240,6 +245,10 @@ interface SummaryAnchor { blockId: string; summary: string; topic?: string; + /** #4313: pre-formatted arrival-time footer of the block's anchor range + * (`[folded A → B UTC]`); undefined when timestamps are off or no anchor + * id carries a frozen time (pre-#4313 history). */ + timeFooter?: string; insertAt: number; /** True when no anchor id was present in the input (the substrate is off * the wire). Unresolved anchors park before the newest user message and @@ -251,6 +260,35 @@ interface SummaryAnchor { unresolved?: boolean; } +/** #4313: `[folded A → B UTC]` over the anchor ids' frozen arrival times + * (single point when min == max). Deterministic — read-only over + * timeSnapshot and the immutable block record. */ +function summaryTimeFooter( + state: CompressionState, + block: { directMessageIds?: string[]; effectiveMessageIds: string[] }, + renderTimestamps: boolean, +): string | undefined { + if (!renderTimestamps) return undefined; + const ids = + block.directMessageIds && block.directMessageIds.length > 0 + ? block.directMessageIds + : block.effectiveMessageIds; + const times = state.timeSnapshot; + if (!times) return undefined; + let min: number | undefined; + let max: number | undefined; + for (const id of ids) { + const t = times[state.messageRefs.byRaw[id] ?? ""]; + if (typeof t !== "number") continue; + if (min === undefined || t < min) min = t; + if (max === undefined || t > max) max = t; + } + if (min === undefined || max === undefined) return undefined; + return min === max + ? `[folded ${formatUtcMinute(min)} UTC]` + : `[folded ${formatUtcMinute(min)} → ${formatUtcMinute(max)} UTC]`; +} + function collectSummaryAnchors( state: CompressionState, baseIndexById: Map, @@ -260,6 +298,7 @@ function collectSummaryAnchors( // blocks created by one of these skip their anchor render (see the // collection site above for the rationale and the safety conditions). visibleCompressCallIds: Set, + renderTimestamps: boolean, ): SummaryAnchor[] { const anchors: SummaryAnchor[] = []; for (const block of activeBlocks(state)) { @@ -269,6 +308,12 @@ function collectSummaryAnchors( // rebuildMessages via knownSummaryIds and NOT re-injected here. if (block.compressCallId && visibleCompressCallIds.has(block.compressCallId)) continue; + // #4313: arrival-time footer over the block's DIRECT range — the same + // id set the anchor position uses below (legacy blocks fall back to the + // effective set). Refs without a frozen time (pre-#4313 history) are + // skipped, not guessed at; no times at all → no footer. + const footer = summaryTimeFooter(state, block, renderTimestamps); + // Prefer the position of an already-rendered summary (hosts may pass a // previously-pruned view): keeps the summary stable in place instead of // jumping to index 0 when the raw ids are no longer in the input. @@ -278,6 +323,7 @@ function collectSummaryAnchors( blockId: block.blockId, summary: block.summary, topic: block.topic, + timeFooter: footer, insertAt: existingIndex, }); continue; @@ -307,6 +353,7 @@ function collectSummaryAnchors( blockId: block.blockId, summary: block.summary, topic: block.topic, + timeFooter: footer, // Unresolved (no anchor id present in this input): park before the // newest user message — see prune() for the #3640/#2733 reasoning. // Tail-parking (the pre-#3640 behavior) let stale summaries land after @@ -550,7 +597,10 @@ function renderSummary(anchor: SummaryAnchor): CoreMessage { const topicLine = anchor.topic ? `${SUMMARY_HEADER} — ${anchor.topic}` : SUMMARY_HEADER; - const text = body.length === 0 ? topicLine : `${topicLine}\n${body}`; + const text = + body.length === 0 + ? topicLine + : `${topicLine}\n${body}${anchor.timeFooter ? `\n${anchor.timeFooter}` : ""}`; return { id: summaryMessageId(anchor.blockId), role: "system", diff --git a/kernel/src/render-refs.ts b/kernel/src/render-refs.ts index 6590d25843..64634111aa 100644 --- a/kernel/src/render-refs.ts +++ b/kernel/src/render-refs.ts @@ -1,6 +1,7 @@ import type { CoreMessage, CompressionState, MessageRefMap } from "./types.js"; import { refForRaw, BLOCKED_REF } from "./refs.js"; import { thinkingTokenValue } from "./tokenize.js"; +import { formatUtcMinute } from "./time-fmt.js"; import type { PipelineNode, PipelineContext, NodeIO } from "./pipeline.js"; /** @@ -42,7 +43,7 @@ const GT = "\x3e"; const TAG_OPEN = LT + "acp "; const TAG_CLOSE = LT + "/acp" + GT; -function acpTag(ref: string, tokens: number, type: string): string { +function acpTag(ref: string, tokens: number, type: string, at?: string): string { return ( TAG_OPEN + 'tokens="' + @@ -50,6 +51,7 @@ function acpTag(ref: string, tokens: number, type: string): string { '" type="' + type + '"' + + (at !== undefined ? ' at="' + at + '"' : "") + GT + ref + TAG_CLOSE @@ -63,6 +65,8 @@ function renderMessage( strategy: RenderStrategy, snapshot: Record | null = null, deferred: ReadonlySet | null = null, + timeSnapshot: Record | null = null, + timestamps = false, ): CoreMessage { const ref = refForRaw(map, message.id); if (!ref || ref === BLOCKED_REF) return message; @@ -102,7 +106,15 @@ function renderMessage( : countTokens(cleanText); const tokens = textTokens + thinkingTokenValue(message.thinkingTokens); const type = classifyType(message); - const prefix = acpTag(ref, tokens, type) + "\n"; + // #4313: arrival stamp, read-only — the freeze happened at ref mint + // (assign-refs node). A ref with no frozen time (pre-#4313 history) renders + // UNMARKED rather than guessing "now" (rejected option A for legacy + // history in the issue). + const at = + timestamps && timeSnapshot !== null && timeSnapshot[ref] !== undefined + ? formatUtcMinute(timeSnapshot[ref]!) + : undefined; + const prefix = acpTag(ref, tokens, type, at) + "\n"; if (!cleanText) return { ...message, text: prefix }; return { ...message, text: prefix + cleanText }; @@ -113,6 +125,7 @@ export function renderVisibleRefs( state: CompressionState, countTokens: (text: string) => number = (text) => Math.ceil(text.length / 4), strategy: RenderStrategy = "all", + timestamps = false, ): CoreMessage[] { // Legacy behavior: recompute tokens every render (snapshot = null). const map = state.messageRefs; @@ -120,7 +133,16 @@ export function renderVisibleRefs( ? new Set(state.renderDeferredRefs) : null; return messages.map((message) => - renderMessage(message, map, countTokens, strategy, null, deferred), + renderMessage( + message, + map, + countTokens, + strategy, + null, + deferred, + state.timeSnapshot ?? null, + timestamps, + ), ); } @@ -138,14 +160,27 @@ export function renderWithSnapshot( state: CompressionState, countTokens: (text: string) => number = (text) => Math.ceil(text.length / 4), strategy: RenderStrategy = "all", + timestamps = false, ): RenderWithSnapshotResult { const map = state.messageRefs; const snapshot = { ...(state.tokenSnapshot ?? {}) }; const deferred = state.renderDeferredRefs ? new Set(state.renderDeferredRefs) : null; + // #4313: read-only view of the frozen arrival times (stamped upstream by + // the assign-refs node in the same turn). + const timeSnapshot = state.timeSnapshot ?? null; const rendered = messages.map((message) => - renderMessage(message, map, countTokens, strategy, snapshot, deferred), + renderMessage( + message, + map, + countTokens, + strategy, + snapshot, + deferred, + timeSnapshot, + timestamps, + ), ); return { messages: rendered, tokenSnapshot: snapshot }; } @@ -160,6 +195,7 @@ export function createRenderRefsNode(strategy: RenderStrategy): PipelineNode { io.state, ctx.countTokens, strategy, + ctx.config.renderTimestamps === true, ); // Write the snapshot back only when it grew: steady-state (all hits) // must not churn the state object and force an adapter save every turn. diff --git a/kernel/src/sync.ts b/kernel/src/sync.ts index a3fbafed55..07e911107e 100644 --- a/kernel/src/sync.ts +++ b/kernel/src/sync.ts @@ -68,6 +68,13 @@ export function syncBlocks( }, // Snapshot is keyed by ref with primitive values — shallow copy suffices. tokenSnapshot: { ...(state.tokenSnapshot ?? {}) }, + // #4313: arrival times ride the same clone, ABSENCE-PRESERVING — a + // pre-#4313 state must clone to an identical digest. Retention differs + // from tokenSnapshot BELOW — footers read times of FOLDED messages, so + // the live-only prune would kill them at the fold boundary. + ...(state.timeSnapshot + ? { timeSnapshot: { ...state.timeSnapshot } } + : {}), nudge: { ...state.nudge, anchors: { ...state.nudge.anchors } }, stats: { ...state.stats }, absorbed: (state.absorbed ?? []).map((record) => ({ ...record })), @@ -126,6 +133,26 @@ export function syncBlocks( result.tokenSnapshot = pruned; } + // #4313: time retention is WIDER than the token prune — a folded message's + // time stays readable so summary footers (and later re-folds of ancestor + // ranges) keep real arrival times. Drop only entries whose ref is neither + // live nor claimed by any block's effective set (host-deleted/absorbed + // messages with no archive record). + if (result.timeSnapshot !== undefined && Object.keys(result.timeSnapshot).length > 0) { + const blockClaimedRefs = new Set(); + for (const block of result.blocks) { + for (const id of block.effectiveMessageIds) { + const ref = result.messageRefs.byRaw[id]; + if (typeof ref === "string") blockClaimedRefs.add(ref); + } + } + const prunedTimes: Record = {}; + for (const [ref, t] of Object.entries(result.timeSnapshot)) { + if (liveRefs.has(ref) || blockClaimedRefs.has(ref)) prunedTimes[ref] = t; + } + result.timeSnapshot = prunedTimes; + } + const consumedBlockIds = new Set(); for (const block of result.blocks) { for (const consumedId of block.directBlockIds) { diff --git a/kernel/src/time-fmt.ts b/kernel/src/time-fmt.ts new file mode 100644 index 0000000000..db93554b2a --- /dev/null +++ b/kernel/src/time-fmt.ts @@ -0,0 +1,12 @@ +/** #4313: UTC wall-clock rendering for ref tags and summary footers. + * Minute precision, ISO-like "YYYY-MM-DD HH:mm" — human-readable beats + * epoch seconds for the model (no arithmetic to misread) at negligible + * token cost. */ +export function formatUtcMinute(epochMs: number): string { + const d = new Date(epochMs); + const p = (n: number): string => String(n).padStart(2, "0"); + return ( + `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())} ` + + `${p(d.getUTCHours())}:${p(d.getUTCMinutes())}` + ); +} diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 3ac5c6a348..8b7bf92455 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -248,6 +248,14 @@ export interface CompressionState { * provider prefix cache. Keyed by ref (not raw id): refs survive restarts * and omp live-N raw-id replacement. */ tokenSnapshot: Record; + /** #4313: first-seen wall-clock (epoch ms) per message ref — the message's + * arrival time, frozen once at ref mint and read forever (same discipline + * as tokenSnapshot). Rendering (`at="..."` on ref tags, folded-range + * footers on summary carriers) is gated by Config.renderTimestamps; the + * freeze itself is unconditional so enabling the flag mid-session yields + * real arrival times instead of "now". Optional: pre-#4313 persisted + * states lack it. */ + timeSnapshot?: Record; nudge: NudgeState; stats: CompressionStats; /** Instant tool-result absorption records. Optional: pre-absorb persisted states lack it. */ @@ -486,6 +494,12 @@ export interface Config { * exactly the messages that carry no toolName. Must be pure and cheap: it * runs once per message per protection scan. */ messagePathOf?: (msg: CoreMessage) => string | undefined; + /** #4313: render arrival timestamps — `at="YYYY-MM-DD HH:mm"` (UTC, minute + * precision) appended inside ref tags, and a `[folded A → B UTC]` + * footer line on summary carriers. Default off: byte-stable with every + * pre-#4313 wire. One-time prefix-cache flush when toggled on + * mid-session. */ + renderTimestamps?: boolean; /** Tool-name patterns (glob suffix allowed) protected in their LATEST * instance only: the newest matching tool-call and its paired tool-result * are protected from compression; older instances remain compressible. For diff --git a/kernel/tests/issue4313-timestamps.test.ts b/kernel/tests/issue4313-timestamps.test.ts new file mode 100644 index 0000000000..d31ca11b76 --- /dev/null +++ b/kernel/tests/issue4313-timestamps.test.ts @@ -0,0 +1,150 @@ +// #4313: arrival timestamps on ref tags (`at="YYYY-MM-DD HH:mm"` UTC, +// minute precision) and folded-range footers (`[folded A → B UTC]`) on +// summary carriers. Off by default — every pre-#4313 wire byte-stable; +// history without a frozen time renders unmarked (no guessed "now"). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createCore } from "../src/compress.js"; +import { createInitialState } from "../src/state.js"; +import { assignRefs } from "../src/refs.js"; +import { renderWithSnapshot } from "../src/render-refs.js"; +import { defaultConfig } from "../src/config.js"; +import { formatUtcMinute } from "../src/time-fmt.js"; +import { syncBlocks } from "../src/sync.js"; +import type { CompressionState, CoreMessage } from "../src/types.js"; + +function msg(id: string, text: string): CoreMessage { + return { id, role: "user", contentType: "text", text }; +} + +function stateWithRefs(messages: CoreMessage[]): CompressionState { + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { + existing: state.messageRefs, + nextIndex: 1, + }).map; + return state; +} + +const AT_ATTR = / at="\d{4}-\d{2}-\d{2} \d{2}:\d{2}"/; + +test("formatUtcMinute: exact zero-padded UTC minute string", () => { + assert.equal(formatUtcMinute(Date.UTC(2026, 9, 22, 6, 5)), "2026-10-22 06:05"); + assert.equal(formatUtcMinute(Date.UTC(2026, 0, 1, 0, 0)), "2026-01-01 00:00"); +}); + +test("#4313 default off: rendered tags carry NO at-attribute (byte-stable)", () => { + const messages = [msg("a", "hello"), msg("b", "world")]; + const state = stateWithRefs(messages); + state.timeSnapshot = { m00001: Date.now(), m00002: Date.now() }; + const out = renderWithSnapshot(messages, state, (t) => t.length, "all"); + for (const m of out.messages) { + assert.doesNotMatch(m.text ?? "", AT_ATTR, "no at-attribute when flag off"); + } +}); + +test("#4313 flag on: at-attribute renders from the frozen time, stable across renders", () => { + const messages = [msg("a", "hello"), msg("b", "world")]; + const state = stateWithRefs(messages); + const t0 = Date.UTC(2026, 9, 22, 6, 5); + state.timeSnapshot = { m00001: t0, m00002: t0 + 60_000 }; + const r1 = renderWithSnapshot(messages, state, (t) => t.length, "all", true); + assert.match(r1.messages[0]!.text!, /\x3cacp tokens="\d+" type="text" at="2026-10-22 06:05"\x3em00001\x3c\/acp\x3e\nhello/); + assert.match(r1.messages[1]!.text!, / at="2026-10-22 06:06"/); + // Re-render after wall-clock moved: same frozen stamps (prefix-cache safe). + const r2 = renderWithSnapshot(messages, state, (t) => t.length, "all", true); + assert.equal(r2.messages[0]!.text, r1.messages[0]!.text); +}); + +test("#4313 unmarked history: no frozen time → no at-attribute even when flag on", () => { + const messages = [msg("legacy", "old message from before #4313")]; + const state = stateWithRefs(messages); + delete state.timeSnapshot; // pre-#4313 persisted state + const out = renderWithSnapshot(messages, state, (t) => t.length, "all", true); + assert.doesNotMatch(out.messages[0]!.text ?? "", AT_ATTR, "legacy history renders unmarked"); +}); + +test("#4313 processTurn freezes first-seen times; sync keeps folded-message times", () => { + const core = createCore(); + const state = createInitialState(); + const messages = [msg("a", "hello there"), msg("b", "second message")]; + const r = core.processTurn({ messages, state, config: defaultConfig(200000) }); + assert.equal(r.state.timeSnapshot?.m00001, r.state.timeSnapshot?.m0002 ?? r.state.timeSnapshot?.m00002); + assert.ok(typeof r.state.timeSnapshot?.m00001 === "number", "first-seen time frozen at ref mint"); + assert.ok(typeof r.state.timeSnapshot?.m00002 === "number"); + + // Fold both messages into a block, then sync a view WITHOUT them: their + // times must survive (summary footers read folded times), while refs of + // messages gone without any block record are dropped. + const folded = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: "A long enough summary body to satisfy the minimum summary length gate of fifty characters." }], + messages, + state: r.state, + config: defaultConfig(200000), + }); + const synced = syncBlocks([], folded.state); + assert.equal(synced.timeSnapshot?.m00001, folded.state.timeSnapshot?.m00001, "block-claimed time survives the live-ref prune"); + assert.equal(synced.timeSnapshot?.m00002, folded.state.timeSnapshot?.m00002); +}); + +test("#4313 summary carrier footer: fold range renders [folded A → B UTC] when on, nothing when off", () => { + const core = createCore(); + const state = createInitialState(); + // Bodies must clear compress.minCompressRange (5000 chars default) or the + // fold is refused as below-threshold noise. + const big = (seed: string) => `${seed} `.repeat(1200); + const messages = [ + msg("a", big("alpha arrival content")), + msg("b", big("beta arrival content")), + msg("c", "tail stays visible"), + ]; + const turn1 = core.processTurn({ messages, state, config: defaultConfig(200000) }); + const t0 = turn1.state.timeSnapshot!.m00001!; + const t2 = turn1.state.timeSnapshot!.m00002!; + + const cfgOn = defaultConfig(200000, { preserveRecentMessages: 1, preserveRecentTokens: 0 }); + cfgOn.renderTimestamps = true; + const on = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: "A long enough summary body to satisfy the minimum summary length gate of fifty characters." }], + messages, + state: turn1.state, + config: cfgOn, + }); + // Full-history view (the storage-wire shape): folded ids re-enter the + // input and prune replaces them with the carrier at the anchor position. + const prunedOn = core.processTurn({ + messages, + state: on.state, + config: cfgOn, + }); + const carrierOn = prunedOn.messages.find((m) => (m.text ?? "").startsWith("[Compressed conversation section]")); + assert.ok(carrierOn, `summary carrier rendered: ${JSON.stringify(prunedOn.messages.map((m) => m.text?.slice(0, 40)))}`); + // a and b were minted in the SAME turn, so their frozen times usually + // coincide → the single-point form renders. Accept either form (a + // millisecond-straddled minute boundary yields the range form). + assert.match( + carrierOn!.text!, + new RegExp( + `\\n\\[folded ${formatUtcMinute(t0)}( → ${formatUtcMinute(t2)})? UTC\\]$`, + ), + "footer gives the folded span's arrival-time range", + ); + + // Same fold with the flag off: carrier has no footer. + const turnOff = core.processTurn({ messages, state: createInitialState(), config: defaultConfig(200000) }); + const cfgOff = defaultConfig(200000, { preserveRecentMessages: 1, preserveRecentTokens: 0 }); + const off = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: "A long enough summary body to satisfy the minimum summary length gate of fifty characters." }], + messages, + state: turnOff.state, + config: cfgOff, + }); + const prunedOff = core.processTurn({ + messages, + state: off.state, + config: cfgOff, + }); + const carrierOff = prunedOff.messages.find((m) => (m.text ?? "").startsWith("[Compressed conversation section]")); + assert.ok(carrierOff); + assert.doesNotMatch(carrierOff!.text!, /\[folded /, "no footer when flag off"); +}); diff --git a/package-lock.json b/package-lock.json index eced96ec98..bfc642e9f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.170", + "version": "0.0.171", "dev": true, "license": "MIT", "devDependencies": { diff --git a/src/compress-settings.ts b/src/compress-settings.ts index 34e53ca3ed..2ee9a7f59d 100644 --- a/src/compress-settings.ts +++ b/src/compress-settings.ts @@ -336,6 +336,9 @@ export function applyCompressSettings(base: Config, limit: number, s: CompressSe tiers, preserveRecentMessages: s.preserveRecentMessages ?? base.preserveRecentMessages, preserveRecentTokens: s.preserveRecentTokens ?? base.preserveRecentTokens, + // #4313: absent at every level leaves the kernel default (off) — + // byte-stable wire for pre-#4313 sessions. + renderTimestamps: s.timestamps ?? (base as ResolvedKernelConfig).renderTimestamps, compress: { ...base.compress, minCompressRange: s.minCompressRangeChars ?? s.minCompressRange ?? base.compress.minCompressRange, diff --git a/src/config.ts b/src/config.ts index 08b1fbd435..7d641f5fc5 100644 --- a/src/config.ts +++ b/src/config.ts @@ -286,6 +286,14 @@ export type CompressSettings = { /** #2228: output budget (tokens) of the decision side call. Default 200 * (same ceiling class as SIDE_REQUEST_MAX_TOKENS). Must be > 0. */ nudgeDecisionMaxTokens?: number; + /** #4313: render arrival timestamps — `at="YYYY-MM-DD HH:mm"` (UTC, + * minute precision) inside ref tags, and a `[folded A → B UTC]` + * footer on summary carriers giving the arrival-time range of the + * folded span. Off by default: enabling rewrites every rendered tag + * once (a one-time provider prefix-cache flush). History that predates + * the setting renders unmarked (no guessed times). Maps to kernel + * `renderTimestamps` (acp-kernel >= 0.0.171). */ + timestamps?: boolean; /** Trailing messages never offered for compression * (kernel `preserveRecentMessages`). */ preserveRecentMessages?: number; diff --git a/src/persist.ts b/src/persist.ts index 5aa2e6f80f..ef76a0b7f2 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -1751,6 +1751,25 @@ export class SessionStore { this.log("info", `[persist] remapped ${moves.length} token-snapshot entries onto ledger-aligned refs for ${session.id} (#4599)`); } } + // #4313: arrival times are keyed by ref too — without the same + // remap, alignment would re-point tags at the WRONG message's + // time (same corruption class the token remap prevents). + const timeSnap = (state as { timeSnapshot?: Record }).timeSnapshot; + if (timeSnap && outcome.superseded.size > 0) { + const byRawNow = state.messageRefs.byRaw; + const timeMoves: Array<[oldRef: string, newRef: string, t: number]> = []; + for (const [oldRef, rawId] of outcome.superseded) { + const t = timeSnap[oldRef]; + const newRef = byRawNow[rawId]; + if (t === undefined || newRef === undefined || newRef === oldRef) continue; + timeMoves.push([oldRef, newRef, t]); + } + if (timeMoves.length > 0) { + for (const [oldRef] of timeMoves) delete timeSnap[oldRef]; + for (const [, newRef, t] of timeMoves) timeSnap[newRef] = t; + this.log("info", `[persist] remapped ${timeMoves.length} time-snapshot entries onto ledger-aligned refs for ${session.id} (#4313/#4599)`); + } + } state.refLedgerAligned = true; this.log("info", `[persist] ledger-aligned refs for ${session.id}: kept=${outcome.kept} restamped=${outcome.restamped} rehomed=${outcome.rehomed} blocked=${outcome.blocked} superseded=${outcome.superseded.size} (#4316 PR3/3)`); this.scheduleSave(session); diff --git a/src/plugin.ts b/src/plugin.ts index 2feb2e5c31..28d2921f50 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1564,6 +1564,9 @@ export async function handlePluginFork(payload: string, res: ServerResponse): Pr if (ref !== null) { child.state.messageRefs.byRef[ref] = rawId; if (parent.state.tokenSnapshot[ref] !== undefined) child.state.tokenSnapshot[ref] = parent.state.tokenSnapshot[ref]; + if (parent.state.timeSnapshot?.[ref] !== undefined) { + (child.state.timeSnapshot ??= {})[ref] = parent.state.timeSnapshot[ref]!; + } } } child.state.nextBlockId = parent.state.nextBlockId; diff --git a/src/state-hydration.ts b/src/state-hydration.ts index ab412c07ad..dbf219567a 100644 --- a/src/state-hydration.ts +++ b/src/state-hydration.ts @@ -33,6 +33,12 @@ export function mergeState(parsed: CompressionState): CompressionState { nextBlockId: parsed.nextBlockId ?? fresh.nextBlockId, nextRunId: parsed.nextRunId ?? fresh.nextRunId, tokenSnapshot: parsed.tokenSnapshot ?? fresh.tokenSnapshot, + // #4313: frozen arrival times per ref — restart must not lose them + // (tags and summary footers re-render from this map). ABSENCE- + // PRESERVING: legacy states must load to their pinned digests. + ...(parsed.timeSnapshot !== undefined + ? { timeSnapshot: parsed.timeSnapshot } + : {}), lastPassIds: parsed.lastPassIds ?? fresh.lastPassIds, hiddenOrphanRefs: parsed.hiddenOrphanRefs ?? fresh.hiddenOrphanRefs, // #2362: without this a restart forgets which refs are dead and the @@ -73,5 +79,10 @@ export function mergeState(parsed: CompressionState): CompressionState { * (#4192). Consumers: kstate_json serialization order (storage/ingest.ts), * unified view rebuild, digest key order. */ -export const COMPRESSION_STATE_FIELDS: readonly (keyof CompressionState)[] = - Object.keys(mergeState(createInitialState())) as (keyof CompressionState)[]; +export const COMPRESSION_STATE_FIELDS: readonly (keyof CompressionState)[] = [ + ...Object.keys(mergeState(createInitialState())) as (keyof CompressionState)[], + // #4313: optional — absent from a fresh state until the first ref mint + // freezes a time, so it never appears in the keys() scan above; enumerated + // explicitly so kstate_json round-trips it through the unified store. + "timeSnapshot", +]; diff --git a/src/web/client.ts b/src/web/client.ts index 05d396617a..8ec69b4ac7 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -3858,6 +3858,7 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + updateNudgeNote(); refreshTierInputs(); prm.value = String(cp && typeof cp.preserveRecentMessages === "number" ? cp.preserveRecentMessages : PRM_KERNEL_DEFAULT); + tsRow.inp.checked = cp?.timestamps === true; ptInp.value = (cp && Array.isArray(cp.protectedTools)) ? cp.protectedTools.join(", ") : ""; const nv = (cp && Array.isArray(cp.neverPreserveRecentTools)) ? cp.neverPreserveRecentTools : null; neInp.value = nv ? nv.filter((x) => typeof x === "string").join(", ") : ""; @@ -3966,6 +3967,25 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + abHint.className = "dim small"; abHint.textContent = t("cfg.q_absorb_hint"); abRow.ctl.appendChild(abHint); + // #4313: compress.timestamps — arrival times on tags and + // [folded A → B UTC] footers on summary carriers. + const tsRow = row("quick-timestamps", t("cfg.q_timestamps")); + qCtrls.push(tsRow.inp); + tsRow.inp.addEventListener("change", () => commit((d) => { + const c = compressOf(d); + if (tsRow.inp.checked) { + if (!c) d.compress = {}; + const c2 = compressOf(d); + if (c2) c2.timestamps = true; + } else if (c) { + delete c.timestamps; + if (Object.keys(c).length === 0) delete d.compress; + } + })); + const tsHint = document.createElement("span"); + tsHint.className = "dim small"; + tsHint.textContent = t("cfg.q_timestamps_hint"); + tsRow.ctl.appendChild(tsHint); const packSel = document.createElement("select"); packSel.className = "field-input mono"; qCtrls.push(packSel); diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 49c3cc65ac..c4f34d29d9 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -560,6 +560,8 @@ export const MESSAGES: Record> = { "cfg.q_dsh_ctxtab_label": "DSH「上下文」标签页名称(dsh.contextTabLabel)——留空用内置名「上下文」,可改名避免与其他插件重名", "cfg.q_absorb": "工具结果即时蒸馏(absorb)——大工具结果到达时由模型即时蒸馏,原文隐藏到下一轮折叠前(默认关)", "cfg.q_absorb_hint": "默认只吸含图结果(#3422);mediaOnly: false 可恢复吸全文。子项(minToolTokens、contextThresholdPct、excludeTools)请在下方 JSON 编辑框写", + "cfg.q_timestamps": "消息时间戳(compress.timestamps)——每条消息的 标签带到达时间 at=\"YYYY-MM-DD HH:mm\"(UTC 分钟),折叠摘要末尾带覆盖区间的起止时间(#4313)", + "cfg.q_timestamps_hint": "默认关。开启会一次性改写所有已渲染标签(一次性前缀缓存冲刷);开启之前的历史消息不打标(不猜时间)", "cfg.q_pack": "压缩提示词包(compress.promptPack)", "cfg.q_nudge": "压缩增长阈值 tokens(compress.nudgeGrowthTokens)", "cfg.q_nudge_step": "步进 5000", @@ -1228,6 +1230,8 @@ export const MESSAGES: Record> = { "cfg.q_dsh_ctxtab_label": "Label of the DSH Context tab (dsh.contextTabLabel) — empty keeps the built-in name \"Context\"; rename to avoid clashing with another plugin's tab", "cfg.q_absorb": "Instant tool-result absorption (absorb) — large tool results are distilled by the model on arrival; originals hidden until the next fold round (default off)", "cfg.q_absorb_hint": "by default only image-bearing results are absorbed (#3422); set mediaOnly: false to absorb full text. Sub-fields (minToolTokens, contextThresholdPct, excludeTools) go in the JSON editor below", + "cfg.q_timestamps": "Message timestamps (compress.timestamps) — every rendered ref tag carries the message's arrival time at=\"YYYY-MM-DD HH:mm\" (UTC, minute precision), and each folded summary ends with the covered span's time range (#4313)", + "cfg.q_timestamps_hint": "Off by default. Turning it on rewrites every already-rendered tag once (a one-time provider prefix-cache flush); history that predates the setting renders unmarked (no guessed times)", "cfg.q_pack": "Compression prompt pack (compress.promptPack)", "cfg.q_nudge": "Compress growth threshold tokens (compress.nudgeGrowthTokens)", "cfg.q_nudge_step": "step of 5000", diff --git a/tests/compress-settings.test.ts b/tests/compress-settings.test.ts index 4940464dc0..14f4b36977 100644 --- a/tests/compress-settings.test.ts +++ b/tests/compress-settings.test.ts @@ -36,6 +36,17 @@ test("mergeCompress: all undefined yields all-undefined settings", () => { assert.equal(hasCompressSettings(merged), false); }); +test("#4313: CompressSettings.timestamps maps to kernel renderTimestamps, unset inherits/off", () => { + const base = defaultConfig(200000); + assert.equal(base.renderTimestamps, undefined, "kernel default stays off (byte-stable wire)"); + const on = applyCompressSettings(base, 200000, { timestamps: true }); + assert.equal(on.renderTimestamps, true); + const off = applyCompressSettings(on, 200000, {}); + assert.equal(off.renderTimestamps, true, "unset at deeper level inherits the base value"); + const fromFile = applyCompressSettings(base, 200000, { timestamps: false }); + assert.equal(fromFile.renderTimestamps, false, "explicit false disables"); +}); + test("hasCompressSettings: true when any field set", () => { assert.equal(hasCompressSettings({}), false); assert.equal(hasCompressSettings({ nudgeGrowthTokens: 50000 }), true); diff --git a/tests/golden/storage-render/anthropic.json b/tests/golden/storage-render/anthropic.json index b6ebe6f156..b0c3d09689 100644 --- a/tests/golden/storage-render/anthropic.json +++ b/tests/golden/storage-render/anthropic.json @@ -95,10 +95,10 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "81ee1ad6ff722210226a6f3969162e6715dedf607f3c1bc9b9c9293d9539ca38", - "stateDigestAligned": "833d3548ede983e7c0c49c685f97c8f62b28fca779a27b211cedd13731fb5c58", + "stateDigest": "c659e4774e97f64d6c3d90f7856e725faa4eeca2e1517ee30456ada7080d1ab1", + "stateDigestAligned": "d79b4527bbfefdc60129ba3c4fbab55402c8b24ddbc655ae98886f47f3450ade", "sectionDigests": { - "state": "7f38eb530c6731be", + "state": "172707d4503a8ee3", "blockContents": "dc7d13d250c94bb4", "stats": "17f1325cb58358bb", "metadata": "a4ab27ced8ed8346" @@ -111,6 +111,7 @@ "nextBlockId": "d4735e3a265e16ee", "nextRunId": "d4735e3a265e16ee", "tokenSnapshot": "7c8dbc981fdfcbd6", + "timeSnapshot": "0680967e9150a178", "lastPassIds": "f13452893a1b4980", "hiddenOrphanRefs": "4f53cda18c2baa0c", "deadRefs": "74234e98afe7498f", diff --git a/tests/golden/storage-render/chat.json b/tests/golden/storage-render/chat.json index 0a9dc0c169..3375e52da5 100644 --- a/tests/golden/storage-render/chat.json +++ b/tests/golden/storage-render/chat.json @@ -95,10 +95,10 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "63744b46ebb010d6ee194aa60caff8afd03c4c03849d2b45d3a9356193a159be", - "stateDigestAligned": "24ec5c3955e73f9ebecd194aaa428f1af4c1db7c58d6a9e93cf86f42e4c3ce8a", + "stateDigest": "8a668c027464e3b788ecbda5a20c21c2afd4263c816f3a3233bab1ebc0db3b79", + "stateDigestAligned": "cc10e1e17ef4d210aed2e5767c54e561ab6468a410c1524b199de7d1f1a4dcc3", "sectionDigests": { - "state": "8d09f6115ebffb9d", + "state": "c00eeb9be8680a76", "blockContents": "94a58f96d7c5cfc3", "stats": "95712051bd1e8b03", "metadata": "0cbd1fda3a07b9af" @@ -111,6 +111,7 @@ "nextBlockId": "d4735e3a265e16ee", "nextRunId": "d4735e3a265e16ee", "tokenSnapshot": "5080181ee1a25a8c", + "timeSnapshot": "04e9e9f390ed0223", "lastPassIds": "d18ace2914339891", "hiddenOrphanRefs": "4f53cda18c2baa0c", "deadRefs": "74234e98afe7498f", diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index 1d51cd4e0d..6a165785ab 100644 --- a/tests/golden/storage-render/google.json +++ b/tests/golden/storage-render/google.json @@ -95,10 +95,10 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "7795ffa5f895adbaeebff6eb78817b4612cf3fec5652dee92c4872a91a0ec961", - "stateDigestAligned": "aebc5d16e500e193c08652c54214ac50f8acfc6ba89d24e33371a7eb2a06d2a9", + "stateDigest": "b350e0e3059b9d8b24f255235ecfea626d93c1aa997b932bacda0cd6ce0ac870", + "stateDigestAligned": "3151eb2b0ad2e5aaf08f7adcf4da271906d07fdaf41c1d74807609684f26fc6b", "sectionDigests": { - "state": "3b0f64f8e2b16e36", + "state": "cf7b5151b1578e8d", "blockContents": "473264d9df8ba338", "stats": "b215001eb0f2a5ff", "metadata": "829b443829784726" @@ -111,6 +111,7 @@ "nextBlockId": "d4735e3a265e16ee", "nextRunId": "d4735e3a265e16ee", "tokenSnapshot": "5080181ee1a25a8c", + "timeSnapshot": "04e9e9f390ed0223", "lastPassIds": "1e3edaf045fbb7d1", "hiddenOrphanRefs": "4f53cda18c2baa0c", "deadRefs": "74234e98afe7498f", diff --git a/tests/golden/storage-render/responses.json b/tests/golden/storage-render/responses.json index 04831f8bfa..8fbd62ee69 100644 --- a/tests/golden/storage-render/responses.json +++ b/tests/golden/storage-render/responses.json @@ -95,10 +95,10 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "5b613a8c8a9c1cc47597779fc398bfe9ed99b524c2bd6a8e7e7188cc3c0a9798", - "stateDigestAligned": "4b725248d57d935b4a8fe03ed114684bf9421acfa8f7431dd286e3909a138086", + "stateDigest": "f14cb2f3bb7d8ba765b600ebf8500a079f228f825b1cf5a56f709f9d5493610c", + "stateDigestAligned": "c2a71d3486c1483f5416a09f15e3a8ab663805b7ac78fb52fd06c09c015c5c35", "sectionDigests": { - "state": "543d4459ecf0fe8f", + "state": "ca64e17ba5b45ccb", "blockContents": "b6701268a0bdcd8a", "stats": "0c75fc5429aa3048", "metadata": "afea52381c5db9fc" @@ -111,6 +111,7 @@ "nextBlockId": "d4735e3a265e16ee", "nextRunId": "d4735e3a265e16ee", "tokenSnapshot": "003006fbddac1a2b", + "timeSnapshot": "6d5a706be9c49da2", "lastPassIds": "de5c5da67428b09f", "hiddenOrphanRefs": "4f53cda18c2baa0c", "deadRefs": "74234e98afe7498f", diff --git a/tests/storage-state-fields.test.ts b/tests/storage-state-fields.test.ts index 19f3dd5850..0d46a46a75 100644 --- a/tests/storage-state-fields.test.ts +++ b/tests/storage-state-fields.test.ts @@ -65,6 +65,15 @@ test("mechanism: every field of a fresh state is covered by the derived list (no `createInitialState emits "${key}" but COMPRESSION_STATE_FIELDS lacks it — add it to mergeState's literal (src/state-hydration.ts)`, ); } - // And the list is exactly the merge output — nothing stale either. - assert.deepEqual([...COMPRESSION_STATE_FIELDS], Object.keys(mergeState(createInitialState()))); + // And the list is exactly the merge output plus the documented optional + // appendix — nothing stale either. #4313: fields that are legitimately + // ABSENT from a fresh state until first use (timeSnapshot: frozen at the + // first ref mint) can never appear in the keys() scan, so they ride an + // explicit appendix instead — kstate_json round-trips them generically. + const optionalAppendix = ["timeSnapshot"] as const; + const mergeKeys = Object.keys(mergeState(createInitialState())); + assert.deepEqual( + [...COMPRESSION_STATE_FIELDS], + [...mergeKeys, ...optionalAppendix.filter((k) => !mergeKeys.includes(k))], + ); }); diff --git a/verif/exceptions.ts b/verif/exceptions.ts index 34c13ed91e..fd7e46ebab 100644 --- a/verif/exceptions.ts +++ b/verif/exceptions.ts @@ -49,6 +49,14 @@ export const EXCEPTIONS: readonly SubsetException[] = [ reason: "createdAt: Date.now() — wall-clock stamp on new blocks; orthogonal to every verified invariant, modeled as an unconstrained symbolic integer.", }, + { + file: "kernel/src/compress.ts", + code: "ENV_ACCESS", + fn: "run", + detail: "Date.now", + reason: + "#4313 assign-refs node: time[ref] = Date.now() — first-seen wall-clock freeze per minted ref, same class as the block createdAt stamp above; orthogonal to every verified invariant, modeled as an unconstrained symbolic integer.", + }, { file: "kernel/src/compress.ts", code: "ENV_ACCESS", diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index 532cd5a055..f4be6e51e2 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -102,6 +102,16 @@ entries: desc_zh: "强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。" site_en: "Force streaming (SSE) summarization from the first attempt — stream-mandating upstreams now self-heal via a one-shot SSE probe on any non-streaming 400 (#2494); kept as the escape hatch for gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the self-learn cannot detect, or to skip the one probe round-trip." site_zh: "强制摘要从首次起走流式(SSE)——要求流式的上游现在通过任何非流式 400 上的一次性 SSE 探测自愈(#2494);保留作为会掐断长非流式调用的网关(如 Cloudflare 524)的逃生通道(自学习无法感知该场景),也可用于省去一次探测往返。" + - key: compress.timestamps + type: boolean + default: "false (unset)" + group: compress + id: cw.ts4313 + render: compress-row + desc_en: "Render arrival timestamps (#4313): every rendered ref tag carries at=\"YYYY-MM-DD HH:mm\" (UTC, minute precision) and each folded summary ends with the covered span's [folded A → B UTC] range, so a days-old plan stops competing with a minutes-old instruction on equal footing. History that predates the setting renders unmarked (times are frozen at first sight, never guessed). Enabling rewrites every already-rendered tag once — a one-time provider prefix-cache flush." + desc_zh: "渲染消息到达时间(#4313):每个已渲染的 ref 标签带 at=\"YYYY-MM-DD HH:mm\"(UTC、分钟精度),每条折叠摘要末尾带覆盖区间的 [folded A → B UTC] 时间范围,让几天前的旧方案不再与几分钟前的新指令“看起来同时发生”。早于本设置开启的历史不打标(时间在首次看到时冻结,从不倒填猜测)。开启会把已渲染标签一次性重写——即一次性 provider 前缀缓存冲刷。" + site_en: "Show when each message arrived and when a folded span covers (#4313) — ref tags carry at=\"YYYY-MM-DD HH:mm\" UTC and summary footers carry the covered range; pre-existing history renders unmarked." + site_zh: "显示每条消息何时到达、每个折叠块覆盖哪段时间(#4313)——ref 标签带 at=\"YYYY-MM-DD HH:mm\" UTC,摘要页脚带覆盖范围;开启前的历史不打标。" - key: compress.preserveRecentMessages type: number default: "3" diff --git a/website/docs/index.html b/website/docs/index.html index d4e06633e6..0f5308a545 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -189,6 +189,7 @@

compress — every knob

nudgeModelDecidedbooleanModel-decided nudge timing (off by default): an armed tier-1 nudge first asks the model, over the session's cached prefix, whether compressing now helps the current task; a strict-JSON yes injects a directive with a program-finalized span, anything else injects nothing this round. nudgeDecisionMaxTokensnumberOutput budget (tokens) of the model-decision side call (default 200). Must be > 0. streamSummarybooleanForce streaming (SSE) summarization from the first attempt — stream-mandating upstreams now self-heal via a one-shot SSE probe on any non-streaming 400 (#2494); kept as the escape hatch for gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the self-learn cannot detect, or to skip the one probe round-trip. + timestampsbooleanShow when each message arrived and when a folded span covers (#4313) — ref tags carry at="YYYY-MM-DD HH:mm" UTC and summary footers carry the covered range; pre-existing history renders unmarked. preserveRecentMessagesnumberKernel default 3 (tuned 5 → 3, #3058): the most recent messages stay soft-protected from folds. preserveRecentTokensnumberKernel default ≈5000: the most recent tokens stay soft-protected from folds. minCompressRangeCharsnumber (deprecated alias: minCompressRange)Smallest foldable range, in characters (kernel default ≈5000) — shorter ranges never fold. diff --git a/website/main.js b/website/main.js index 68e502e338..efdd365f76 100644 --- a/website/main.js +++ b/website/main.js @@ -71,6 +71,7 @@ "cw.nmd": "Model-decided nudge timing (off by default): an armed tier-1 nudge first asks the model, over the session's cached prefix, whether compressing now helps the current task; a strict-JSON yes injects a directive with a program-finalized span, anything else injects nothing this round.", "cw.ndmt": "Output budget (tokens) of the model-decision side call (default 200). Must be > 0.", "cw.ssm": "Force streaming (SSE) summarization from the first attempt — stream-mandating upstreams now self-heal via a one-shot SSE probe on any non-streaming 400 (#2494); kept as the escape hatch for gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the self-learn cannot detect, or to skip the one probe round-trip.", + "cw.ts4313": "Show when each message arrived and when a folded span covers (#4313) — ref tags carry at=\"YYYY-MM-DD HH:mm\" UTC and summary footers carry the covered range; pre-existing history renders unmarked.", "cw.prm": "Kernel default 3 (tuned 5 → 3, #3058): the most recent messages stay soft-protected from folds.", "cw.prt": "Kernel default ≈5000: the most recent tokens stay soft-protected from folds.", "cw.mrc": "Smallest foldable range, in characters (kernel default ≈5000) — shorter ranges never fold.", @@ -318,6 +319,7 @@ "cw.nmd": "模型自决的压缩时机(默认关闭):tier-1 提醒触发时,先通过会话缓存前缀上的短 side call 问模型现在压缩是否划算;严格 JSON 的 yes 注入带程序最终确定范围的指令,其余情况本轮不注入。", "cw.ndmt": "模型决策 side call 的输出预算(token,默认 200)。必须 > 0。", "cw.ssm": "强制摘要从首次起走流式(SSE)——要求流式的上游现在通过任何非流式 400 上的一次性 SSE 探测自愈(#2494);保留作为会掐断长非流式调用的网关(如 Cloudflare 524)的逃生通道(自学习无法感知该场景),也可用于省去一次探测往返。", + "cw.ts4313": "显示每条消息何时到达、每个折叠块覆盖哪段时间(#4313)——ref 标签带 at=\"YYYY-MM-DD HH:mm\" UTC,摘要页脚带覆盖范围;开启前的历史不打标。", "cw.prm": "内核默认 3(5 → 3,#3058):最近消息软保护、免于折叠。", "cw.prt": "内核默认约 5000:最近的 token 软保护、免于折叠。", "cw.mrc": "可折叠片段的最小字符数(内核默认约 5000),更短的永不折叠。",