فهرست منبع

fix: reduce repeated history processing and token estimation (#250)

* fix: reduce repeated history processing and token estimation

* test: preserve native snapshot cloning boundaries

* fix: preserve shared references across semantic snapshot cloning
DanielWalnut 2 ماه پیش
والد
کامیت
3b3310f37e

+ 25 - 1
packages/agent-modules/context-manager/src/token-estimator.ts

@@ -199,8 +199,15 @@ function getLastAssistantUsageInfo(
   return undefined;
   return undefined;
 }
 }
 
 
+const MAX_CACHED_TEXT_UNITS = 1_048_576;
+const MAX_CACHED_TEXT_ENTRIES = 2_048;
+
 export class BpeTokenEstimator implements TokenEstimator {
 export class BpeTokenEstimator implements TokenEstimator {
   private readonly countExactTokens: (text: string) => number;
   private readonly countExactTokens: (text: string) => number;
+  // Content keys remain valid across detached histories, edits and model
+  // projections. Bound retained UTF-16 text as well as entry count.
+  private readonly textTokens = new Map<string, number>();
+  private cachedTextUnits = 0;
 
 
   /**
   /**
    * @param encoder Override the default o200k_base tokenizer. Tests inject
    * @param encoder Override the default o200k_base tokenizer. Tests inject
@@ -222,12 +229,29 @@ export class BpeTokenEstimator implements TokenEstimator {
 
 
   estimateTextTokens(text: string): number {
   estimateTextTokens(text: string): number {
     if (!text) return 0;
     if (!text) return 0;
+    const cached = this.textTokens.get(text);
+    if (cached !== undefined) {
+      this.textTokens.delete(text);
+      this.textTokens.set(text, cached);
+      return cached;
+    }
     try {
     try {
       if (text.length > MAX_EXACT_TOKENIZER_CHARS && hasOversizedAlphanumericRun(text)) {
       if (text.length > MAX_EXACT_TOKENIZER_CHARS && hasOversizedAlphanumericRun(text)) {
         return estimateTextTokensUpperBound(text);
         return estimateTextTokensUpperBound(text);
       }
       }
       const tokens = this.countExactTokens(text);
       const tokens = this.countExactTokens(text);
-      return Number.isFinite(tokens) && tokens >= 0 ? tokens : estimateTextTokensUpperBound(text);
+      if (!Number.isFinite(tokens) || tokens < 0) return estimateTextTokensUpperBound(text);
+      if (text.length <= MAX_CACHED_TEXT_UNITS) {
+        while (this.textTokens.size >= MAX_CACHED_TEXT_ENTRIES || this.cachedTextUnits + text.length > MAX_CACHED_TEXT_UNITS) {
+          const oldest = this.textTokens.keys().next().value;
+          if (oldest === undefined) break;
+          this.textTokens.delete(oldest);
+          this.cachedTextUnits -= oldest.length;
+        }
+        this.textTokens.set(text, tokens);
+        this.cachedTextUnits += text.length;
+      }
+      return tokens;
     } catch {
     } catch {
       return estimateTextTokensUpperBound(text);
       return estimateTextTokensUpperBound(text);
     }
     }

+ 4 - 3
packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-provider.ts

@@ -305,7 +305,7 @@ export function createSessionSystemCanonicalHistoryProvider(
             `Canonical compaction generation verification failed: ${change.sessionId}`,
             `Canonical compaction generation verification failed: ${change.sessionId}`,
           );
           );
         }
         }
-        await syncIndex(change.sessionId, paths, true);
+        await syncIndex(change.sessionId, paths, true, committed);
         const result = {
         const result = {
           revision: canonicalActiveHistoryRevision(committed),
           revision: canonicalActiveHistoryRevision(committed),
           generation: committedGeneration,
           generation: committedGeneration,
@@ -335,7 +335,7 @@ export function createSessionSystemCanonicalHistoryProvider(
       }
       }
       options.activity?.notify(sessionId);
       options.activity?.notify(sessionId);
     }
     }
-    await syncIndex(sessionId, paths, true);
+    await syncIndex(sessionId, paths, true, records);
     return historySnapshot(records, allowPendingToolCallTail);
     return historySnapshot(records, allowPendingToolCallTail);
   }
   }
 
 
@@ -372,8 +372,9 @@ export function createSessionSystemCanonicalHistoryProvider(
     sessionId: string,
     sessionId: string,
     paths: SessionHistoryPaths,
     paths: SessionHistoryPaths,
     allowMissingParent = false,
     allowMissingParent = false,
+    verifiedRecords?: readonly CanonicalHistoryEnvelope[],
   ): Promise<void> {
   ): Promise<void> {
-    const active = await files.readActiveStrict(paths.messages);
+    const active = verifiedRecords ?? (await files.readActiveStrict(paths.messages));
     const adapter = indexes.get(sessionId) ?? createCanonicalHistoryIndexAdapter(paths.sessionDir);
     const adapter = indexes.get(sessionId) ?? createCanonicalHistoryIndexAdapter(paths.sessionDir);
     indexes.set(sessionId, adapter);
     indexes.set(sessionId, adapter);
     try {
     try {

+ 11 - 6
packages/local-runtime-v2/src/service/turn-system/agent-host/history/durable-canonical-history-store.ts

@@ -27,9 +27,10 @@ export interface DurableCanonicalHistoryProvider {
   read(sessionId: string): Promise<CanonicalHistorySnapshot>;
   read(sessionId: string): Promise<CanonicalHistorySnapshot>;
   /** Active post-mutation history; the final tool round may still await results. */
   /** Active post-mutation history; the final tool round may still await results. */
   readActive(sessionId: string): Promise<CanonicalHistorySnapshot>;
   readActive(sessionId: string): Promise<CanonicalHistorySnapshot>;
-  append(change: CanonicalHistoryChange): Promise<unknown>;
-  replace(change: CanonicalHistoryChange): Promise<unknown>;
-  compact?(change: CanonicalHistoryCompactionChange): Promise<unknown>;
+  /** Return the verified post-write snapshot from the same lane, or request a reread with void. */
+  append(change: CanonicalHistoryChange): Promise<CanonicalHistorySnapshot | void>;
+  replace(change: CanonicalHistoryChange): Promise<CanonicalHistorySnapshot | void>;
+  compact?(change: CanonicalHistoryCompactionChange): Promise<CanonicalHistorySnapshot | void>;
   settleTurnTail?(mutation: SettleTurnTailMutation): Promise<TurnHistoryMutationCommit>;
   settleTurnTail?(mutation: SettleTurnTailMutation): Promise<TurnHistoryMutationCommit>;
   retractTurn?(mutation: RetractTurnMutation): Promise<TurnHistoryMutationCommit>;
   retractTurn?(mutation: RetractTurnMutation): Promise<TurnHistoryMutationCommit>;
 }
 }
