You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by ku...@apache.org on 2026/08/29 13:51:50 UTC

(maka) branch refactor/session-context-ref-reader created (now 1403028d7)

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

likun666661 pushed a change to branch refactor/session-context-ref-reader
in repository https://gitbox.apache.org/repos/asf/maka.git


      at 1403028d7 feat(storage): read durable Session context refs

This branch includes the following new commits:

     new 1403028d7 feat(storage): read durable Session context refs

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



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


(maka) 01/01: feat(storage): read durable Session context refs

Posted by ku...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

likun666661 pushed a commit to branch refactor/session-context-ref-reader
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 1403028d752dbcea9a9add477d8cf0e0c7326e5f
Author: likun666661 <90...@users.noreply.github.com>
AuthorDate: Sat Aug 29 21:51:05 2026 +0800

    feat(storage): read durable Session context refs
    
    Generated-by: OpenAI Codex
---
 packages/core/src/__tests__/runtime-event.test.ts  | 39 ++++++++++++++++
 packages/core/src/context-offload.ts               |  3 ++
 packages/core/src/events.ts                        | 26 ++++++++++-
 .../runtime-host/src/__tests__/protocol.test.ts    | 15 +++++++
 packages/runtime-host/src/protocol/turn.ts         | 10 +++--
 .../src/server/execution-composition.ts            | 19 ++++++++
 .../src/server/execution-model-composition.ts      | 11 +++++
 .../provider-image-overflow-recovery.test.ts       | 35 +++++++++++++--
 .../src/provider-image-overflow-recovery.ts        |  7 +++
 packages/storage/package.json                      |  2 +
 .../src/__tests__/artifact-attachments.test.ts     | 52 ++++++++++++++++++++++
 .../__tests__/storage-writer-composition.test.ts   | 47 +++++++++++++++++++
 packages/storage/src/artifact-attachments.ts       | 10 +++++
 .../storage/src/sqlite-context-offload-store.ts    |  4 +-
 packages/storage/src/storage-writer-composition.ts | 16 +++++++
 15 files changed, 285 insertions(+), 11 deletions(-)

