You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/08/31 10:21:01 UTC

(maka) 01/01: refactor(runtime): budget and compact effective model history

This is an automated email from the ASF dual-hosted git repository.

Astro-Han pushed a commit to branch refactor/4283-effective-history-reducer
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 6c1d81f32f39efb370809ba1058440095e2b7b14
Author: AstroHan <le...@outlook.com>
AuthorDate: Mon Aug 31 18:20:44 2026 +0800

    refactor(runtime): budget and compact effective model history
    
    Context budgeting, summarization, provider-native compaction, and history
    compact checkpoint source digests each re-derived their own view of a Tool
    Result. All four read the raw `function_response.result` — the execution
    fact — rather than the durable model projection that #4287 commits atomically
    at T2 and that live continuation, next-Turn replay, and restart already
    replay. A bounded or redacted projection was therefore sized, summarized, and
    hashed at the size and content of the raw evidence it replaced.
    
    Move the sizing authority to the reducer: `estimateRuntimeEventChars`,
    `estimateRuntimeEventsTokens`, and `groupEventsByTurn` leave the
    dependency-free scalar helpers and live in `model-history.ts`, where a
    `function_response` is measured through `effectiveToolResultModelValue` —
    one decode of the effective projection shared by sizing and digests. The
    summary size floor rides the same estimator, so it is fixed by construction.
    
    Route the two compaction materializers through the same effective output as
    primary replay: `effectiveReplayToolResultOutput` prefers the durable
    projection and falls back to raw output only for a response that has none
    (legacy or provider-native). This removes the divergent `toolResultOutput`
    call in the LLM summarizer and the Codex compactor.
    
    Derive the checkpoint source digest from effective model history. Rewriting
    raw evidence under an unchanged projection no longer invalidates a valid
    checkpoint, while replacing the projection does — a checkpoint can never
    replay over content it did not cover. That is a source-policy change, so
    `HISTORY_COMPACT_SOURCE_POLICY_VERSION` becomes v2 and a v1 checkpoint fails
    the existing shape check and re-summarizes instead of claiming coverage this
    policy never computed. `HistoryCompactCheckpoint` stays a contiguous-prefix
    replacement; no sparse override is introduced.
    
    Covered by `effective-history-compaction.test.ts` (budget sizes the
    projection, summarization cannot read replaced raw output, the digest ignores
    raw evidence but tracks the projection, a v1-policy checkpoint no longer
    validates) and the runtime workspace suite.
    
    Part of #4283 (PR 2).
    
    Generated-by: Claude Code
---
 .../runtime/src/__tests__/context-budget.test.ts   |   2 +-
 .../__tests__/effective-history-compaction.test.ts | 195 +++++++++++++++++++++
 packages/runtime/src/context-budget-helpers.ts     |  61 +------
 packages/runtime/src/context-budget.ts             |  10 +-
 .../runtime/src/durable-tool-result-projection.ts  |  37 ++++
 packages/runtime/src/history-compact-checkpoint.ts |  28 ++-
 packages/runtime/src/history-compact-summarizer.ts |   4 +-
 .../src/history-compact-summary-validation.ts      |   3 +-
 packages/runtime/src/history-compaction.ts         |   7 +-
 packages/runtime/src/model-history.ts              | 110 +++++++++++-
 .../runtime/src/openai-codex-history-compactor.ts  |   4 +-
 packages/runtime/src/session-recap.ts              |   3 +-
 12 files changed, 385 insertions(+), 79 deletions(-)

diff --git a/packages/runtime/src/__tests__/context-budget.test.ts b/packages/runtime/src/__tests__/context-budget.test.ts
index c360aea827..25389b61dc 100644
--- a/packages/runtime/src/__tests__/context-budget.test.ts
+++ b/packages/runtime/src/__tests__/context-budget.test.ts
@@ -22,7 +22,7 @@ import { createHash } from 'node:crypto';
 import { test } from 'node:test';
 import type { RuntimeEvent } from '@maka/core/runtime-event';
 import { applyRuntimeEventContextBudget } from '../context-budget.js';