@@ -102,13 +103,17 @@ export class DurableCanonicalHistoryStore implements CanonicalHistoryStore {
   private commit(
   private commit(
     kind: 'append' | 'replace',
     kind: 'append' | 'replace',
     change: CanonicalHistoryChange,
     change: CanonicalHistoryChange,
-    mutate: (snapshot: CanonicalHistoryChange) => Promise<unknown>,
+    mutate: (snapshot: CanonicalHistoryChange) => Promise<CanonicalHistorySnapshot | void>,
   ): Promise<CanonicalHistoryCommit> {
   ): Promise<CanonicalHistoryCommit> {
     const snapshot = captureSemanticSnapshot(change).value;
     const snapshot = captureSemanticSnapshot(change).value;
     validateCanonicalHistoryChange(snapshot, kind);
     validateCanonicalHistoryChange(snapshot, kind);
     return this.lane.run(snapshot.sessionId, async () => {
     return this.lane.run(snapshot.sessionId, async () => {
-      await mutate(snapshot);
-      return this.readActiveCommitted(snapshot.sessionId);
+      const committed = await mutate(snapshot);
+      // Session-owned providers already reread and validate inside their lane.
+      // Legacy adapters returning void retain the strict post-write read.
+      return committed === undefined
+        ? this.readActiveCommitted(snapshot.sessionId)
+        : this.readProviderSnapshot(committed);
     });
     });
   }
   }
 
 

+ 6 - 136
packages/local-runtime-v2/src/service/turn-system/agent-host/history/incremental-sha256.ts

@@ -1,34 +1,10 @@
-const BLOCK_BYTES = 64;
-const UTF8_CHUNK_CODE_UNITS = 8 * 1_024;
-
-const INITIAL_STATE = [
-  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
-] as const;
+import { createHash } from 'node:crypto';
 
 
-const ROUND_CONSTANTS = new Uint32Array([
-  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
-  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
-  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
-  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
-  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
-  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
-  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
-  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
-]);
+const UTF8_CHUNK_CODE_UNITS = 8 * 1_024;
 
 
-/**
- * Dependency-free incremental SHA-256 for AgentHost semantic identity.
- * Text is encoded in bounded chunks so hashing one large History string does
- * not allocate another payload-sized Buffer. This is intentionally internal;
- * persistence digests continue to use their owning adapters.
- */
+/** Native SHA-256 with bounded UTF-8 chunks and the existing update boundaries. */
 export class IncrementalSha256 {
 export class IncrementalSha256 {
-  private readonly state = new Uint32Array(INITIAL_STATE);
-  private readonly block = new Uint8Array(BLOCK_BYTES);
-  private readonly schedule = new Uint32Array(64);
-  private readonly textEncoder = new TextEncoder();
-  private bufferedBytes = 0;
-  private totalBytes = 0;
+  private readonly hash = createHash('sha256');
   private finalized = false;
   private finalized = false;
 
 
   update(value: string): void {
   update(value: string): void {
@@ -36,7 +12,7 @@ export class IncrementalSha256 {
     let offset = 0;
     let offset = 0;
     while (offset < value.length) {
     while (offset < value.length) {
       const end = safeUtf8ChunkEnd(value, offset);
       const end = safeUtf8ChunkEnd(value, offset);
-      this.updateBytes(this.textEncoder.encode(value.slice(offset, end)));
+      this.hash.update(value.slice(offset, end), 'utf8');
       offset = end;
       offset = end;
     }
     }
   }
   }
@@ -44,96 +20,7 @@ export class IncrementalSha256 {
   digestHex(): string {
   digestHex(): string {
     if (this.finalized) throw new Error('SHA-256 digest is already finalized.');
     if (this.finalized) throw new Error('SHA-256 digest is already finalized.');
     this.finalized = true;
     this.finalized = true;
-    const messageBytes = this.totalBytes;
-    this.block[this.bufferedBytes] = 0x80;
-    this.bufferedBytes += 1;
-    if (this.bufferedBytes > 56) {
-      this.block.fill(0, this.bufferedBytes);
-      this.compress();
-      this.bufferedBytes = 0;
-    }
-    this.block.fill(0, this.bufferedBytes, 56);
-    const messageBits = messageBytes * 8;
-    writeUint32BigEndian(this.block, 56, Math.floor(messageBits / 0x1_0000_0000));
-    writeUint32BigEndian(this.block, 60, messageBits >>> 0);
-    this.compress();
-    return [...this.state].map((word) => word.toString(16).padStart(8, '0')).join('');
-  }
-
-  private updateBytes(bytes: Uint8Array): void {
-    this.totalBytes += bytes.length;
-    let offset = 0;
-    while (offset < bytes.length) {
-      const copied = Math.min(BLOCK_BYTES - this.bufferedBytes, bytes.length - offset);
-      this.block.set(bytes.subarray(offset, offset + copied), this.bufferedBytes);
-      this.bufferedBytes += copied;
-      offset += copied;
-      if (this.bufferedBytes !== BLOCK_BYTES) continue;
-      this.compress();
-      this.bufferedBytes = 0;
-    }
-  }
-
-  private compress(): void {
-    const words = this.schedule;
-    for (let index = 0; index < 16; index += 1) {
-      const offset = index * 4;
-      words[index] =
-        (arrayValue(this.block, offset) << 24) |
-        (arrayValue(this.block, offset + 1) << 16) |
-        (arrayValue(this.block, offset + 2) << 8) |
-        arrayValue(this.block, offset + 3);
-    }
-    for (let index = 16; index < 64; index += 1) {
-      const prior15 = arrayValue(words, index - 15);
-      const prior2 = arrayValue(words, index - 2);
-      const sigma0 = rotateRight(prior15, 7) ^ rotateRight(prior15, 18) ^ (prior15 >>> 3);
-      const sigma1 = rotateRight(prior2, 17) ^ rotateRight(prior2, 19) ^ (prior2 >>> 10);
-      words[index] =
-        (arrayValue(words, index - 16) + sigma0 + arrayValue(words, index - 7) + sigma1) >>> 0;
-    }
-    this.compressRounds(words);
-  }
-
-  private compressRounds(words: Uint32Array): void {
-    let a = arrayValue(this.state, 0);
-    let b = arrayValue(this.state, 1);
-    let c = arrayValue(this.state, 2);
-    let d = arrayValue(this.state, 3);
-    let e = arrayValue(this.state, 4);
-    let f = arrayValue(this.state, 5);
-    let g = arrayValue(this.state, 6);
-    let h = arrayValue(this.state, 7);
-    for (let index = 0; index < 64; index += 1) {
-      const upperSigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
-      const choose = (e & f) ^ (~e & g);
-      const temporary1 =
-        (h +
-          upperSigma1 +
-          choose +
-          arrayValue(ROUND_CONSTANTS, index) +
-          arrayValue(words, index)) >>>
-        0;
-      const upperSigma0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
-      const majority = (a & b) ^ (a & c) ^ (b & c);
-      const temporary2 = (upperSigma0 + majority) >>> 0;
-      h = g;
-      g = f;
-      f = e;
-      e = (d + temporary1) >>> 0;
-      d = c;
-      c = b;
-      b = a;
-      a = (temporary1 + temporary2) >>> 0;
-    }
-    this.state[0] = (arrayValue(this.state, 0) + a) >>> 0;
-    this.state[1] = (arrayValue(this.state, 1) + b) >>> 0;
-    this.state[2] = (arrayValue(this.state, 2) + c) >>> 0;
-    this.state[3] = (arrayValue(this.state, 3) + d) >>> 0;
-    this.state[4] = (arrayValue(this.state, 4) + e) >>> 0;
-    this.state[5] = (arrayValue(this.state, 5) + f) >>> 0;
-    this.state[6] = (arrayValue(this.state, 6) + g) >>> 0;
-    this.state[7] = (arrayValue(this.state, 7) + h) >>> 0;
+    return this.hash.digest('hex');
   }
   }
 }
 }
 
 
@@ -152,20 +39,3 @@ function isHighSurrogate(value: number): boolean {
 function isLowSurrogate(value: number): boolean {
 function isLowSurrogate(value: number): boolean {
   return value >= 0xdc00 && value <= 0xdfff;
   return value >= 0xdc00 && value <= 0xdfff;
 }
 }
-
-function rotateRight(value: number, bits: number): number {
-  return (value >>> bits) | (value << (32 - bits));
-}
-
-function writeUint32BigEndian(target: Uint8Array, offset: number, value: number): void {
-  target[offset] = (value >>> 24) & 0xff;
-  target[offset + 1] = (value >>> 16) & 0xff;
-  target[offset + 2] = (value >>> 8) & 0xff;
-  target[offset + 3] = value & 0xff;
-}
-
-function arrayValue(values: Uint8Array | Uint32Array, index: number): number {
-  const value = values[index];
-  if (value === undefined) throw new RangeError(`SHA-256 array index is out of bounds: ${index}.`);
-  return value;
-}

+ 47 - 12
packages/local-runtime-v2/src/service/turn-system/agent-host/history/semantic-identity.ts

@@ -5,6 +5,9 @@ export interface SemanticSnapshot<T> {
   readonly fingerprint: string;
   readonly fingerprint: string;
 }
 }
 
 
+const ownedValues = new WeakSet<object>();
+const fingerprints = new WeakMap<object, string>();
+
 /**
 /**
  * Detach callback-owned History/event data before it becomes an in-run
  * Detach callback-owned History/event data before it becomes an in-run
  * identity or deferred delivery payload. Unsupported or cyclic values fail
  * identity or deferred delivery payload. Unsupported or cyclic values fail
@@ -12,12 +15,29 @@ export interface SemanticSnapshot<T> {
  * encoded payload size.
  * encoded payload size.
  */
  */
 export function captureSemanticSnapshot<T>(value: T): SemanticSnapshot<T> {
 export function captureSemanticSnapshot<T>(value: T): SemanticSnapshot<T> {
-  const snapshot = structuredClone(value);
-  const encoder = new SemanticIdentityEncoder(new IncrementalSha256());
-  encodeValue(snapshot, new WeakSet<object>(), encoder);
+  // Clone an external graph in one operation: independent subtree clones can
+  // change aliasing and getter order. Reuse only an already-owned root.
+  const snapshot =
+    typeof value === 'object' && value !== null && ownedValues.has(value)
+      ? value
+      : freezeSemanticValue(structuredClone(value), new WeakSet<object>());
+  let fingerprint: string | undefined;
   return {
   return {
-    value: freezeSemanticValue(snapshot, new WeakSet<object>()),
-    fingerprint: encoder.digest(),
+    value: snapshot,
+    // Value-only consumers still validate and detach eagerly, but never encode
+    // or hash the history. Only values frozen by this module may be reused.
+    get fingerprint() {
+      if (fingerprint !== undefined) return fingerprint;
+      const object = typeof snapshot === 'object' && snapshot !== null ? snapshot : undefined;
+      fingerprint = object ? fingerprints.get(object) : undefined;
+      if (fingerprint === undefined) {
+        const encoder = new SemanticIdentityEncoder(new IncrementalSha256());
+        encodeValue(snapshot, new WeakSet<object>(), encoder);
+        fingerprint = encoder.digest();
+        if (object) fingerprints.set(object, fingerprint);
+      }
+      return fingerprint;
+    },
   };
   };
 }
 }
 
 
@@ -54,13 +74,28 @@ class SemanticIdentityEncoder {
   }
   }
 }
 }
 
 