diff --git a/packages/core/src/__tests__/runtime-event.test.ts b/packages/core/src/__tests__/runtime-event.test.ts
index 120d2eac3..f3c69c7d7 100644
--- a/packages/core/src/__tests__/runtime-event.test.ts
+++ b/packages/core/src/__tests__/runtime-event.test.ts
@@ -22,6 +22,7 @@ import assert from 'node:assert/strict';
 import { expect } from './test-helpers.js';
 import {
   decodeMessageContent,
+  isCanonicalStorageRef,
   messageContentsEqual,
   normalizeMessageContent,
   type SessionEvent,
@@ -173,6 +174,33 @@ describe('continuation-start protocol', () => {
 });
 
 describe('RuntimeEvent content variants', () => {
+  test('recognizes canonical durable Session context references', () => {
+    assert.equal(
+      isCanonicalStorageRef({
+        kind: 'session_context',
+        sessionId: 'session-1',
+        refId: 'read-image:owner-1',
+      }),
+      true,
+    );
+    assert.equal(
+      isCanonicalStorageRef({
+        kind: 'session_context',
+        sessionId: 'session-1',
+        refId: '😀'.repeat(512),
+      }),
+      true,
+    );
+    for (const ref of [
+      { kind: 'session_context', sessionId: 'bad/session', refId: 'ref-1' },
+      { kind: 'session_context', sessionId: 'session-1', refId: '' },
+      { kind: 'session_context', sessionId: 'session-1', refId: '😀'.repeat(513) },
+      { kind: 'session_context', sessionId: 'session-1', refId: 'ref-1', extra: true },
+    ]) {
+      assert.equal(isCanonicalStorageRef(ref), false);
+    }
+  });
+
   test('preserves sent inline references as message identity', () => {
     const inlineReferences = [
       { kind: 'skill', value: '/skill:writer', label: 'Writer', start: 8 },
@@ -324,6 +352,17 @@ describe('RuntimeEvent content variants', () => {
         bytes: 1,
         ref: { kind: 'workspace_file' as const, relativePath: 'a.ts' },
       },
+      {
+        kind: 'image' as const,
+        name: 'snapshot.png',
+        mimeType: 'image/png',
+        bytes: 8,
+        ref: {
+          kind: 'session_context' as const,
+          sessionId: 'session-1',
+          refId: 'read-image:owner-1',
+        },
+      },
     ];
     const quotes = [
       { text: 'first', label: 'Assistant', sourceTurnId: 'turn-1' },
diff --git a/packages/core/src/context-offload.ts b/packages/core/src/context-offload.ts
index 77c9e225e..fa0098a3f 100644
--- a/packages/core/src/context-offload.ts
+++ b/packages/core/src/context-offload.ts
@@ -23,6 +23,9 @@ export interface SessionContextRef {
   readonly refId: string;
 }
 
+/** Maximum Unicode code points accepted for durable context-offload identities. */
+export const CONTEXT_OFFLOAD_ID_MAX_CODE_POINTS = 512;
+
 export type ContextOffloadOwner =
   | {
       readonly kind: 'read_image_snapshot';
diff --git a/packages/core/src/events.ts b/packages/core/src/events.ts
index dc9c11c41..218517406 100644
--- a/packages/core/src/events.ts
+++ b/packages/core/src/events.ts
@@ -27,6 +27,7 @@
  */
 
 import * as nodeCrypto from 'node:crypto';
+import { CONTEXT_OFFLOAD_ID_MAX_CODE_POINTS, type SessionContextRef } from './context-offload.js';
 import type {
   AdditionalPermissionRequest,
   PermissionMode,
@@ -74,6 +75,7 @@ type TerminalToolResultStatus = Exclude<ShellRunTerminalStatus, 'orphaned'>;
 // ============================================================================
 
 export type StorageRef =
+  | SessionContextRef
   | { kind: 'session_file'; sessionId: string; relativePath: string }
   | { kind: 'workspace_file'; relativePath: string }
   | { kind: 'external_file'; absolutePath: string };
@@ -154,6 +156,9 @@ const SESSION_FILE_REF_SHAPE = defineObjectShape<Extract<StorageRef, { kind: 'se
   ['kind', 'sessionId', 'relativePath'],
   [],
 );
+const SESSION_CONTEXT_REF_SHAPE = defineObjectShape<
+  Extract<StorageRef, { kind: 'session_context' }>
+>()(['kind', 'sessionId', 'refId'], []);
 const WORKSPACE_FILE_REF_SHAPE = defineObjectShape<
   Extract<StorageRef, { kind: 'workspace_file' }>
 >()(['kind', 'relativePath'], []);
@@ -328,6 +333,13 @@ export function isStorageRef(value: unknown): value is StorageRef {
       typeof value.relativePath === 'string'
     );
   }
+  if (value.kind === 'session_context') {
+    return (
+      hasExactShape(value, SESSION_CONTEXT_REF_SHAPE) &&
+      typeof value.sessionId === 'string' &&
+      typeof value.refId === 'string'
+    );
+  }
   if (value.kind === 'workspace_file') {
     return hasExactShape(value, WORKSPACE_FILE_REF_SHAPE) && typeof value.relativePath === 'string';
   }
@@ -341,9 +353,15 @@ export function isStorageRef(value: unknown): value is StorageRef {
 export function isCanonicalStorageRef(value: unknown): value is StorageRef {
   if (!isStorageRef(value)) return false;
   if (value.kind === 'external_file') return isCanonicalAbsolutePath(value.absolutePath);
-  if (value.kind === 'session_file' && !/^[A-Za-z0-9_-]{1,128}$/.test(value.sessionId)) {
+  if (
+    (value.kind === 'session_file' || value.kind === 'session_context') &&
+    !/^[A-Za-z0-9_-]{1,128}$/.test(value.sessionId)
+  ) {
     return false;
   }
+  if (value.kind === 'session_context') {
+    return value.refId.length > 0 && [...value.refId].length <= CONTEXT_OFFLOAD_ID_MAX_CODE_POINTS;
+  }
   return isCanonicalRelativePath(value.relativePath);
 }
 
@@ -445,6 +463,12 @@ function attachmentRefsEqual(left: AttachmentRef, right: AttachmentRef): boolean
     return false;
   }
   switch (left.ref.kind) {
+    case 'session_context':
+      return (
+        right.ref.kind === 'session_context' &&
+        left.ref.sessionId === right.ref.sessionId &&
+        left.ref.refId === right.ref.refId
+      );
     case 'session_file':
       return (
         right.ref.kind === 'session_file' &&
diff --git a/packages/runtime-host/src/__tests__/protocol.test.ts b/packages/runtime-host/src/__tests__/protocol.test.ts
index 8c4b8e3f2..3ac98974f 100644
--- a/packages/runtime-host/src/__tests__/protocol.test.ts
+++ b/packages/runtime-host/src/__tests__/protocol.test.ts
@@ -1507,6 +1507,18 @@ describe('Runtime Host bootstrap protocol', () => {
         ),
       }),
     );
+    assert.doesNotThrow(() =>
+      submit({
+        text: 'valid context ref',
+        attachments: [
+          attachmentRef({
+            kind: 'session_context',
+            sessionId: 'session-1',
+            refId: 'read-image:owner-1',
+          }),
+        ],
+      }),
+    );
     assert.throws(
       () =>
         submit({
@@ -1527,6 +1539,8 @@ describe('Runtime Host bootstrap protocol', () => {
       { ...attachmentRef({ kind: 'workspace_file', relativePath: 'a.ts' }), mimeType: '' },
       attachmentRef({ kind: 'workspace_file', relativePath: 'a'.repeat(4097) }),
       attachmentRef({ kind: 'session_file', sessionId: 'bad/id', relativePath: 'a.ts' }),
+      attachmentRef({ kind: 'session_context', sessionId: 'session-1', refId: '' }),
+      attachmentRef({ kind: 'session_context', sessionId: 'session-1', refId: 'a'.repeat(513) }),
       attachmentRef({ kind: 'workspace_file', relativePath: '../secret' }),
       attachmentRef({ kind: 'workspace_file', relativePath: 'src//a.ts' }),
       attachmentRef({ kind: 'external_file', absolutePath: 'relative/a.ts' }),
@@ -2007,6 +2021,7 @@ function retractedMessage(text = 'do this next') {
 function attachmentRef(
   ref:
     | { kind: 'session_file'; sessionId: string; relativePath: string }
+    | { kind: 'session_context'; sessionId: string; refId: string }
     | { kind: 'workspace_file'; relativePath: string }
     | { kind: 'external_file'; absolutePath: string },
 ) {
diff --git a/packages/runtime-host/src/protocol/turn.ts b/packages/runtime-host/src/protocol/turn.ts
index 6ce0f6045..8aab204b6 100644
--- a/packages/runtime-host/src/protocol/turn.ts
+++ b/packages/runtime-host/src/protocol/turn.ts
@@ -431,14 +431,16 @@ export function decodeMessageContent(value: unknown, allowEmptyText = false): Me
     if (attachment.bytes > MAX_ATTACHMENT_BYTES) {
       throw invalidProtocolFrame('Invalid AttachmentRef bytes');
     }
-    if (attachment.ref.kind === 'session_file') {
+    if (attachment.ref.kind === 'session_file' || attachment.ref.kind === 'session_context') {
       requireEntityId(attachment.ref.sessionId, 'AttachmentRef sessionId');
     }
-    const path =
+    const identity =
       attachment.ref.kind === 'external_file'
         ? attachment.ref.absolutePath
-        : attachment.ref.relativePath;
-    requireUtf8String(path, 'AttachmentRef path', ATTACHMENT_PATH_MAX_BYTES, false);
+        : attachment.ref.kind === 'session_context'
+          ? attachment.ref.refId
+          : attachment.ref.relativePath;
+    requireUtf8String(identity, 'AttachmentRef identity', ATTACHMENT_PATH_MAX_BYTES, false);
   }
   if ((content.quotes?.length ?? 0) > TURN_MESSAGE_QUOTE_MAX_COUNT) {
     throw invalidProtocolFrame('Invalid Message quotes');
diff --git a/packages/runtime-host/src/server/execution-composition.ts b/packages/runtime-host/src/server/execution-composition.ts
index 246841963..810d898de 100644
--- a/packages/runtime-host/src/server/execution-composition.ts
+++ b/packages/runtime-host/src/server/execution-composition.ts
@@ -18,6 +18,8 @@
  */
 
 import { createHash, randomUUID } from 'node:crypto';
+import { MAX_READ_IMAGE_BYTES } from '@maka/core/attachments';
+import type { ContextOffloadLimits } from '@maka/core/context-offload';
 import { messageContentDigest, normalizeMessageContent } from '@maka/core/events';
 import {
   describeChatConfigurationReason,
@@ -196,6 +198,17 @@ export interface ExecutionRuntimeHostComposition extends RuntimeHostComposition
   readonly workspaceExecution: RuntimeHostWorkspaceExecutionComposition;
 }
 
+const CONTEXT_OFFLOAD_READER_LIMITS: ContextOffloadLimits = Object.freeze({
+  ownerMaxBytes: Object.freeze({
+    read_image_snapshot: MAX_READ_IMAGE_BYTES,
+    tool_result_archive: 0,
+  }),
+  // This expand slice opens only the reader path. Zero quotas make accidental
+  // non-empty puts fail closed until the writer/lifecycle cutover lands.
+  sessionLogicalBytes: 0,
+  workspacePhysicalBytes: 0,
+});
+
 export interface CreateExecutionRuntimeHostCompositionOptions {
   readonly bootstrapRuntimePolicy?: boolean;
   readonly skillHomeDirectory?: string;
@@ -222,6 +235,7 @@ export async function createExecutionRuntimeHostComposition(
   dependencies: ExecutionRuntimeHostCompositionDependencies = {},
 ): Promise<ExecutionRuntimeHostComposition> {
   const storage = await openStorageWriterComposition(context.owner.lease, {
+    contextOffloadLimits: CONTEXT_OFFLOAD_READER_LIMITS,
     afterRuntimePolicyOpened: async (stores) => {
       if (options.bootstrapRuntimePolicy !== false) {
         await ensureBootstrapRuntimePolicy({
@@ -258,6 +272,10 @@ export async function createExecutionRuntimeHostComposition(
     const longTermMemoryStore = storage.longTermMemory;
     const taskLedgerStore = storage.taskLedger;
     const openedArtifactStore = storage.artifacts;
+    const openedContextOffloadStore = storage.contextOffload;
+    if (!openedContextOffloadStore) {
+      throw new Error('Runtime Host context-offload reader authority is unavailable');
+    }
     const openedUsageStores = storage.usage;
     const openedShellRunStore = storage.shellRuns;
     const worktreeChildExecutor = createGitWorktreeChildExecutor({
@@ -672,6 +690,7 @@ export async function createExecutionRuntimeHostComposition(
               ? {}
               : { memoryExtraction }),
             artifacts: openedArtifactStore,
+            contextOffload: openedContextOffloadStore,
             executionArtifacts,
             usage: openedUsageStores,
             childAgents: bindHostChildAgentBackend(
diff --git a/packages/runtime-host/src/server/execution-model-composition.ts b/packages/runtime-host/src/server/execution-model-composition.ts
index 0c450b39c..4dd698761 100644
--- a/packages/runtime-host/src/server/execution-model-composition.ts
+++ b/packages/runtime-host/src/server/execution-model-composition.ts
@@ -49,6 +49,8 @@ import {
   persistProviderRequestCaptureArtifact,
   type InteractiveArtifactStoreWriter,
 } from '@maka/storage/artifact-stores';
+import type { InteractiveContextOffloadWriter } from '@maka/storage/context-offload-store';
+import { createReadImageSnapshotStore } from '@maka/storage/read-image-snapshot-store';
 import type { RuntimePolicyStoresWriter } from '@maka/storage/runtime-policy-stores';
 import type { InteractiveUsageStoresWriter } from '@maka/storage/usage-stores';
 import {
@@ -70,6 +72,7 @@ export interface HostAiSdkBackendInput {
   readonly sandboxDiagnostics: SandboxDiagnosticsProvider;
   readonly memoryExtraction?: HostMemoryExtractionCoordinator;
   readonly artifacts: HostExecutionArtifactAuthority;
+  readonly contextOffload?: InteractiveContextOffloadWriter;
   readonly executionArtifacts: HostExecutionArtifactServices;
   readonly usage: HostExecutionUsageAuthority;
   readonly requestDrain: () => void;
@@ -381,6 +384,14 @@ export async function createHostAiSdkBackend(input: HostAiSdkBackendInput): Prom
         readAttachmentBytes: createAttachmentByteReader({
           artifactStore: input.artifacts,
           sessionId: input.context.sessionId,
+          ...(input.contextOffload
+            ? {
+                readImageSnapshots: createReadImageSnapshotStore(
+                  input.contextOffload,
+                  input.context.sessionId,
+                ),
+              }
+            : {}),
         }),
         recordToolArtifacts: input.executionArtifacts.recordToolArtifacts,
         toolResultArchive: input.executionArtifacts.toolResultArchive,
diff --git a/packages/runtime/src/__tests__/provider-image-overflow-recovery.test.ts b/packages/runtime/src/__tests__/provider-image-overflow-recovery.test.ts
index cf03db629..a58861f15 100644
--- a/packages/runtime/src/__tests__/provider-image-overflow-recovery.test.ts
+++ b/packages/runtime/src/__tests__/provider-image-overflow-recovery.test.ts
@@ -21,13 +21,14 @@ import assert from 'node:assert/strict';
 import { describe, test } from 'node:test';
 
 import type { RuntimeEvent } from '@maka/core/runtime-event';
+import type { StorageRef } from '@maka/core/events';
 import type { ModelMessage } from '../model-protocol.js';
 import {
   collectHistoricalImageToolResults,
   omitHistoricalImageToolResults,
 } from '../provider-image-overflow-recovery.js';
 
-function imageResultEvent(toolCallId: string, relativePath: string): RuntimeEvent {
+function imageResultEvent(toolCallId: string, ref: StorageRef): RuntimeEvent {
   return {
     id: `event-${toolCallId}`,
     sessionId: 'session-1',
@@ -46,7 +47,7 @@ function imageResultEvent(toolCallId: string, relativePath: string): RuntimeEven
       result: {
         kind: 'image',
         mimeType: 'image/png',
-        ref: { kind: 'session_file', sessionId: 'session-1', relativePath },
+        ref,
       },
       isError: false,
     },
@@ -84,7 +85,13 @@ function prompt(messages: readonly ModelMessage[]): string {
 
 describe('provider image overflow recovery projection', () => {
   test('omits only eligible historical tool-result images and names their artifact', () => {
-    const priorEvents = [imageResultEvent('prior-image-call', 'screenshots/screenshot.png')];
+    const priorEvents = [
+      imageResultEvent('prior-image-call', {
+        kind: 'session_file',
+        sessionId: 'session-1',
+        relativePath: 'screenshots/screenshot.png',
+      }),
+    ];
     const messages = [
       {
         role: 'user',
@@ -111,7 +118,11 @@ describe('provider image overflow recovery projection', () => {
     const messages = [toolImageMessage('prior-image-call', 'PRIOR_IMAGE')];
     const original = structuredClone(messages);
     const eligible = collectHistoricalImageToolResults([
-      imageResultEvent('prior-image-call', 'screenshot.png'),
+      imageResultEvent('prior-image-call', {
+        kind: 'session_file',
+        sessionId: 'session-1',
+        relativePath: 'screenshot.png',
+      }),
     ]);
 
     const first = omitHistoricalImageToolResults(messages, eligible);
@@ -124,4 +135,20 @@ describe('provider image overflow recovery projection', () => {
     assert.equal(second.omittedParts, 0);
     assert.deepEqual(second.messages, first.messages);
   });
+
+  test('uses the durable context identity when an omitted image has no file path', () => {
+    const eligible = collectHistoricalImageToolResults([
+      imageResultEvent('prior-image-call', {
+        kind: 'session_context',
+        sessionId: 'session-1',
+        refId: 'read-image:owner-1',
+      }),
+    ]);
+    const result = omitHistoricalImageToolResults(
+      [toolImageMessage('prior-image-call', 'PRIOR_IMAGE')],
+      eligible,
+    );
+
+    assert.match(prompt(result.messages), /read-image:owner-1/);
+  });
 });
diff --git a/packages/runtime/src/provider-image-overflow-recovery.ts b/packages/runtime/src/provider-image-overflow-recovery.ts
index ad31df5dd..71a90e5e6 100644
--- a/packages/runtime/src/provider-image-overflow-recovery.ts
+++ b/packages/runtime/src/provider-image-overflow-recovery.ts
@@ -46,6 +46,13 @@ function storageRefLabel(value: unknown): string | undefined {
   ) {
     return value.relativePath;
   }
+  if (
+    value.kind === 'session_context' &&
+    typeof value.refId === 'string' &&
+    value.refId.length > 0
+  ) {
+    return value.refId;
+  }
   if (
     value.kind === 'external_file' &&
     typeof value.absolutePath === 'string' &&
diff --git a/packages/storage/package.json b/packages/storage/package.json
index 2c4bc7853..cbcbaddc1 100644
--- a/packages/storage/package.json
+++ b/packages/storage/package.json
@@ -10,6 +10,7 @@
     "./agent-run-store": "./dist/agent-run-store.js",
     "./artifact-stores": "./dist/artifact-stores.js",
     "./config-transfer": "./dist/config-transfer.js",
+    "./context-offload-store": "./dist/context-offload-store.js",
     "./credential-store": "./dist/credential-store.js",
     "./daily-review-authority": "./dist/daily-review-authority.js",
     "./deep-research-authority": "./dist/deep-research-authority.js",
@@ -36,6 +37,7 @@
     "./project-catalog": "./dist/project-catalog.js",
     "./project-catalog-authority": "./dist/project-catalog-authority.js",
     "./root-authority": "./dist/root-authority.js",
+    "./read-image-snapshot-store": "./dist/read-image-snapshot-store.js",
     "./runtime-event-persistence": "./dist/runtime-event-persistence.js",
     "./runtime-policy-stores": "./dist/runtime-policy-stores.js",
     "./scheduled-task-store": "./dist/scheduled-task-store.js",
diff --git a/packages/storage/src/__tests__/artifact-attachments.test.ts b/packages/storage/src/__tests__/artifact-attachments.test.ts
index 7a23eadf4..fd0ba6f12 100644
--- a/packages/storage/src/__tests__/artifact-attachments.test.ts
+++ b/packages/storage/src/__tests__/artifact-attachments.test.ts
@@ -23,6 +23,7 @@ import { tmpdir } from 'node:os';
 import { join } from 'node:path';
 import { describe, test } from 'node:test';
 import { MAX_ATTACHMENT_BYTES } from '@maka/core/attachments';
+import type { ReadImageSnapshotStore } from '@maka/core/context-offload';
 import { type StorageRef } from '@maka/core/events';
 import {
   createArtifactAttachmentResourceReader,
@@ -124,6 +125,53 @@ describe('artifact attachment authority', () => {
     });
   });
 
+  test('routes durable context refs through the Session-bound snapshot reader', async () => {
+    await withStore(async (store) => {
+      const reads: string[] = [];
+      const readImageSnapshots: ReadImageSnapshotStore = {
+        async snapshot() {
+          throw new Error('not used by the reader path');
+        },
+        async read(ref) {
+          reads.push(ref.refId);
+          if (ref.refId === 'missing') return { ok: false, reason: 'not_found' };
+          return {
+            ok: true,
+            record: {
+              refId: ref.refId,
+              sessionId: ref.sessionId,
+              owner: { kind: 'read_image_snapshot', ownerId: 'owner-1' },
+              blobId: 'a'.repeat(64),
+              sizeBytes: png.byteLength,
+              mediaType: 'image/png',
+              createdAt: 1,
+            },
+            bytes: png,
+          };
+        },
+      };
+      const reader = createAttachmentByteReader({
+        artifactStore: store,
+        sessionId: 'session-1',
+        readImageSnapshots,
+      });
+
+      assert.deepEqual(await reader(sessionContextRef('ref-1')), {
+        ok: true,
+        bytes: png,
+      });
+      assert.deepEqual(await reader(sessionContextRef('missing')), {
+        ok: false,
+        reason: 'not_found',
+      });
+      assert.deepEqual(await reader(sessionContextRef('ref-2', 'other-session')), {
+        ok: false,
+        reason: 'session_mismatch',
+      });
+      assert.deepEqual(reads, ['ref-1', 'missing']);
+    });
+  });
+
   test('passes through real store not-found and unsupported-mime failures', async () => {
     await withStore(async (store) => {
       const reader = createAttachmentByteReader({
@@ -172,6 +220,10 @@ function sessionFileRef(relativePath: string, sessionId = 'session-1'): StorageR
   return { kind: 'session_file', sessionId, relativePath };
 }
 
+function sessionContextRef(refId: string, sessionId = 'session-1'): StorageRef {
+  return { kind: 'session_context', sessionId, refId };
+}
+
 async function withStore(
   run: (store: ReturnType<typeof createArtifactStore>) => Promise<void>,
 ): Promise<void> {
diff --git a/packages/storage/src/__tests__/storage-writer-composition.test.ts b/packages/storage/src/__tests__/storage-writer-composition.test.ts
index 4c65607f5..e242eede0 100644
--- a/packages/storage/src/__tests__/storage-writer-composition.test.ts
+++ b/packages/storage/src/__tests__/storage-writer-composition.test.ts
@@ -22,6 +22,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
 import { tmpdir } from 'node:os';
 import { join } from 'node:path';
 import { after, test } from 'node:test';
+import type { ContextOffloadLimits } from '@maka/core/context-offload';
 import { acquireOperationalStateDatabase } from '../operational-state-store.js';
 import { openStorageWriterComposition } from '../storage-writer-composition.js';
 import {
@@ -38,6 +39,12 @@ import {
 // temporary root's removal leaves it behind; reclaim the recorded rootIds here.
 after(removeTrackedControlDirectories);
 
+const contextOffloadLimits: ContextOffloadLimits = Object.freeze({
+  ownerMaxBytes: Object.freeze({ read_image_snapshot: 1024, tool_result_archive: 1024 }),
+  sessionLogicalBytes: 4096,
+  workspacePhysicalBytes: 4096,
+});
+
 test('storage writer composition rejects reuse until close completes', async () => {
   const root = await mkdtemp(join(tmpdir(), 'maka-storage-composition-'));
   try {
@@ -88,6 +95,46 @@ test('opening a second storage writer composition creates a usable lifecycle', a
   }
 });
 
+test('context-offload authority is optional and participates in composition close', async () => {
+  const root = await mkdtemp(join(tmpdir(), 'maka-storage-context-composition-'));
+  try {
+    const capability = trackControlDirectory(
+      await resolveStorageRoot({ path: root, kind: 'interactive' }),
+    );
+    const owner = await tryAcquireInteractiveRootOwner(capability);
+    assert.ok(owner);
+    try {
+      const withoutContext = await openStorageWriterComposition(owner.lease);
+      assert.equal(withoutContext.contextOffload, undefined);
+      await withoutContext.close();
+
+      const withContext = await openStorageWriterComposition(owner.lease, {
+        contextOffloadLimits,
+      });
+      assert.ok(withContext.contextOffload);
+      assert.deepEqual(
+        await withContext.contextOffload.read({
+          sessionId: 'session-1',
+          refId: 'missing',
+          maxBytes: 1024,
+        }),
+        { ok: false, reason: 'not_found' },
+      );
+      await withContext.close();
+
+      const reopened = await openStorageWriterComposition(owner.lease, {
+        contextOffloadLimits,
+      });
+      assert.ok(reopened.contextOffload);
+      await reopened.close();
+    } finally {
+      await owner.close();
+    }
+  } finally {
+    await rm(root, { recursive: true, force: true });
+  }
+});
+
 test('a failed close keeps the lease unavailable', async () => {
   const root = await mkdtemp(join(tmpdir(), 'maka-storage-composition-close-failure-'));
   try {
diff --git a/packages/storage/src/artifact-attachments.ts b/packages/storage/src/artifact-attachments.ts
index 075ba28da..4b4cf3514 100644
--- a/packages/storage/src/artifact-attachments.ts
+++ b/packages/storage/src/artifact-attachments.ts
@@ -24,6 +24,7 @@ import {
   type AttachmentByteReader,
 } from '@maka/core/attachments';
 import { type StorageRef, type ToolResultContent } from '@maka/core/events';
+import type { ReadImageSnapshotStore } from '@maka/core/context-offload';
 import type {
   ArtifactAuthorityStore,
   ArtifactStore,
@@ -86,10 +87,19 @@ export function createArtifactAttachmentResourceReader(input: {
 export function createAttachmentByteReader(input: {
   artifactStore: DurableArtifactAttachmentReader;
   sessionId: string;
+  readImageSnapshots?: ReadImageSnapshotStore;
   maxBytes?: number;
 }): AttachmentByteReader {
   const maxBytes = input.maxBytes ?? MAX_ATTACHMENT_BYTES;
   return async (ref) => {
+    if (ref.kind === 'session_context') {
+      if (ref.sessionId !== input.sessionId) return { ok: false, reason: 'session_mismatch' };
+      if (!input.readImageSnapshots) return { ok: false, reason: 'unsupported_ref_kind' };
+      const result = await input.readImageSnapshots.read(ref);
+      return result.ok
+        ? { ok: true, bytes: new Uint8Array(result.bytes) }
+        : { ok: false, reason: result.reason };
+    }
     if (ref.kind !== 'session_file') return { ok: false, reason: 'unsupported_ref_kind' };
     if (ref.sessionId !== input.sessionId) return { ok: false, reason: 'session_mismatch' };
     const result = await input.artifactStore.readDurableAttachmentBinary({
diff --git a/packages/storage/src/sqlite-context-offload-store.ts b/packages/storage/src/sqlite-context-offload-store.ts
index 5b96a7514..e8c2e4e47 100644
--- a/packages/storage/src/sqlite-context-offload-store.ts
+++ b/packages/storage/src/sqlite-context-offload-store.ts
@@ -24,6 +24,7 @@ import { createRequire } from 'node:module';
 import { dirname, isAbsolute, join, relative, sep } from 'node:path';
 import type { DatabaseSync } from 'node:sqlite';
 import {
+  CONTEXT_OFFLOAD_ID_MAX_CODE_POINTS,
   type ContextOffloadCopyResult,
   type ContextOffloadGarbageCollectionResult,
   type ContextOffloadLimits,
@@ -46,7 +47,6 @@ import {
   syncFile,
 } from './stable-storage.js';
 
-const MAX_ID_CODE_POINTS = 512;
 const MAX_MEDIA_TYPE_CODE_POINTS = 256;
 const SHA256_PATTERN = /^[0-9a-f]{64}$/;
 const MANAGED_FILE_LOCATOR_PATTERN = /^sha256\/([0-9a-f]{2})\/([0-9a-f]{64})$/;
@@ -1368,7 +1368,7 @@ function isOwnerKind(value: unknown): value is ContextOffloadOwner['kind'] {
 }
 
 function assertBoundedIdentity(value: string, label: string): void {
-  assertBoundedText(value, MAX_ID_CODE_POINTS, label);
+  assertBoundedText(value, CONTEXT_OFFLOAD_ID_MAX_CODE_POINTS, label);
 }
 
 function assertBoundedText(value: string, maxCodePoints: number, label: string): void {
diff --git a/packages/storage/src/storage-writer-composition.ts b/packages/storage/src/storage-writer-composition.ts
index 5261127c7..95cbae169 100644
--- a/packages/storage/src/storage-writer-composition.ts
+++ b/packages/storage/src/storage-writer-composition.ts
@@ -18,6 +18,8 @@
  */
 
 import { openInteractiveArtifactStoreForWrite } from './artifact-stores.js';
+import type { ContextOffloadLimits } from '@maka/core/context-offload';
+import { openInteractiveContextOffloadStoreForWrite } from './context-offload-store.js';
 import { openInteractiveDailyReviewAuthorityForWrite } from './daily-review-authority.js';
 import { openInteractiveDeepResearchStoreForWrite } from './deep-research-authority.js';
 import { openInteractiveExecutionStoresForWrite } from './execution-stores.js';
@@ -38,6 +40,8 @@ export interface OpenStorageWriterCompositionOptions {
   afterRuntimePolicyOpened?: (
     stores: Awaited<ReturnType<typeof openInteractiveRuntimePolicyStoresForWrite>>,
   ) => void | Promise<void>;
+  /** Opens the context-offload authority only when a reader or writer is composed. */
+  contextOffloadLimits?: ContextOffloadLimits;
 }
 
 export interface StorageWriterComposition {
@@ -53,6 +57,7 @@ export interface StorageWriterComposition {
   readonly longTermMemory: Awaited<ReturnType<typeof openInteractiveLongTermMemoryStoreForWrite>>;
   readonly taskLedger: Awaited<ReturnType<typeof openInteractiveTaskLedgerStoreForWrite>>;
   readonly artifacts: Awaited<ReturnType<typeof openInteractiveArtifactStoreForWrite>>;
+  readonly contextOffload?: Awaited<ReturnType<typeof openInteractiveContextOffloadStoreForWrite>>;
   readonly usage: Awaited<ReturnType<typeof openInteractiveUsageStoresForWrite>>;
   readonly shellRuns: Awaited<ReturnType<typeof openInteractiveShellRunStoreForWrite>>;
   close(): Promise<void>;
@@ -153,6 +158,16 @@ async function createComposition(
     () => openInteractiveArtifactStoreForWrite(lease),
     closeWriter,
   );
+  const contextOffloadLimits = options.contextOffloadLimits;
+  const contextOffload = contextOffloadLimits
+    ? await openWriter(
+        () =>
+          openInteractiveContextOffloadStoreForWrite(lease, {
+            limits: contextOffloadLimits,
+          }),
+        closeWriter,
+      )
+    : undefined;
   const usage = await openWriter(() => openInteractiveUsageStoresForWrite(lease), closeWriter);
   const shellRuns = await openWriter(
     () => openInteractiveShellRunStoreForWrite(lease),
@@ -171,6 +186,7 @@ async function createComposition(
     longTermMemory,
     taskLedger,
     artifacts,
+    ...(contextOffload ? { contextOffload } : {}),
     usage,
     shellRuns,
     close,


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