-import { estimateRuntimeEventsTokens } from '../context-budget-helpers.js';
+import { estimateRuntimeEventsTokens } from '../model-history.js';
 import { buildHistoryCompactCheckpoint } from '../history-compact-checkpoint.js';
 
 test('estimates only model-visible provider context', () => {
diff --git a/packages/runtime/src/__tests__/effective-history-compaction.test.ts b/packages/runtime/src/__tests__/effective-history-compaction.test.ts
new file mode 100644
index 0000000000..3c09d826d1
--- /dev/null
+++ b/packages/runtime/src/__tests__/effective-history-compaction.test.ts
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Budgeting, summarization, and checkpoint source digests must all read the
+ * EFFECTIVE model history — the durable Tool Result projection committed at T2
+ * — and never the raw execution fact it replaced (apache/maka#4283, PR 2).
+ */
+
+import assert from 'node:assert/strict';
+import { describe, test } from 'node:test';
+import type { RuntimeEvent } from '@maka/core/runtime-event';
+import type { DurableToolResultProjection } from '@maka/core/durable-tool-result-projection';
+import { estimateRuntimeEventsTokens } from '../model-history.js';
+import {
+  buildHistoryCompactCheckpoint,
+  matchHistoryCompactCheckpointPrefix,
+  validateHistoryCompactCheckpointShape,
+} from '../history-compact-checkpoint.js';
+import {
+  buildLlmHistorySummarizer,
+  type AiSdkGenerateTextLike,
+} from '../history-compact-summarizer.js';
+
+const RAW_SECRET = 'RAW-EXECUTION-EVIDENCE-'.repeat(200);
+const PROJECTED = 'bounded model-visible result';
+
+const STRUCTURED_SUMMARY = [
+  '## Goal',
+  'X',
+  '',
+  '## Progress',
+  '- done',
+  '',
+  '## Next Steps',
+  '1. continue',
+  '',
+  '## Critical Context',
+  '- (none)',
+].join('\n');
+
+describe('effective model history feeds budgeting and compaction', () => {
+  test('budgeting sizes the durable projection, not the raw execution fact', () => {
+    const projected = toolResultEvent('evt-3', RAW_SECRET, textProjection(PROJECTED));
+    const raw = toolResultEvent('evt-3', RAW_SECRET);
+
+    // Same raw result, but only the un-projected legacy event is sized by it.
+    assert.equal(estimateRuntimeEventsTokens([projected], 1), 'Bash'.length + PROJECTED.length);
+    assert.ok(estimateRuntimeEventsTokens([raw], 1) > RAW_SECRET.length);
+  });
+
+  test('summarization cannot read raw output the projection replaced', async () => {
+    let seen: Parameters<AiSdkGenerateTextLike>[0] | undefined;
+    const summarize = buildLlmHistorySummarizer({
+      resolveModel: () => 'fake-model',
+      generateText: async (options) => {
+        seen = options;
+        return { text: STRUCTURED_SUMMARY };
+      },
+    });
+
+    await summarize({
+      sessionId: 'session-1',
+      turnId: 'turn-1',
+      source: {
+        foldedRuntimeEvents: [
+          userEvent('evt-1', 'run it'),
+          toolCallEvent('evt-2'),
+          toolResultEvent('evt-3', RAW_SECRET, textProjection(PROJECTED)),
+        ],
+      },
+    });
+
+    const serialized = JSON.stringify(seen?.messages ?? []);
+    assert.ok(serialized.includes(PROJECTED));
+    assert.equal(serialized.includes('RAW-EXECUTION-EVIDENCE-'), false);
+  });
+
+  test('the source digest ignores raw evidence but tracks the effective projection', () => {
+    const covered = [
+      userEvent('evt-1', 'run it'),
+      toolCallEvent('evt-2'),
+      toolResultEvent('evt-3', RAW_SECRET, textProjection(PROJECTED)),
+    ];
+    const checkpoint = buildHistoryCompactCheckpoint({
+      sessionId: 'session-1',
+      coveredRuntimeEvents: covered,
+      summary: STRUCTURED_SUMMARY,
+      charsPerToken: 1,
+    });
+
+    // Raw evidence rewritten under an unchanged projection: still the same
+    // folded model history, so the checkpoint keeps replaying.
+    const rawRewritten = [
+      ...covered.slice(0, 2),
+      toolResultEvent('evt-3', 'a different raw fact', textProjection(PROJECTED)),
+    ];
+    assert.equal(matchHistoryCompactCheckpointPrefix(checkpoint, rawRewritten).reason, undefined);
+
+    // The projection itself replaced: the folded content is no longer what
+    // this checkpoint covered, so it must not replay over it.
+    const projectionReplaced = [
+      ...covered.slice(0, 2),
+      toolResultEvent('evt-3', RAW_SECRET, textProjection('[archived]')),
+    ];
+    assert.equal(
+      matchHistoryCompactCheckpointPrefix(checkpoint, projectionReplaced).reason,
+      'source_hash_mismatch',
+    );
+  });
+
+  test('a checkpoint minted under the raw-source policy no longer validates', () => {
+    const checkpoint = buildHistoryCompactCheckpoint({
+      sessionId: 'session-1',
+      coveredRuntimeEvents: [userEvent('evt-1', 'run it')],
+      summary: STRUCTURED_SUMMARY,
+      charsPerToken: 1,
+    });
+    const legacy = {
+      ...checkpoint,
+      source: {
+        ...checkpoint.source,
+        policyVersion: 'maka.compactable_runtime_event_projection.v1',
+      },
+    } as unknown as typeof checkpoint;
+
+    assert.equal(validateHistoryCompactCheckpointShape(checkpoint, 'session-1'), true);
+    assert.equal(validateHistoryCompactCheckpointShape(legacy, 'session-1'), false);
+  });
+});
+
+function textProjection(text: string): DurableToolResultProjection {
+  return { version: 1, kind: 'text', text };
+}
+
+function userEvent(id: string, text: string): RuntimeEvent {
+  return {
+    id,
+    invocationId: 'invocation-1',
+    sessionId: 'session-1',
+    runId: 'run-1',
+    turnId: 'turn-1',
+    ts: 1,
+    partial: false,
+    role: 'user',
+    author: 'user',
+    status: 'completed',
+    modelVisibility: 'visible',
+    content: { kind: 'text', text },
+  };
+}
+
+function toolCallEvent(id: string): RuntimeEvent {
+  return {
+    ...userEvent(id, ''),
+    role: 'model',
+    author: 'agent',
+    content: { kind: 'function_call', id: 'tool-call', name: 'Bash', args: {} },
+  };
+}
+
+function toolResultEvent(
+  id: string,
+  result: string,
+  modelProjection?: DurableToolResultProjection,
+): RuntimeEvent {
+  return {
+    ...userEvent(id, ''),
+    role: 'tool',
+    author: 'tool',
+    content: {
+      kind: 'function_response',
+      id: 'tool-call',
+      name: 'Bash',
+      result,
+      ...(modelProjection ? { modelProjection } : {}),
+    },
+  };
+}
diff --git a/packages/runtime/src/context-budget-helpers.ts b/packages/runtime/src/context-budget-helpers.ts
index 920114f6ea..b66e78aa1b 100644
--- a/packages/runtime/src/context-budget-helpers.ts
+++ b/packages/runtime/src/context-budget-helpers.ts
@@ -26,7 +26,10 @@ import type { RuntimeEvent } from '@maka/core/runtime-event';
  * modules can reuse them without a reverse import into `context-budget.ts`.
  *
  * These are intentionally dependency-free (only `node:crypto` and the
- * `RuntimeEvent` type); no domain policy types live here.
+ * `RuntimeEvent` type); no domain policy types live here. Sizing a
+ * RuntimeEvent is NOT such a helper — it must read the effective model
+ * projection — so `estimateRuntimeEventChars`/`estimateRuntimeEventsTokens`/
+ * `groupEventsByTurn` live with the reducer in `model-history.ts`.
  */
 
 export function estimateTokens(chars: number, charsPerToken = 4): number {
@@ -43,66 +46,10 @@ export function stableJsonLength(value: unknown): number {
   }
 }
 
-export function estimateRuntimeEventChars(event: RuntimeEvent): number {
-  let total = 0;
-  const content = event.content;
-  if (content?.kind === 'text' || content?.kind === 'thinking') total += content.text.length;
-  else if (content?.kind === 'function_call')
-    total += content.name.length + stableJsonLength(content.args);
-  else if (content?.kind === 'function_response')
-    total +=
-      content.name.length +
-      stableJsonLength(
-        content.providerExecuted && content.providerOutput !== undefined
-          ? content.providerOutput
-          : content.result,
-      );
-  else if (content?.kind === 'error') total += content.message.length;
-  return total;
-}
-
-export function estimateRuntimeEventsTokens(
-  events: readonly RuntimeEvent[],
-  charsPerToken = 4,
-): number {
-  const chars = events.reduce(
-    (total, event) =>
-      event.modelVisibility === 'hidden' ? total : total + estimateRuntimeEventChars(event),
-    0,
-  );
-  return estimateTokens(chars, charsPerToken);
-}
-
 export function turnKey(event: RuntimeEvent): string {
   return event.turnId || '<unknown-turn>';
 }
 
-export function groupEventsByTurn(
-  events: readonly RuntimeEvent[],
-  charsPerToken: number,
-): Array<{
-  turnId: string;
-  estimatedTokens: number;
-  events: RuntimeEvent[];
-}> {
-  const order: string[] = [];
-  const byTurn = new Map<string, RuntimeEvent[]>();
-  for (const event of events) {
-    const key = turnKey(event);
-    const group = byTurn.get(key);
-    if (group) group.push(event);
-    else {
-      order.push(key);
-      byTurn.set(key, [event]);
-    }
-  }
-  return order.map((turnId) => ({
-    turnId,
-    events: byTurn.get(turnId) ?? [],
-    estimatedTokens: estimateRuntimeEventsTokens(byTurn.get(turnId) ?? [], charsPerToken),
-  }));
-}
-
 export function uniqueSorted(values: readonly string[]): string[] {
   return [...new Set(values.filter((value) => value.length > 0))].sort();
 }
diff --git a/packages/runtime/src/context-budget.ts b/packages/runtime/src/context-budget.ts
index a38ad111c0..2e133ea7f6 100644
--- a/packages/runtime/src/context-budget.ts
+++ b/packages/runtime/src/context-budget.ts
@@ -17,15 +17,13 @@
  * under the License.
  */
 
-import {
-  estimateTokens,
-  estimateRuntimeEventsTokens,
-  stableJsonLength,
-} from './context-budget-helpers.js';
+import { estimateTokens, stableJsonLength } from './context-budget-helpers.js';
+import { estimateRuntimeEventsTokens } from './model-history.js';
 
 // Public re-export surface for @maka/runtime consumers. Explicit list keeps
 // the ./context-budget subpath from leaking leaf-internal collaboration symbols.
-export { estimateRuntimeEventsTokens, estimateTokens } from './context-budget-helpers.js';
+export { estimateTokens } from './context-budget-helpers.js';
+export { estimateRuntimeEventsTokens } from './model-history.js';
 export {
   ARCHIVED_TOOL_RESULT_PLACEHOLDER_KIND,
   ARCHIVED_TOOL_RESULT_REWRITE_VERSION,
diff --git a/packages/runtime/src/durable-tool-result-projection.ts b/packages/runtime/src/durable-tool-result-projection.ts
index f81e4d5f82..9dddcbe59c 100644
--- a/packages/runtime/src/durable-tool-result-projection.ts
+++ b/packages/runtime/src/durable-tool-result-projection.ts
@@ -42,6 +42,7 @@ import { markPersisted } from '@maka/core/persisted-value';
 import { decodePersistedToolResultContent } from '@maka/core/tool-result-record-schema';
 
 import type { ToolResultOutput } from './model-protocol.js';
+import { stableJsonLength } from './context-budget-helpers.js';
 import { toolResultOutput } from './tool-result-output.js';
 import { withToolResultArchiveResourceRef } from './tool-result-archive.js';
 import { projectBashToolResultForModel } from './bash-model-output.js';
@@ -163,6 +164,42 @@ export function durableProjectionToToolResultOutput(
   }
 }
 
+/**
+ * The one pure materialization of a replayed Tool Result into model-facing
+ * output. A durable projection wins; only a response that has none (legacy or
+ * provider-native) falls back to its raw output. Every consumer of effective
+ * model history — replay, summarization, provider-native compaction — goes
+ * through here so no second path can re-read what the projection removed.
+ */
+export function effectiveReplayToolResultOutput(item: {
+  modelProjection?: DurableToolResultProjection;
+  output: unknown;
+  isError: boolean;
+}): ToolResultOutput {
+  return item.modelProjection
+    ? durableProjectionToToolResultOutput(item.modelProjection)
+    : toolResultOutput(item.output, item.isError);
+}
+
+/** Model-visible character count of one materialized Tool Result output. */
+export function estimateToolResultOutputChars(output: ToolResultOutput): number {
+  switch (output.type) {
+    case 'text':
+    case 'error-text':
+      return output.value.length;
+    case 'json':
+    case 'error-json':
+      return stableJsonLength(output.value);
+    case 'content':
+      return output.value.reduce(
+        (total, part) => total + (part.type === 'text' ? part.text.length : 0),
+        0,
+      );
+    case 'execution-denied':
+      return output.reason?.length ?? 0;
+  }
+}
+
 export function rewriteDurableToolResultProjectionArtifactRefs(
   projection: DurableToolResultProjection,
   rewrite: (ref: DurableProjectionArtifactRef) => DurableProjectionArtifactRef,
diff --git a/packages/runtime/src/history-compact-checkpoint.ts b/packages/runtime/src/history-compact-checkpoint.ts
index d47463bfb3..ddea53ef0f 100644
--- a/packages/runtime/src/history-compact-checkpoint.ts
+++ b/packages/runtime/src/history-compact-checkpoint.ts
@@ -28,9 +28,15 @@ import {
   SECTIONED_SUMMARY_FORMAT,
   type SectionedSummaryFormat,
 } from './history-compact-summary-validation.js';
+import { effectiveToolResultModelValue } from './model-history.js';
 
+// v2: coverage and source digest are taken over EFFECTIVE model history (the
+// durable Tool Result projection), not raw RuntimeEvent evidence. A v1
+// checkpoint's digest was computed over a different source, so it fails the
+// shape check and its session re-summarizes rather than replaying a
+// coverage claim this policy never made.
 export const HISTORY_COMPACT_SOURCE_POLICY_VERSION =
-  'maka.compactable_runtime_event_projection.v1' as const;
+  'maka.compactable_runtime_event_projection.v2' as const;
 export interface HistoryCompactCheckpointSource {
   schemaVersion: 1;
   kind: 'runtime_event_projection';
@@ -725,10 +731,18 @@ function sameHistoryCompactSourceCoverage(
   );
 }
 
+/**
+ * A checkpoint replaces a contiguous prefix of EFFECTIVE model history, so its
+ * source digest must pin exactly that: raw execution evidence a durable
+ * projection already bounded or redacted is not part of what was folded, and
+ * changing it must not invalidate a valid checkpoint. Conversely, replacing a
+ * response's effective projection does change the digest, so a checkpoint can
+ * never be replayed over content it never covered.
+ */
 function historyCompactSourceDigest(events: readonly RuntimeEvent[]): string {
   const hash = createHash('sha256');
   for (const event of events) {
-    const serialized = stableStringify(event);
+    const serialized = stableStringify(effectiveDigestEvent(event));
     hash.update(String(Buffer.byteLength(serialized, 'utf8')));
     hash.update(':');
     hash.update(serialized);
@@ -737,6 +751,16 @@ function historyCompactSourceDigest(events: readonly RuntimeEvent[]): string {
   return `sha256:${hash.digest('hex')}`;
 }
 
+function effectiveDigestEvent(event: RuntimeEvent): unknown {
+  const content = event.content;
+  if (content?.kind !== 'function_response') return event;
+  const { result, providerOutput, modelProjection, ...identity } = content;
+  return {
+    ...event,
+    content: { ...identity, effective: effectiveToolResultModelValue(content, event.sessionId) },
+  };
+}
+
 function sha256(value: string): string {
   return createHash('sha256').update(value).digest('hex');
 }
diff --git a/packages/runtime/src/history-compact-summarizer.ts b/packages/runtime/src/history-compact-summarizer.ts
index f952b600df..bcfad2552c 100644
--- a/packages/runtime/src/history-compact-summarizer.ts
+++ b/packages/runtime/src/history-compact-summarizer.ts
@@ -23,7 +23,7 @@ import {
   findCheckpointSummaryDefect,
   SUMMARY_FORMAT_TEMPLATE,
 } from './history-compact-summary-validation.js';
-import { toolResultOutput } from './tool-result-output.js';
+import { effectiveReplayToolResultOutput } from './durable-tool-result-projection.js';
 import type { HistoryCompactSummaryInput } from './ai-sdk-compaction-contract.js';
 import {
   HistoryCompactSummarizerError,
@@ -297,7 +297,7 @@ export function replayPlanItemsToModelMessages(items: ReplayPlanItems): ModelMes
             type: 'tool-result',
             toolCallId: item.toolCallId,
             toolName: item.toolName,
-            output: toolResultOutput(item.output, item.isError),
+            output: effectiveReplayToolResultOutput(item),
           },
         ],
       };
diff --git a/packages/runtime/src/history-compact-summary-validation.ts b/packages/runtime/src/history-compact-summary-validation.ts
index 6ed2f5da25..eec8172a5a 100644
--- a/packages/runtime/src/history-compact-summary-validation.ts
+++ b/packages/runtime/src/history-compact-summary-validation.ts
@@ -19,7 +19,8 @@
 
 import type { RuntimeEvent } from '@maka/core/runtime-event';
 import type { ContextBudgetExhaustedDetail } from '@maka/core/events';
-import { estimateRuntimeEventsTokens, estimateTokens } from './context-budget-helpers.js';
+import { estimateTokens } from './context-budget-helpers.js';
+import { estimateRuntimeEventsTokens } from './model-history.js';
 
 // The single authority on what a history-compact checkpoint summary must look
 // like (#3029). The summarization prompt is built from the same constants and
diff --git a/packages/runtime/src/history-compaction.ts b/packages/runtime/src/history-compaction.ts
index ee50498ee5..1ee5fc1fb0 100644
--- a/packages/runtime/src/history-compaction.ts
+++ b/packages/runtime/src/history-compaction.ts
@@ -19,11 +19,8 @@
 
 import type { RuntimeEvent } from '@maka/core/runtime-event';
 import type { ContextBudgetDiagnostic } from '@maka/core/usage-stats/types';
-import {
-  estimateRuntimeEventChars,
-  estimateRuntimeEventsTokens,
-  finitePositive,
-} from './context-budget-helpers.js';
+import { finitePositive } from './context-budget-helpers.js';
+import { estimateRuntimeEventChars, estimateRuntimeEventsTokens } from './model-history.js';
 import { compactionDecisionDiagnosticPatch } from './compaction-boundary.js';
 import {
   HistoryCompactSummarizerError,
diff --git a/packages/runtime/src/model-history.ts b/packages/runtime/src/model-history.ts
index 1a74cde6c6..4bed67c0c2 100644
--- a/packages/runtime/src/model-history.ts
+++ b/packages/runtime/src/model-history.ts
@@ -63,12 +63,118 @@ import {
 } from '@maka/core/runtime-event';
 import { formatAttachmentResourceRef } from '@maka/core/attachments';
 import type { AttachmentRef, QuoteRef } from '@maka/core/events';
-import type { ModelMessage, UserContent, UserModelMessage } from './model-protocol.js';
-import { decodeEffectiveToolResultProjection } from './durable-tool-result-projection.js';
+import type {
+  ModelMessage,
+  ToolResultOutput,
+  UserContent,
+  UserModelMessage,
+} from './model-protocol.js';
+import {
+  decodeEffectiveToolResultProjection,
+  durableProjectionToToolResultOutput,
+  estimateToolResultOutputChars,
+} from './durable-tool-result-projection.js';
+import { estimateTokens, stableJsonLength, turnKey } from './context-budget-helpers.js';
 import type { DurableToolResultProjection } from '@maka/core/durable-tool-result-projection';
 
 export const PROVIDER_REPLAY_PROJECTION_VERSION = 1;
 
+// ============================================================================
+// Effective model-history sizing
+// ============================================================================
+
+/**
+ * The model-facing value a `function_response` event contributes to effective
+ * history. Sizing and checkpoint source digests both read THIS, never the raw
+ * execution fact that the durable projection already bounded or redacted.
+ */
+export type EffectiveToolResultModelValue =
+  | { kind: 'output'; output: ToolResultOutput }
+  | { kind: 'opaque'; value: unknown }
+  | { kind: 'invalid'; message: string };
+
+export function effectiveToolResultModelValue(
+  content: Extract<RuntimeEventContent, { kind: 'function_response' }>,
+  sessionId: string,
+): EffectiveToolResultModelValue {
+  const effective = decodeEffectiveToolResultProjection(content, sessionId);
+  switch (effective.kind) {
+    case 'projection':
+      return { kind: 'output', output: durableProjectionToToolResultOutput(effective.projection) };
+    case 'provider_native':
+    case 'legacy_output':
+      return { kind: 'opaque', value: effective.output };
+    case 'invalid_legacy':
+      return { kind: 'invalid', message: effective.message };
+  }
+}
+
+/** Model-visible character count of a `function_response`'s effective value. */
+export function estimateEffectiveToolResultChars(
+  content: Extract<RuntimeEventContent, { kind: 'function_response' }>,
+  sessionId: string,
+): number {
+  const value = effectiveToolResultModelValue(content, sessionId);
+  switch (value.kind) {
+    case 'output':
+      return estimateToolResultOutputChars(value.output);
+    case 'opaque':
+      return stableJsonLength(value.value);
+    case 'invalid':
+      return value.message.length;
+  }
+}
+
+export function estimateRuntimeEventChars(event: RuntimeEvent): number {
+  let total = 0;
+  const content = event.content;
+  if (content?.kind === 'text' || content?.kind === 'thinking') total += content.text.length;
+  else if (content?.kind === 'function_call')
+    total += content.name.length + stableJsonLength(content.args);
+  else if (content?.kind === 'function_response')
+    total += content.name.length + estimateEffectiveToolResultChars(content, event.sessionId);
+  else if (content?.kind === 'error') total += content.message.length;
+  return total;
+}
+
+export function estimateRuntimeEventsTokens(
+  events: readonly RuntimeEvent[],
+  charsPerToken = 4,
+): number {
+  const chars = events.reduce(
+    (total, event) =>
+      event.modelVisibility === 'hidden' ? total : total + estimateRuntimeEventChars(event),
+    0,
+  );
+  return estimateTokens(chars, charsPerToken);
+}
+
+export function groupEventsByTurn(
+  events: readonly RuntimeEvent[],
+  charsPerToken: number,
+): Array<{
+  turnId: string;
+  estimatedTokens: number;
+  events: RuntimeEvent[];
+}> {
+  const order: string[] = [];
+  const byTurn = new Map<string, RuntimeEvent[]>();
+  for (const event of events) {
+    const key = turnKey(event);
+    const group = byTurn.get(key);
+    if (group) group.push(event);
+    else {
+      order.push(key);
+      byTurn.set(key, [event]);
+    }
+  }
+  return order.map((turnId) => ({
+    turnId,
+    events: byTurn.get(turnId) ?? [],
+    estimatedTokens: estimateRuntimeEventsTokens(byTurn.get(turnId) ?? [], charsPerToken),
+  }));
+}
+
 // ============================================================================
 // Output type
 // ============================================================================
diff --git a/packages/runtime/src/openai-codex-history-compactor.ts b/packages/runtime/src/openai-codex-history-compactor.ts
index b147a24fb0..9d9e843dec 100644
--- a/packages/runtime/src/openai-codex-history-compactor.ts
+++ b/packages/runtime/src/openai-codex-history-compactor.ts
@@ -35,7 +35,7 @@ import {
   type RuntimeEventModelReplayItem,
 } from './model-history.js';
 import { withProviderStreamTracking } from './provider-request-telemetry.js';
-import { toolResultOutput } from './tool-result-output.js';
+import { effectiveReplayToolResultOutput } from './durable-tool-result-projection.js';
 import { providerFailureDiagnostic } from './provider-error-classification.js';
 
 export { fitHistoryCompactMessages as fitOpenAiCodexCompactionMessages } from './history-compact-input-fit.js';
@@ -232,7 +232,7 @@ export function openAiCodexCompactionMessages(events: readonly RuntimeEvent[]):
           type: 'tool-result',
           toolCallId: result.toolCallId,
           toolName: result.toolName,
-          output: toolResultOutput(result.output, result.isError),
+          output: effectiveReplayToolResultOutput(result),
         },
       ],
     });
diff --git a/packages/runtime/src/session-recap.ts b/packages/runtime/src/session-recap.ts
index 1333fbf159..4c8549cb40 100644
--- a/packages/runtime/src/session-recap.ts
+++ b/packages/runtime/src/session-recap.ts
@@ -20,7 +20,8 @@
 import type { RuntimeEvent } from '@maka/core/runtime-event';
 import type { RuntimeExecutionConnection } from '@maka/core/llm-connections';
 import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
-import { groupEventsByTurn, stableJsonLength } from './context-budget-helpers.js';
+import { stableJsonLength } from './context-budget-helpers.js';
+import { groupEventsByTurn } from './model-history.js';
 import { HistoryCompactSummarizerError } from './history-compact-error.js';
 import { fitHistoryCompactMessages } from './history-compact-input-fit.js';
 import { replayPlanItemsToModelMessages } from './history-compact-summarizer.js';


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org