-function freezeSemanticValue<T>(value: T, seen: WeakSet<object>): T {
-  if (typeof value !== 'object' || value === null || seen.has(value)) return value;
-  seen.add(value);
-  Reflect.ownKeys(value).forEach((key) => {
-    freezeSemanticValue(Reflect.get(value, key), seen);
-  });
-  return Object.freeze(value);
+function freezeSemanticValue<T>(value: T, ancestors: WeakSet<object>): T {
+  if (typeof value !== 'object' || value === null) {
+    if (!['undefined', 'string', 'boolean', 'number'].includes(typeof value) && value !== null) {
+      throw new TypeError(`Unsupported semantic identity value: ${typeof value}.`);
+    }
+    return value;
+  }
+  if (ownedValues.has(value)) return value;
+  if (ancestors.has(value)) throw new TypeError('Cyclic semantic identity values are unsupported.');
+  const prototype = Object.getPrototypeOf(value);
+  if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {
+    throw new TypeError('Semantic identity values must contain only plain objects and arrays.');
+  }
+  if (Object.getOwnPropertySymbols(value).length > 0) {
+    throw new TypeError('Symbol-keyed semantic identity values are unsupported.');
+  }
+  ancestors.add(value);
+  for (const key of Object.keys(value)) freezeSemanticValue(Reflect.get(value, key), ancestors);
+  ancestors.delete(value);
+  Object.freeze(value);
+  ownedValues.add(value);
+  return value;
 }
 }
 
 
 function encodeValue(
 function encodeValue(

+ 19 - 5
packages/local-runtime-v2/src/service/turn-system/production-composition.ts

@@ -855,8 +855,16 @@ function adaptCanonicalHistory(
         identityVector: snapshot.identityVector,
         identityVector: snapshot.identityVector,
       };
       };
     },
     },
-    append: (change) => provider.append(requireHistoryOperation(change)),
-    replace: (change) => provider.replace(requireHistoryOperation(change)),
+    append: async (change) => {
+      const committed = await provider.append(requireHistoryOperation(change));
+      validateCanonicalHistoryMessages(committed.messages);
+      return { ...committed, messages: committed.messages };
+    },
+    replace: async (change) => {
+      const committed = await provider.replace(requireHistoryOperation(change));
+      validateCanonicalHistoryMessages(committed.messages);
+      return { ...committed, messages: committed.messages };
+    },
     compact: async (change: CanonicalHistoryCompactionChange) => {
     compact: async (change: CanonicalHistoryCompactionChange) => {
       const operation = requireHistoryOperation(change);
       const operation = requireHistoryOperation(change);
       if (operation.reason !== 'replaceMessages' || operation.operation.kind !== 'compaction') {
       if (operation.reason !== 'replaceMessages' || operation.operation.kind !== 'compaction') {
@@ -875,14 +883,20 @@ function adaptCanonicalHistory(
           : { currentUserSourceIndex: metadata.currentUserSourceIndex }),
           : { currentUserSourceIndex: metadata.currentUserSourceIndex }),
       } as const;
       } as const;
       if (metadata.method !== 'llm_checkpoint') {
       if (metadata.method !== 'llm_checkpoint') {
-        await provider.compact({
+        const committed = await provider.compact({
           ...baseChange,
           ...baseChange,
           method: metadata.method,
           method: metadata.method,
           replacementSourceIndexes: metadata.replacementSourceIndexes,
           replacementSourceIndexes: metadata.replacementSourceIndexes,
         });
         });
-        return;
+        validateCanonicalHistoryMessages(committed.messages);
+        return { ...committed, messages: committed.messages };
       }
       }
-      await provider.compact({ ...baseChange, method: metadata.method });
+      const committed = await provider.compact({
+        ...baseChange,
+        method: metadata.method,
+      });
+      validateCanonicalHistoryMessages(committed.messages);
+      return { ...committed, messages: committed.messages };
     },
     },
     settleTurnTail: async (input) => {
     settleTurnTail: async (input) => {
       if (!mutation.settleTurnTail) {
       if (!mutation.settleTurnTail) {

+ 1 - 0
release/public-source.json

@@ -3301,6 +3301,7 @@
     "scripts/verify.mjs",
     "scripts/verify.mjs",
     "test/byok.test.mjs",
     "test/byok.test.mjs",
     "test/executable-resolution.test.ts",
     "test/executable-resolution.test.ts",
+    "test/history-processing.test.ts",
     "test/network-deny.mjs",
     "test/network-deny.mjs",
     "test/offline-environment.mjs",
     "test/offline-environment.mjs",
     "test/public-artifact.test.mjs",
     "test/public-artifact.test.mjs",

+ 329 - 0
test/history-processing.test.ts

@@ -0,0 +1,329 @@
+import { createHash } from 'node:crypto';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import { IncrementalSha256 } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/incremental-sha256.js';
+import { captureSemanticSnapshot } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/semantic-identity.js';
+import { DurableCanonicalHistoryStore } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/durable-canonical-history-store.js';
+import type { CanonicalHistoryChange } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/contracts.js';
+import { BpeTokenEstimator } from '../packages/agent-modules/context-manager/src/token-estimator.js';
+import { createSessionSystemCanonicalHistoryProvider } from '../packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-provider.js';
+import { createCanonicalHistoryFileAdapter } from '../packages/local-runtime-v2/src/service/session-system/sessions/representation/canonical-history.js';
+import {
+  resolveSessionHistoryPaths,
+  utcSessionHistoryRelativeDir,
+} from '../packages/local-runtime-v2/src/service/session-system/messages/history/session-history-paths.js';
+import type { SessionRecord } from '../packages/local-runtime-v2/src/service/session-system/sessions/repo/contract.js';
+
+describe('native incremental semantic hashing', () => {
+  const inputs = ['', 'abc', '中文🙂', '\ud800', '\udc00', 'a'.repeat(8191) + '🙂tail'];
+  for (const length of [55, 56, 63, 64, 65, 8191, 8192, 8193, 32769]) {
+    inputs.push('x'.repeat(length), '中'.repeat(length));
+  }
+  it.each(inputs)('preserves UTF-8 hashing %#', (input) => {
+    const hash = new IncrementalSha256();
+    hash.update(input);
+    expect(hash.digestHex()).toBe(createHash('sha256').update(input).digest('hex'));
+    expect(() => hash.update('')).toThrow('finalized');
+    expect(() => hash.digestHex()).toThrow('finalized');
+  });
+  it('preserves encoding boundaries between separate updates', () => {
+    const hash = new IncrementalSha256();
+    hash.update('\ud83d');
+    hash.update('\ude42');
+    expect(hash.digestHex()).toBe(
+      createHash('sha256').update('\ud83d').update('\ude42').digest('hex'),
+    );
+  });
+});
+
+describe('semantic snapshots', () => {
+  it('detaches and freezes eagerly but hashes only when identity is requested', () => {
+    const hash = vi.spyOn(IncrementalSha256.prototype, 'update');
+    try {
+      const original = { messages: [{ text: 'before' }] };
+      const snapshot = captureSemanticSnapshot(original);
+      original.messages[0]!.text = 'after';
+      expect(snapshot.value.messages[0]!.text).toBe('before');
+      expect(Object.isFrozen(snapshot.value.messages[0])).toBe(true);
+      expect(hash).not.toHaveBeenCalled();
+      const reused = captureSemanticSnapshot(snapshot.value);
+      expect(reused.value).toBe(snapshot.value);
+      const wrapped = captureSemanticSnapshot({
+        history: snapshot.value.messages,
+      });
+      expect(wrapped.value.history).not.toBe(snapshot.value.messages);
+      expect(wrapped.value.history).toEqual(snapshot.value.messages);
+      const fingerprint = snapshot.fingerprint;
+      expect(hash).toHaveBeenCalled();
+      hash.mockClear();
+      expect(reused.fingerprint).toBe(fingerprint);
+      expect(hash).not.toHaveBeenCalled();
+      expect(captureSemanticSnapshot(original).fingerprint).not.toBe(fingerprint);
+    } finally {
+      hash.mockRestore();
+    }
+  });
+  it('does not trust externally frozen objects with mutable descendants', () => {
+    const original = Object.freeze({ nested: { text: 'before' } });
+    const snapshot = captureSemanticSnapshot(original);
+    original.nested.text = 'after';
+    expect(snapshot.value.nested.text).toBe('before');
+  });
+  it('preserves native rejection of proxies without invoking their traps', () => {
+    const trap = vi.fn();
+    const value = new Proxy({}, { ownKeys: trap });
+    expect(() => captureSemanticSnapshot(value)).toThrow();
+    expect(trap).not.toHaveBeenCalled();
+  });
+  it('preserves native enumeration when an accessor deletes another field', () => {
+    const value = {
+      get first() {
+        delete this.second;
+        return 'first';
+      },
+      second: 'deleted' as string | undefined,
+    };
+    expect(captureSemanticSnapshot(value).value).toEqual({ first: 'first' });
+  });
+  it.each([false, true])(
+    'preserves shared references across a mutating getter (getter first: %s)',
+    (getterFirst) => {
+      const makeInput = () => {
+        const shared = { value: 1 };
+        const getter = vi.fn(() => {
+          shared.value = 2;
+          return shared;
+        });
+        const nested = {
+          get shared() {
+            return getter();
+          },
+        };
+        return { input: getterFirst ? { nested, shared } : { shared, nested }, getter };
+      };
+      const expected = structuredClone(makeInput().input);
+      const { input, getter } = makeInput();
+      const snapshot = captureSemanticSnapshot(input);
+      expect(snapshot.value).toEqual(expected);
+      expect(snapshot.value.shared).toBe(snapshot.value.nested.shared);
+      expect(snapshot.fingerprint).toBe(captureSemanticSnapshot(expected).fingerprint);
+      expect(getter).toHaveBeenCalledTimes(1);
+    },
+  );
+  it('preserves shared references across a class instance normalized by native cloning', () => {
+    const shared = { value: 1 };
+    class Container {
+      child = shared;
+    }
+    const snapshot = captureSemanticSnapshot({ shared, nested: new Container() });
+    expect(snapshot.value.shared).toBe(snapshot.value.nested.child);
+    expect(Object.getPrototypeOf(snapshot.value.nested)).toBe(Object.prototype);
+  });
+  it.each([new Date(), new Map(), new Uint8Array([1]), 1n])(
+    'rejects unsupported value-only payloads %#',
+    (value) => {
+      expect(() => captureSemanticSnapshot(value).value).toThrow();
+    },
+  );
+  it('rejects cycles eagerly and accepts shared acyclic objects', () => {
+    const cyclic: { self?: unknown } = {};
+    cyclic.self = cyclic;
+    expect(() => captureSemanticSnapshot(cyclic).value).toThrow('Cyclic');
+    const shared = { value: 'same' };
+    expect(captureSemanticSnapshot([shared, shared]).fingerprint).toBe(
+      captureSemanticSnapshot([{ value: 'same' }, { value: 'same' }]).fingerprint,
+    );
+  });
+  it('retains ordering, framing and special number distinctions', () => {
+    const fingerprint = (value: unknown) => captureSemanticSnapshot(value).fingerprint;
+    expect(fingerprint({ b: 2, a: 1 })).toBe(fingerprint({ a: 1, b: 2 }));
+    expect(
+      new Set(
+        [
+          undefined,
+          null,
+          NaN,
+          Infinity,
+          -Infinity,
+          -0,
+          0,
+          '',
+          [],
+          Array(1),
+          [undefined],
+          {},
+          { a: undefined },
+        ].map(fingerprint),
+      ).size,
+    ).toBe(13);
+    expect(fingerprint(['ab', 'c'])).not.toBe(fingerprint(['a', 'bc']));
+  });
+});
+
+describe('bounded token count reuse', () => {
+  it('reuses text across detached histories and observes content edits and compaction', () => {
+    const encode = vi.fn((text: string) => [...text]);
+    const estimator = new BpeTokenEstimator(encode);
+    const messages = [
+      {
+        role: 'user' as const,
+        content: [{ type: 'text' as const, text: 'old' }],
+        timestamp: 0,
+      },
+    ];
+    expect(estimator.estimateMessages(messages)).toBe(7);
+    expect(estimator.estimateMessages(structuredClone(messages))).toBe(7);
+    expect(encode).toHaveBeenCalledTimes(1);
+    messages[0]!.content[0]!.text = 'replacement';
+    expect(estimator.estimateMessages(messages)).toBe(15);
+    expect(estimator.estimateMessages([])).toBe(0);
+    expect(estimator.estimateMessages([{ role: 'user', content: 'summary', timestamp: 1 }])).toBe(
+      11,
+    );
+    expect(encode).toHaveBeenCalledTimes(3);
+  });
+  it('isolates different estimators and evicts least-recently-used text', () => {
+    const encode = vi.fn((text: string) => [...text]);
+    const estimator = new BpeTokenEstimator(encode);
+    estimator.estimateTextTokens('old');
+    for (let i = 0; i < 2048; i++) estimator.estimateTextTokens(`text ${i}`);
+    encode.mockClear();
+    estimator.estimateTextTokens('old');
+    expect(encode).toHaveBeenCalledTimes(1);
+    expect(new BpeTokenEstimator(() => [0]).estimateTextTokens('old')).toBe(1);
+  });
+  it('bounds retained text independently of entry count', () => {
+    const encode = vi.fn(() => [1]);
+    const estimator = new BpeTokenEstimator(encode);
+    const first = 'a '.repeat(300_000);
+    const second = 'b '.repeat(300_000);
+    estimator.estimateTextTokens(first);
+    estimator.estimateTextTokens(second);
+    estimator.estimateTextTokens(first);
+    expect(encode).toHaveBeenCalledTimes(3);
+  });
+  it('does not cache tokenizer failures', () => {
+    const encode = vi
+      .fn()
+      .mockImplementationOnce(() => {
+        throw new Error('transient');
+      })
+      .mockReturnValue([1]);
+    const estimator = new BpeTokenEstimator(encode);
+    expect(estimator.estimateTextTokens('中文')).toBe(6);
+    expect(estimator.estimateTextTokens('中文')).toBe(1);
+  });
+});
+
+describe('committed history read reuse', () => {
+  it('reuses verified records for indexing while observing external changes and corruption', async () => {
+    const dataDir = await mkdtemp(join(tmpdir(), 'mcode-history-reuse-'));
+    try {
+      const session: SessionRecord = {
+        sessionId: 'synthetic-session',
+        agentName: 'test',
+        workspaceDir: dataDir,
+        runtime: 'pi-agent',
+        sessionType: 'root',
+        sessionKind: 'conversation',
+        archived: false,
+        status: 'idle',
+        createdAtMs: 0,
+        updatedAtMs: 0,
+        historyRelativeDir: utcSessionHistoryRelativeDir('synthetic-session', 0),
+      };
+      const files = createCanonicalHistoryFileAdapter();
+      const strictRead = vi.spyOn(files, 'readActiveStrict');
+      const provider = createSessionSystemCanonicalHistoryProvider({
+        dataDir,
+        sessions: { get: async () => session },
+        files,
+      });
+      await provider.initialize(session.sessionId);
+      strictRead.mockClear();
+      expect((await provider.readActive(session.sessionId)).messages).toEqual([]);
+      expect(strictRead).not.toHaveBeenCalled();
+      const committed = await provider.append({
+        sessionId: session.sessionId,
+        turnId: 'turn-1',
+        reason: 'messageDelta',
+        messages: [{ role: 'user', content: 'first', timestamp: 1 }],
+        operation: { id: 'append-1', kind: 'append' },
+      });
+      expect(committed.messages).toHaveLength(1);
+      expect(strictRead).toHaveBeenCalledTimes(1);
+      const paths = resolveSessionHistoryPaths(dataDir, session);
+      const external = createCanonicalHistoryFileAdapter();
+      await external.replace(paths.messages, [
+        {
+          message_id: 'msg-external-id',
+          turn_id: 'turn-2',
+          message: { role: 'user', content: 'edited', timestamp: 2 },
+        },
+      ]);
+      expect((await provider.readActive(session.sessionId)).messages[0]).toMatchObject({
+        content: 'edited',
+      });
+      await writeFile(paths.messages, '{invalid json}\n');
+      await expect(provider.readActive(session.sessionId)).rejects.toThrow();
+    } finally {
+      await rm(dataDir, { recursive: true, force: true });
+    }
+  });
+  const change: CanonicalHistoryChange = {
+    sessionId: 'synthetic-session',
+    turnId: 'synthetic-turn',
+    reason: 'messageDelta',
+    messages: [],
+    operation: { id: 'append-1', kind: 'append' },
+  };
+  it('uses the provider commit without a second read and still reads fresh on demand', async () => {
+    const committed = { revision: 'r1', messages: [], identityVector: [] };
+    const read = vi.fn(async () => ({
+      revision: 'r2',
+      messages: [],
+      identityVector: [],
+    }));
+    const readActive = vi.fn(async () => committed);
+    const store = new DurableCanonicalHistoryStore({
+      read,
+      readActive,
+      append: async () => committed,
+      replace: async () => committed,
+    });
+    const result = await store.append(change);
+    committed.revision = 'mutated';
+    expect(result.revision).toBe('r1');
+    expect(readActive).not.toHaveBeenCalled();
+    expect((await store.read('synthetic-session')).revision).toBe('r2');
+  });
+  it('retains legacy rereads and rejects invalid commits or write failures', async () => {
+    const readActive = vi.fn(async () => ({
+      revision: 'r1',
+      messages: [],
+      identityVector: [],
+    }));
+    const append = vi.fn<
+      () => Promise<ReturnType<typeof readActive> extends Promise<infer T> ? T | void : never>
+    >(async () => undefined);
+    const store = new DurableCanonicalHistoryStore({
+      read: readActive,
+      readActive,
+      append,
+      replace: async () => undefined,
+    });
+    expect((await store.append(change)).revision).toBe('r1');
+    expect(readActive).toHaveBeenCalledTimes(1);
+    append.mockResolvedValueOnce({
+      revision: '',
+      messages: [],
+      identityVector: [],
+    });
+    await expect(store.append(change)).rejects.toThrow();
+    append.mockRejectedValueOnce(new Error('write failed'));
+    await expect(store.append(change)).rejects.toThrow('write failed');
+    expect(readActive).toHaveBeenCalledTimes(1);
+  });
+});

+ 2 - 1
test/vitest-suites.json

@@ -144,7 +144,8 @@
       "packages/config/test/config-file-permissions.test.ts",
       "packages/config/test/config-file-permissions.test.ts",
       "packages/config/test/config-update-preservation.test.ts",
       "packages/config/test/config-update-preservation.test.ts",
       "packages/agent-modules/context-manager/test/compaction-usage.test.ts",
       "packages/agent-modules/context-manager/test/compaction-usage.test.ts",
-      "packages/local-runtime/test/unit/session-diff-fallback.test.ts"
+      "packages/local-runtime/test/unit/session-diff-fallback.test.ts",
+      "test/history-processing.test.ts"
     ],
     ],
     "status-contract": [
     "status-contract": [
       "packages/tui/test/unit/tui-build-mode-contract.test.ts"
       "packages/tui/test/unit/tui-build-mode-contract.test.ts"