You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by mi...@apache.org on 2026/09/09 08:44:28 UTC

(maka) branch codex/local-runtime-persistence-contracts created (now 4afc270d3c)

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

MicroGery pushed a change to branch codex/local-runtime-persistence-contracts
in repository https://gitbox.apache.org/repos/asf/maka.git


      at 4afc270d3c refactor(storage): isolate local persistence contracts

This branch includes the following new commits:

     new 4afc270d3c refactor(storage): isolate local persistence contracts

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: refactor(storage): isolate local persistence contracts

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

MicroGery pushed a commit to branch codex/local-runtime-persistence-contracts
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 4afc270d3cf17392ca42bcf4b50de536fc0341f9
Author: MicroGrey <ch...@outlook.com>
AuthorDate: Wed Sep 9 16:44:07 2026 +0800

    refactor(storage): isolate local persistence contracts
    
    Preserve existing leased SQLite domain transactions and verify WorkHub recovery across commit-before-dispatch process death. Fix copied attachment validation and durable replay identity.
    
    Generated-by: OpenAI Codex
---
 docs/architecture/runtime-host-architecture.md     |  31 ++
 .../runtime-host-architecture.zh-CN.md             |  31 ++
 .../fixtures/workhub-assignment-crash-host.ts      |  86 ++++
 .../workhub-assignment-crash-recovery.test.ts      | 401 ++++++++++++++++
 .../src/server/external-session-coordinator.ts     |   2 +-
 .../src/server/session-catalog-coordinator.ts      |   2 +-
 .../src/server/workhub-coordination-coordinator.ts |   4 +-
 .../src/__tests__/fixtures/workhub-assignment.ts   |  92 ++++
 .../__tests__/local-persistence-contract.test.ts   | 263 +++++++++++
 .../local-persistence-dependencies.test.ts         |  94 ++++
 .../__tests__/workhub-message-assignment.test.ts   |  71 +--
 packages/storage/src/execution-stores.ts           |  12 +-
 .../storage/src/runtime-event-store-contract.ts    |  67 +++
 packages/storage/src/session-store-contract.ts     | 516 +++++++++++++++++++++
 packages/storage/src/session-store.ts              | 479 +++----------------
 packages/storage/src/sqlite-runtime-store.ts       |  61 +--
 .../storage/src/sqlite-session-metadata-store.ts   | 108 ++---
 17 files changed, 1735 insertions(+), 585 deletions(-)

diff --git a/docs/architecture/runtime-host-architecture.md b/docs/architecture/runtime-host-architecture.md
index d6158e7caf..7a80ff8c98 100644
--- a/docs/architecture/runtime-host-architecture.md
+++ b/docs/architecture/runtime-host-architecture.md
@@ -75,6 +75,37 @@ The execution names also describe different scopes:
 | Run | The durable execution entity that performs model and tool work for a Turn |
 | Root execution | The one top-level execution currently admitted for a Session |
 
+## Local persistence boundary
+
+Local Runtime integration follows the separation discussed in [#2370](https://github.com/apache/maka/issues/2370) and [#4666](https://github.com/apache/maka/discussions/4666), without replacing the existing live-state authority.
+
+The Host already opens `storage-writer-composition.ts` with its root lease and injects the owned writers. `execution-stores.ts` preserves lease validation, branded facades, and close/drain behavior. `session-store-contract.ts` now defines Session operations, DTOs and domain errors independently of the SQLite adapter; `runtime-event-store-contract.ts` does the same for the Tool transaction DTOs and Session event positions. Existing exports remain compatible. This is not a second facade or [...]
+
+| Capability | Contract and consumers | Commit boundary retained |
+|---|---|---|
+| Session metadata/catalog | `ExecutionSessionWriter`; Session Catalog and External Session coordinators | Stable create identity, version-checked metadata/lifecycle updates |
+| Canonical history | Session snapshot queries, `RuntimeTranscriptQueries`; Session Continuity and Runtime | Durable event append positions; bounded read projections are not new facts |
+| Message and Root Turn admission | `MessageAdmissionStore`, `ExecutionAgentRunWriter`; Message and Root Turn coordinators | Exact input/identity admission, source-message receipts, idempotent replay |
+| Tool execution | `ExecutionRuntimeEventWriter`; Runtime Tool commit sink | T1 prepared/dispatch facts and journal together; T2 outcome and journal together |
+| Continuation | `RuntimeContinuationAuthorityStore`; Runtime recovery and Root Turn coordinator | Immutable source-bound claim and dedicated continuation-start commit |
+| WorkHub delegation | `assignWorkHubMessage`; WorkHub coordinator through Host composition | Optional target creation/claim, target pending admission, coordination linkage and optional supersession in one transaction |
+
+Consumers retain their existing narrow `Pick<...>` dependencies where appropriate. No SQL handle or generic transaction callback is exposed to a coordinator. Goal, Memory, Artifact and other domains keep their existing contracts and lifecycle.
+
+### WorkHub as a compatibility test
+
+The process-crash test submits `workhub.coordination.act` through a real Host connection. A fixture-only barrier pauses after the actual SQLite assignment transaction commits and before its result returns to the Host. The parent kills that process without draining it, verifies a still-pending target message and no target Root admission, and starts a fresh Host with a fresh lease. Production recovery must expose the same delegation, execute the same target message, and converge on the sam [...]
+
+Both `create_new` and `delegate_existing` are tested with and without an attachment. The Host copies selected artifacts before assignment; the transaction preserves the coordination-owned source references and target-owned admission references with matching attachment metadata. A source attachment change cannot reuse the original action identity. A separate transaction-abort test checks all-or-none rollback after target admission insertion.
+
+This proves recovery in the specified **before-first-target-dispatch** window, not exactly-once arbitrary external effects. Stop, replacement and continuation retain their existing semantics and regression coverage.
+
+### What this boundary does not change
+
+SQLite and existing local files remain authoritative for live commits and ordinary in-place restart. No schema migration, new checkpoint I/O, or per-message packing is introduced here. The Repository Head from #2370 identifies a published checkpoint; it is not the metadata revision or event ordinal and must not overwrite newer live commits.
+
+Host checkpoint publication and restricted exact-checkpoint restore are follow-up changes. In particular, independently restored Session checkpoints do not establish a consistent cross-Session WorkHub assignment. The initial local boundary work neither activates such a restore nor redesigns WorkHub, Memory retrieval, or cross-Host ownership.
+
 ## One Turn through the system
 
 ```mermaid
diff --git a/docs/architecture/runtime-host-architecture.zh-CN.md b/docs/architecture/runtime-host-architecture.zh-CN.md
index 5c803d6d80..4dbdca27b2 100644
--- a/docs/architecture/runtime-host-architecture.zh-CN.md
+++ b/docs/architecture/runtime-host-architecture.zh-CN.md
@@ -74,6 +74,37 @@ Durable Stores 是 recovery 的事实来源。下文所说的 **canonical state*
 | Run | 为一次 Turn 执行 model 与 tool work 的持久实体 |
 | Root execution | 一个 Session 当前唯一被 admit 的顶层 execution |
 
+## 本地持久化边界
+
+本地 Runtime 接入遵循 [#2370](https://github.com/apache/maka/issues/2370) 和 [#4666](https://github.com/apache/maka/discussions/4666) 讨论的职责分离,但不替换已有 live-state authority。
+
+Host 已经用 root lease 打开 `storage-writer-composition.ts`,并注入由其持有的 writers。`execution-stores.ts` 保留 lease 校验、品牌鉴权及 close/drain 行为。`session-store-contract.ts` 将 Session 操作、DTO 和领域错误从 SQLite adapter 中分离;`runtime-event-store-contract.ts` 则定义 Tool 事务 DTO 与 Session 事件位置。旧导出保持兼容。这不是第二套 facade,也不表示已有 remote live-state adapter。
+
+| 能力 | 契约与消费者 | 保留的提交边界 |
+|---|---|---|
+| Session metadata/catalog | `ExecutionSessionWriter`;Session Catalog、External Session coordinators | 稳定创建身份、带版本校验的元数据与生命周期更新 |
+| Canonical history | Session snapshot queries、`RuntimeTranscriptQueries`;Session Continuity、Runtime | 持久事件追加位置;有界读取投影不成为第二份事实 |
+| Message 与 Root Turn admission | `MessageAdmissionStore`、`ExecutionAgentRunWriter`;Message、Root Turn coordinators | 绑定确切输入和身份的准入、source-message receipts、幂等重试 |
+| Tool execution | `ExecutionRuntimeEventWriter`;Runtime Tool commit sink | T1 prepared/dispatch 事实与 journal 一起提交;T2 outcome 与 journal 一起提交 |
+| Continuation | `RuntimeContinuationAuthorityStore`;Runtime recovery、Root Turn coordinator | 绑定不可变 source 的 claim,以及专用 continuation-start 提交 |
+| WorkHub 委派 | `assignWorkHubMessage`;WorkHub coordinator 经 Host composition 调用 | 可选目标创建/claim、目标 pending admission、协调记录与可选 supersession 在同一事务提交 |
+
+消费者按需保留已有的窄 `Pick<...>` 依赖,不向 coordinator 暴露 SQL handle 或通用 transaction callback。Goal、Memory、Artifact 等领域继续使用已有契约与生命周期。
+
+### 用 WorkHub 验证兼容性
+
+进程崩溃测试通过真实 Host 连接提交 `workhub.coordination.act`。仅存在于 fixture 的屏障在真实 SQLite 委派事务提交之后、结果返回 Host 之前暂停。父进程不做 drain,直接强杀子进程;确认目标消息仍待执行、目标 Root 尚未准入后,再启动持有新 lease 的 Host。正式恢复流程必须显示同一委派、执行同一目标消息,并在 Client 重试时收敛到原身份。
+
+`create_new` 和 `delegate_existing` 都覆盖带附件与不带附件的情况。Host 在委派之前复制选中的 Artifact;事务保留协调 Session 的源引用及目标 Session 的 admission 引用,并校验附件元数据对应。改变源附件不能复用原 action 身份。另有事务中断测试在目标 admission 插入之后验证整体回滚。
+
+这只证明指定的**目标首次 dispatch 之前**的恢复窗口,不承诺任意外部副作用 exactly once。Stop、replacement、continuation 保持原语义,并继续回归验证。
+
+### 这条边界不改变什么
+
+SQLite 与现有本地文件仍是 live commit 和普通原地重启的权威。这里不引入 schema migration、checkpoint I/O 或逐消息打包。#2370 的 Repository Head 表示已发布 checkpoint,不是 metadata revision 或 event ordinal,更不能覆盖较新的 live commit。
+
+Host checkpoint 发布和受限的精确 checkpoint 恢复属于后续修改。尤其是,分别恢复各 Session 的 checkpoint,并不能建立一致的跨 Session WorkHub 委派。当前边界整理不启用这种恢复,也不重做 WorkHub、Memory 检索或跨 Host ownership。
+
 ## 一次 Turn 如何穿过系统
 
 ```mermaid
diff --git a/packages/runtime-host/src/__tests__/fixtures/workhub-assignment-crash-host.ts b/packages/runtime-host/src/__tests__/fixtures/workhub-assignment-crash-host.ts
new file mode 100644
index 0000000000..7d5daf88ac
--- /dev/null
+++ b/packages/runtime-host/src/__tests__/fixtures/workhub-assignment-crash-host.ts
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+import type { BackendSendInput } from '@maka/core/backend-types';
+import type { SessionEvent } from '@maka/core/events';
+import { FakeBackend } from '@maka/runtime/test-only/fake-backend';
+import { SqliteSessionMetadataStore } from '@maka/storage/sqlite-session-metadata-store';
+import { startExecutionRuntimeHostCandidate } from '../../server/execution-candidate.js';
+import { createExecutionRuntimeHostComposition } from '../../server/execution-composition.js';
+import { runRuntimeHostProcessLifecycle } from '../../server/process-lifecycle.js';
+
+const [rootPath, expectedRootId, mode] = process.argv.slice(2);
+if (!rootPath || !expectedRootId || !['crash', 'recover'].includes(mode ?? '')) {
+  throw new Error('usage: workhub-assignment-crash-host <root> <root-id> <crash|recover>');
+}
+
+// Test-only barrier AFTER the real SQLite transaction, BEFORE its result reaches
+// the leased facade and the Host can consume the target admission. No substitute
+// store, production failpoint, graceful drain, or in-memory recovery is involved.
+if (mode === 'crash') {
+  const assign = SqliteSessionMetadataStore.prototype.assignWorkHubMessage;
+  SqliteSessionMetadataStore.prototype.assignWorkHubMessage = async function (request) {
+    const result = await assign.call(this, request);
+    process.send?.({
+      type: 'assignment_committed',
+      assignment: result.assignment,
+      admission: request.admission,
+      targetCreated: result.targetCreated,
+    });
+    await new Promise<never>(() => undefined);
+    return result;
+  };
+}
+
+class ObservedBackend extends FakeBackend {
+  override async *send(input: BackendSendInput): AsyncIterable<SessionEvent> {
+    process.send?.({
+      type: 'dispatch',
+      sessionId: this.sessionId,
+      turnId: input.turnId,
+      text: input.text,
+      attachments: input.attachments ?? [],
+    });
+    yield* super.send(input);
+  }
+}
+
+const candidate = await startExecutionRuntimeHostCandidate(
+  { rootPath, expectedRootId, idleGraceMs: 60_000 },
+  {
+    createComposition: (context, options) =>
+      createExecutionRuntimeHostComposition(context, options, {
+        primaryBackendFactory: (context) => new ObservedBackend(context),
+      }),
+  },
+);
+if (candidate.kind === 'loser') throw new Error('Fixture failed to acquire Host ownership');
+process.on('message', (message) => {
+  if (message && typeof message === 'object' && 'type' in message && message.type === 'shutdown') {
+    void candidate.host.close();
+  }
+});
+try {
+  await runRuntimeHostProcessLifecycle(candidate.host, {
+    closeOnDisconnect: true,
+    onReady: () => process.send?.({ type: 'ready', hostEpoch: candidate.host.hostEpoch }),
+  });
+} finally {
+  if (process.connected) process.disconnect?.();
+}
diff --git a/packages/runtime-host/src/__tests__/workhub-assignment-crash-recovery.test.ts b/packages/runtime-host/src/__tests__/workhub-assignment-crash-recovery.test.ts
new file mode 100644
index 0000000000..22169c09da
--- /dev/null
+++ b/packages/runtime-host/src/__tests__/workhub-assignment-crash-recovery.test.ts
@@ -0,0 +1,401 @@
+/*
+ * 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.
+ */
+
+import assert from 'node:assert/strict';
+import { fork, type ChildProcess } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { withTimeout } from '@maka/core/test-only/async-primitives';
+import type { AttachmentRef } from '@maka/core/events';
+import {
+  WORKHUB_COORDINATION_SESSION_ID,
+  type WorkHubDelegationAssignedMessage,
+} from '@maka/core/session';
+import type { PendingMessageAdmission } from '@maka/storage/execution-stores';
+import {
+  openStorageWriterComposition,
+  type StorageWriterComposition,
+} from '@maka/storage/storage-writer-composition';
+import {
+  resolveStorageRoot,
+  resolveRootControlNamespace,
+  resolveRootOwnershipNamespace,
+  tryAcquireInteractiveRootOwner,
+  type StorageRootCapability,
+} from '@maka/storage/root-authority';
+import { RuntimeHostOperationError, type RuntimeHostConnection } from '../client/index.js';
+import type { WorkHubCoordinationActInput } from '../protocol/index.js';
+import { connectClient, waitForTerminalTurn } from './fixtures/execution-host-suite.js';
+import { removePosixEndpointDirectories } from './fixtures/endpoint-hygiene.js';
+
+type Notice =
+  | { type: 'ready'; hostEpoch: string }
+  | {
+      type: 'assignment_committed';
+      assignment: WorkHubDelegationAssignedMessage;
+      admission: PendingMessageAdmission;
+      targetCreated: boolean;
+    }
+  | {
+      type: 'dispatch';
+      sessionId: string;
+      turnId: string;
+      text: string;
+      attachments: AttachmentRef[];
+    };
+
+const TIMEOUT = 15_000;
+const ATTACHMENT_TEXT = 'Durable requirements: resume exactly this submitted message.';
+
+// This is a real process loss at a precise durable boundary, not a close/reopen
+// simulation. A fresh Host acquires a fresh lease and runs production recovery.
+for (const disposition of ['create_new', 'delegate_existing'] as const) {
+  for (const withAttachment of [false, true]) {
+    test(`WorkHub ${disposition} survives commit-before-dispatch process death (attachment=${withAttachment})`, {
+      timeout: 60_000,
+    }, async () => {
+      const base = await mkdtemp(join(tmpdir(), 'maka-workhub-crash-'));
+      const root = join(base, 'root');
+      const capability = await resolveStorageRoot({ path: root, kind: 'interactive' });
+      const children: HostProcess[] = [];
+      const clients: RuntimeHostConnection[] = [];
+      try {
+        await withStores(capability, configureDefaultTarget);
+        const first = new HostProcess(root, capability.rootId, 'crash');
+        children.push(first);
+        const firstReady = await first.wait('ready');
+        const client = await connectClient(root);
+        clients.push(client);
+        await client.request('workhub.coordination.resolve', {});
+        const action: WorkHubCoordinationActInput = {
+          actionId: 'durable-delegation',
+          userText:
+            disposition === 'create_new'
+              ? 'Create a new task to review the durable requirements'
+              : 'Review the durable requirements',
+          proposal: { disposition: 'create_new', title: 'Requirements' },
+          create: { workspace: { kind: 'host_path', path: root } },
+        };
+        if (disposition === 'delegate_existing') {
+          await client.request('session.create', {
+            sessionId: 'existing-target',
+            name: 'Requirements',
+            workspace: { kind: 'host_path', path: root },
+            modelTarget: { kind: 'default' },
+          });
+          const candidates = await client.request('workhub.coordination.candidates', {});
+          const target = candidates.candidates.find((c) => c.sessionId === 'existing-target');
+          assert.ok(target);
+          Object.assign(action, {
+            proposal: { disposition, candidateRef: target.candidateRef },
+            candidateSetId: candidates.candidateSetId,
+            create: undefined,
+          });
+        }
+        if (withAttachment)
+          Object.assign(action, { attachments: [await uploadAttachment(client)] });
+
+        // Attach both fulfillment and rejection handlers immediately: the
+        // original caller loses its response when we kill the owner.
+        const request = client.request('workhub.coordination.act', action).then(() => {
+          throw new Error('The trapped assignment unexpectedly returned to its caller');
+        });
+        const committed = await Promise.race([first.wait('assignment_committed'), request]);
+        assert.equal(committed.targetCreated, disposition === 'create_new');
+        assert.deepEqual(
+          first.notices.filter((n) => n.type === 'dispatch'),
+          [],
+        );
+        await first.stop('SIGKILL');
+        await assert.rejects(request);
+        const { assignment, admission } = committed;
+
+        // Open brand-new handles after death. These observations prove we hit
+        // the intended window, before any Root admission or first dispatch.
+        await withStores(capability, async ({ execution: stores }) => {
+          assert.deepEqual(
+            await stores.sessionStore.readWorkHubAssignment(action.actionId),
+            assignment,
+          );
+          assert.deepEqual(
+            await stores.sessionStore.listMessageAdmissions(assignment.targetSessionId),
+            [admission],
+          );
+          assert.equal(
+            await stores.agentRunStore.readRootTurnAdmission(
+              assignment.targetSessionId,
+              assignment.targetTurnId,
+            ),
+            undefined,
+          );
+          assert.deepEqual(
+            await stores.runtimeEventStore.listSessionInvocations(assignment.targetSessionId),
+            [],
+          );
+        });
+
+        const recovered = new HostProcess(root, capability.rootId, 'recover');
+        children.push(recovered);
+        const ready = await recovered.wait('ready');
+        assert.notEqual(ready.hostEpoch, firstReady.hostEpoch);
+        const connection = await connectClient(root);
+        clients.push(connection);
+        const dispatch = await recovered.wait('dispatch');
+        assert.equal(dispatch.sessionId, assignment.targetSessionId);
+        assert.equal(dispatch.turnId, assignment.targetTurnId);
+        assert.equal(dispatch.text, action.userText);
+        const terminal = await waitForTerminalTurn(
+          connection,
+          assignment.targetSessionId,
+          assignment.targetTurnId,
+        );
+        assert.equal(terminal.status, 'completed');
+        if (withAttachment) {
+          assert.equal(dispatch.attachments.length, 1);
+          const ref = dispatch.attachments[0]!.ref;
+          assert.equal(ref.kind, 'session_file');
+          if (ref.kind !== 'session_file') throw new Error('Expected target-owned attachment');
+          assert.equal(ref.sessionId, assignment.targetSessionId);
+          const payload = await connection.request('artifact.query', {
+            kind: 'read_text',
+            sessionId: ref.sessionId,
+            artifactId: ref.relativePath,
+          });
+          assert.equal(payload.kind, 'text');
+          if (payload.kind !== 'text') throw new Error('Expected text attachment');
+          assert.deepEqual(payload.preview, { ok: true, text: ATTACHMENT_TEXT });
+        }
+        const candidates = await connection.request('workhub.coordination.candidates', {});
+        assert.equal(
+          candidates.candidates.find((c) => c.sessionId === assignment.targetSessionId)
+            ?.latestDelegationActionId,
+          action.actionId,
+        );
+
+        // Recovery and a client retry converge on the SAME durable linkage.
+        // No stale candidate reference needs to be re-authorized for replay.
+        const replay = await connection.request('workhub.coordination.act', action);
+        assert.equal(replay.disposition, disposition);
+        assert.ok('targetSessionId' in replay);
+        assert.equal(replay.targetSessionId, assignment.targetSessionId);
+        assert.ok('targetTurnId' in replay);
+        assert.equal(replay.targetTurnId, assignment.targetTurnId);
+        assert.deepEqual(await connection.request('workhub.coordination.act', action), replay);
+        await assert.rejects(
+          connection.request('workhub.coordination.act', {
+            ...action,
+            userText: 'A different task',
+          }),
+          (error: unknown) =>
+            error instanceof RuntimeHostOperationError && error.code === 'operation_conflict',
+        );
+        await connection.close();
+        await recovered.stop();
+        assert.equal(recovered.notices.filter((n) => n.type === 'dispatch').length, 1);
+
+        await withStores(capability, async ({ execution: stores }) => {
+          const headers = await stores.sessionStore.listHeaders();
+          assert.equal(headers.filter((h) => h.role !== 'workhub_coordination').length, 1);
+          const messages = await stores.sessionStore.readMessagesSnapshot(
+            WORKHUB_COORDINATION_SESSION_ID,
+          );
+          assert.deepEqual(
+            messages.filter(
+              (m) => m.type === 'workhub_coordination' && m.kind === 'delegation_assigned',
+            ),
+            [assignment],
+          );
+          assert.deepEqual(
+            await stores.sessionStore.listMessageAdmissions(assignment.targetSessionId),
+            [],
+          );
+          const rootAdmission = await stores.agentRunStore.readRootTurnAdmission(
+            assignment.targetSessionId,
+            assignment.targetTurnId,
+          );
+          assert.ok(rootAdmission);
+          assert.equal(rootAdmission.userMessageId, assignment.targetMessageId);
+          assert.deepEqual(
+            rootAdmission.sourceMessages.map((message) => message.messageId),
+            [assignment.targetMessageId],
+          );
+          assert.deepEqual(rootAdmission.normalizedInput, admission.content);
+          const invocations = await stores.runtimeEventStore.listSessionInvocations(
+            assignment.targetSessionId,
+          );
+          assert.equal(invocations.length, 1);
+          assert.equal(invocations[0]!.runId, rootAdmission.runId);
+          const events = await stores.runtimeEventStore.readImmutableRuntimeEvents(
+            assignment.targetSessionId,
+            rootAdmission.runId,
+          );
+          assert.equal(events.filter((e) => e.role === 'user').length, 1);
+        });
+      } finally {
+        for (const client of clients) await client.close().catch(() => undefined);
+        for (const child of children) await child.stop('SIGKILL');
+        await removePosixEndpointDirectories(capability.rootId);
+        await rm(join(resolveRootControlNamespace(), capability.rootId), {
+          recursive: true,
+          force: true,
+        });
+        await rm(join(resolveRootOwnershipNamespace(), `${capability.rootId}.lock`), {
+          force: true,
+        });
+        await rm(base, { recursive: true, force: true });
+      }
+    });
+  }
+}
+
+async function uploadAttachment(client: RuntimeHostConnection): Promise<AttachmentRef> {
+  const bytes = Buffer.from(ATTACHMENT_TEXT);
+  const sessionId = WORKHUB_COORDINATION_SESSION_ID;
+  const uploadId = 'requirements-upload';
+  await client.request('artifact.ingest', {
+    kind: 'begin',
+    sessionId,
+    uploadId,
+    name: 'requirements.txt',
+    mimeType: 'text/plain',
+    totalBytes: bytes.length,
+    contentSha256: `sha256:${createHash('sha256').update(bytes).digest('hex')}`,
+  });
+  await client.request('artifact.ingest', {
+    kind: 'chunk',
+    sessionId,
+    uploadId,
+    offset: 0,
+    chunkBase64: bytes.toString('base64'),
+  });
+  const result = await client.request('artifact.ingest', { kind: 'commit', sessionId, uploadId });
+  assert.equal(result.kind, 'committed');
+  if (result.kind !== 'committed') throw new Error('Attachment was not committed');
+  return result.attachment;
+}
+
+async function withStores(
+  capability: StorageRootCapability<'interactive'>,
+  run: (stores: StorageWriterComposition) => Promise<void>,
+): Promise<void> {
+  const owner = await tryAcquireInteractiveRootOwner(capability);
+  assert.ok(owner);
+  let stores: StorageWriterComposition | undefined;
+  try {
+    stores = await openStorageWriterComposition(owner.lease);
+    await run(stores);
+  } finally {
+    await stores?.close();
+    await owner.close();
+  }
+}
+
+async function configureDefaultTarget({
+  runtimePolicy: policy,
+}: StorageWriterComposition): Promise<void> {
+  const created = await policy.connectionCatalog.create({
+    expectedCatalogRevision: 0,
+    connection: {
+      slug: 'fake',
+      name: 'Fake',
+      providerType: 'ollama',
+      enabled: true,
+      enabledModelIds: ['fake-model'],
+    },
+  });
+  assert.equal(created.kind, 'committed');
+  if (created.kind !== 'committed') throw new Error('Connection was not committed');
+  const connection = created.snapshot.connections[0]!;
+  const fetch = await policy.operations.beginModelFetch(connection.connectionId);
+  assert.equal(fetch.kind, 'ready');
+  if (fetch.kind !== 'ready') throw new Error('Model fetch was not opened');
+  const fetched = await policy.operations.completeModelFetch(fetch.ticket, {
+    models: [{ id: 'fake-model' }],
+    source: 'fetched',
+    fetchedAt: Date.now(),
+  });
+  assert.equal(fetched.kind, 'committed');
+  if (fetched.kind !== 'committed') throw new Error('Model catalog was not committed');
+  const selected = await policy.connectionCatalog.setDefaultTarget({
+    expectedCatalogRevision: fetched.snapshot.revision,
+    target: { connectionId: connection.connectionId, modelId: 'fake-model' },
+  });
+  assert.equal(selected.kind, 'committed');
+}
+
+class HostProcess {
+  readonly child: ChildProcess;
+  readonly notices: Notice[] = [];
+  readonly closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
+  private readonly listeners = new Set<() => void>();
+
+  constructor(root: string, rootId: string, mode: 'crash' | 'recover') {
+    this.child = fork(
+      new URL('./fixtures/workhub-assignment-crash-host.js', import.meta.url),
+      [root, rootId, mode],
+      { stdio: ['ignore', 'ignore', 'inherit', 'ipc'] },
+    );
+    this.closed = new Promise((resolve, reject) => {
+      this.child.once('error', reject);
+      this.child.once('close', (code, signal) => resolve({ code, signal }));
+    });
+    this.child.on('message', (notice: Notice) => {
+      this.notices.push(notice);
+      for (const listener of this.listeners) listener();
+    });
+  }
+
+  async wait<T extends Notice['type']>(type: T): Promise<Extract<Notice, { type: T }>> {
+    let check!: () => void;
+    const notice = new Promise<Extract<Notice, { type: T }>>((resolve) => {
+      check = () => {
+        const found = this.notices.find((n): n is Extract<Notice, { type: T }> => n.type === type);
+        if (found) resolve(found);
+      };
+      this.listeners.add(check);
+      check();
+    });
+    try {
+      return await withTimeout(
+        Promise.race([
+          notice,
+          this.closed.then((exit) => {
+            throw new Error(`Host exited before ${type}: ${JSON.stringify(exit)}`);
+          }),
+        ]),
+        TIMEOUT,
+        `Host did not report ${type}`,
+      );
+    } finally {
+      this.listeners.delete(check);
+    }
+  }
+
+  async stop(signal?: 'SIGKILL'): Promise<void> {
+    if (this.child.exitCode === null && this.child.signalCode === null) {
+      if (signal) this.child.kill(signal);
+      else this.child.send({ type: 'shutdown' });
+    }
+    const exit = await withTimeout(this.closed, TIMEOUT, 'Host did not exit');
+    if (!signal) assert.deepEqual(exit, { code: 0, signal: null });
+  }
+}
diff --git a/packages/runtime-host/src/server/external-session-coordinator.ts b/packages/runtime-host/src/server/external-session-coordinator.ts
index 53852ef9f2..b12e41af6d 100644
--- a/packages/runtime-host/src/server/external-session-coordinator.ts
+++ b/packages/runtime-host/src/server/external-session-coordinator.ts
@@ -24,7 +24,7 @@ import type {
 } from '@maka/core/external-session';
 import type { CreateSessionInput } from '@maka/core/runtime-inputs';
 import type { SessionExternalOrigin, SessionHeader, StoredMessage } from '@maka/core/session';
-import type { ExternalSessionImportLookupResult } from '@maka/storage/session-store';
+import type { ExternalSessionImportLookupResult } from '@maka/storage/execution-stores';
 import type { SessionCatalogRecord } from '@maka/storage/execution-stores';
 import { ExternalSessionImporter } from '@maka/storage/external-sessions';
 import {
diff --git a/packages/runtime-host/src/server/session-catalog-coordinator.ts b/packages/runtime-host/src/server/session-catalog-coordinator.ts
index 138b6e2d4e..cf8bb2cbb0 100644
--- a/packages/runtime-host/src/server/session-catalog-coordinator.ts
+++ b/packages/runtime-host/src/server/session-catalog-coordinator.ts
@@ -50,7 +50,7 @@ import {
   type SessionHeaderSnapshot,
   type ExecutionStoresWriter,
 } from '@maka/storage/execution-stores';
-import type { CreateStableSessionRequest } from '@maka/storage/session-store';
+import type { CreateStableSessionRequest } from '@maka/storage/execution-stores';
 import { isVisibleSessionMessage } from '@maka/storage/session-message-projection';
 import type { RuntimePolicyStoresWriter } from '@maka/storage/runtime-policy-stores';
 import {
diff --git a/packages/runtime-host/src/server/workhub-coordination-coordinator.ts b/packages/runtime-host/src/server/workhub-coordination-coordinator.ts
index 4ba0f54483..745e98a3d4 100644
--- a/packages/runtime-host/src/server/workhub-coordination-coordinator.ts
+++ b/packages/runtime-host/src/server/workhub-coordination-coordinator.ts
@@ -38,7 +38,7 @@ import {
   type WorkHubDelegationStopRequestedMessage,
   type WorkHubDelegationStopResolvedMessage,
 } from '@maka/core/session';
-import type { SessionAuthorityStore, SessionHeaderSnapshot } from '@maka/storage/session-store';
+import type { ExecutionSessionWriter, SessionHeaderSnapshot } from '@maka/storage/execution-stores';
 import type {
   OperationOutcome,
   WorkHubCoordinationActResult,
@@ -84,7 +84,7 @@ const COORDINATION_SUMMARY_READ_MAX_BYTES =
   16 * 1024;
 
 type CoordinationStores = Pick<
-  SessionAuthorityStore,
+  ExecutionSessionWriter,
   | 'appendMessages'
   | 'createStableSession'
   | 'listHeaders'
diff --git a/packages/storage/src/__tests__/fixtures/workhub-assignment.ts b/packages/storage/src/__tests__/fixtures/workhub-assignment.ts
new file mode 100644
index 0000000000..48d88b5e95
--- /dev/null
+++ b/packages/storage/src/__tests__/fixtures/workhub-assignment.ts
@@ -0,0 +1,92 @@
+/*
+ * 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.
+ */
+
+import { createHash } from 'node:crypto';
+import { messageContentDigest, normalizeMessageContent } from '@maka/core/events';
+import {
+  WORKHUB_COORDINATION_SESSION_ID,
+  WORKHUB_COORDINATION_SESSION_ROLE,
+  type WorkHubDelegationAssignedMessage,
+} from '@maka/core/session';
+import type { SessionAuthorityStore } from '../../session-store-contract.js';
+
+export async function createCoordinationSession(
+  store: Pick<SessionAuthorityStore, 'createStableSession'>,
+  root: string,
+): Promise<void> {
+  await store.createStableSession({
+    sessionId: WORKHUB_COORDINATION_SESSION_ID,
+    requestFingerprint: `sha256:${'a'.repeat(64)}`,
+    input: {
+      cwd: root,
+      name: 'WorkHub',
+      role: WORKHUB_COORDINATION_SESSION_ROLE,
+      llmConnectionSlug: 'test',
+      model: 'test',
+      permissionMode: 'explore',
+      toolProfile: 'workhub-coordination-v1',
+    },
+  });
+}
+
+export type AssignmentRequest = ReturnType<typeof assignmentRequest>;
+
+export function assignmentRequest(
+  actionId: string,
+  targetSessionId: string,
+  targetSessionName: string,
+  targetTurnId: string,
+) {
+  const suffix = createHash('sha256').update(actionId, 'utf8').digest('hex').slice(0, 48);
+  const content = normalizeMessageContent({ text: 'Continue payment work' });
+  const assignment: WorkHubDelegationAssignedMessage = {
+    type: 'workhub_coordination',
+    id: `wha_${suffix}`,
+    turnId: actionId,
+    ts: 10,
+    schemaVersion: 1,
+    kind: 'delegation_assigned',
+    actionId,
+    actionFingerprint: `sha256:${'c'.repeat(64)}`,
+    coordinationTurnId: actionId,
+    targetSessionId,
+    targetSessionName,
+    targetTurnId,
+    targetMessageId: `whm_${suffix}`,
+    delegationId: `whd_${suffix}`,
+    disposition: 'delegate_existing',
+    userText: content.text,
+  };
+  return {
+    assignment,
+    admission: {
+      sessionId: targetSessionId,
+      turnId: targetTurnId,
+      runId: `whr_${suffix}`,
+      messageId: assignment.targetMessageId,
+      content,
+      submittedContentDigest: messageContentDigest(content),
+      submittedPlacement: 'current_turn' as const,
+      placement: 'current_turn' as const,
+      disposition: 'steering' as const,
+      skillInvocation: { loaded: [], failed: [], receipts: [] },
+      admittedAt: 10,
+    },
+  };
+}
diff --git a/packages/storage/src/__tests__/local-persistence-contract.test.ts b/packages/storage/src/__tests__/local-persistence-contract.test.ts
new file mode 100644
index 0000000000..3f0749f180
--- /dev/null
+++ b/packages/storage/src/__tests__/local-persistence-contract.test.ts
@@ -0,0 +1,263 @@
+/*
+ * 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.
+ */
+
+import assert from 'node:assert/strict';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { after, test } from 'node:test';
+import {
+  messageContentDigest,
+  normalizeMessageContent,
+  type AttachmentRef,
+} from '@maka/core/events';
+import { WORKHUB_COORDINATION_SESSION_ID } from '@maka/core/session';
+import {
+  SessionMetadataConflictError,
+  SessionMetadataVersionConflictError,
+  type WorkHubMessageAssignmentRequest,
+} from '../session-store-contract.js';
+import {
+  SessionMetadataConflictError as SqliteConflict,
+  SessionMetadataVersionConflictError as SqliteVersionConflict,
+} from '../sqlite-session-metadata-store.js';
+import { SessionMetadataConflictError as ExecutionConflict } from '../execution-stores.js';
+import { acquireOperationalStateDatabase } from '../operational-state-store.js';
+import {
+  openStorageWriterComposition,
+  type StorageWriterComposition,
+} from '../storage-writer-composition.js';
+import {
+  resolveStorageRoot,
+  tryAcquireInteractiveRootOwner,
+  runWithStorageRootLease,
+  StorageRootAuthorityError,
+  type InteractiveRootOwner,
+} from '../root-authority.js';
+import {
+  trackControlDirectory,
+  removeTrackedControlDirectories,
+} from './fixtures/control-directory-hygiene.js';
+import { assignmentRequest, createCoordinationSession } from './fixtures/workhub-assignment.js';
+
+after(removeTrackedControlDirectories);
+
+test('contract errors retain instanceof identity through existing package seams', () => {
+  assert.equal(SqliteConflict, SessionMetadataConflictError);
+  assert.equal(ExecutionConflict, SessionMetadataConflictError);
+  assert.equal(SqliteVersionConflict, SessionMetadataVersionConflictError);
+  assert.ok(new SessionMetadataVersionConflictError('target', 1, 2) instanceof SqliteConflict);
+});
+
+test('leased WorkHub contract persists copied attachments and rejects inconsistent content or replay', async () => {
+  await withComposition(async (storage, root) => {
+    const store = storage.execution.sessionStore;
+    await createCoordinationSession(store, root);
+    const target = await store.create({
+      cwd: root,
+      name: 'Payments',
+      llmConnectionSlug: 'test',
+      model: 'test',
+      permissionMode: 'ask',
+    });
+    const source: AttachmentRef = {
+      kind: 'other',
+      name: 'requirements.txt',
+      mimeType: 'text/plain',
+      bytes: 12,
+      ref: {
+        kind: 'session_file',
+        sessionId: WORKHUB_COORDINATION_SESSION_ID,
+        relativePath: 'source.txt',
+      },
+    };
+    const copied: AttachmentRef = {
+      ...source,
+      ref: { kind: 'session_file', sessionId: target.id, relativePath: 'copied.txt' },
+    };
+    const base = assignmentRequest('attachments', target.id, 'Payments', 'target-turn');
+    const content = normalizeMessageContent({
+      text: base.assignment.userText,
+      attachments: [copied],
+    });
+    const request: WorkHubMessageAssignmentRequest = {
+      assignment: { ...base.assignment, attachments: [source] },
+      admission: {
+        ...base.admission,
+        content,
+        submittedContentDigest: messageContentDigest(content),
+      },
+    };
+    for (const attachments of [
+      [],
+      [source],
+      [{ ...copied, bytes: 13 }],
+      [copied, copied],
+      [{ ...copied, name: 'different.txt' }],
+    ]) {
+      const invalid = normalizeMessageContent({ text: base.assignment.userText, attachments });
+      await assert.rejects(
+        store.assignWorkHubMessage({
+          ...request,
+          admission: {
+            ...request.admission,
+            content: invalid,
+            submittedContentDigest: messageContentDigest(invalid),
+          },
+        }),
+        SessionMetadataConflictError,
+      );
+      assert.equal(await store.readWorkHubAssignment(base.assignment.actionId), undefined);
+      assert.deepEqual(await store.listMessageAdmissions(target.id), []);
+    }
+    await assert.rejects(
+      store.assignWorkHubMessage({
+        ...request,
+        assignment: { ...request.assignment, attachments: [copied] },
+      }),
+      SessionMetadataConflictError,
+    );
+    assert.equal((await store.assignWorkHubMessage(request)).kind, 'assigned');
+    assert.equal((await store.assignWorkHubMessage(request)).kind, 'existing');
+    assert.deepEqual(
+      await store.readMessageAdmission(target.id, base.admission.messageId),
+      request.admission,
+    );
+    // Same caller-supplied fingerprint cannot authorize replacing source content.
+    const replacement = { ...source, ref: { ...source.ref, relativePath: 'different-source.txt' } };
+    await assert.rejects(
+      store.assignWorkHubMessage({
+        ...request,
+        assignment: { ...request.assignment, attachments: [replacement] },
+      }),
+      SessionMetadataConflictError,
+    );
+    assert.deepEqual(
+      await store.readWorkHubAssignment(base.assignment.actionId),
+      request.assignment,
+    );
+  });
+});
+
+test('leased WorkHub transaction rolls back target, create claim, admission and linkage together', async () => {
+  await withComposition(async (storage, root, owner) => {
+    const store = storage.execution.sessionStore;
+    await createCoordinationSession(store, root);
+    const base = assignmentRequest('rollback', 'new-target', 'Payments', 'target-turn');
+    const request: WorkHubMessageAssignmentRequest = {
+      ...base,
+      assignment: {
+        ...base.assignment,
+        disposition: 'create_new',
+        create: { title: 'Payments', workspace: { kind: 'host_path', path: root } },
+      },
+      create: {
+        sessionId: 'new-target',
+        requestFingerprint: `sha256:${'b'.repeat(64)}`,
+        input: {
+          cwd: root,
+          name: 'Payments',
+          llmConnectionSlug: 'test',
+          model: 'test',
+          permissionMode: 'ask',
+        },
+      },
+    };
+    // The adapter owns one shared connection. A test-only trigger aborts AFTER
+    // target creation and admission insert, during the coordination insert.
+    // The Host-facing contract exposes neither this connection nor SQL callbacks.
+    const database = await runWithStorageRootLease(
+      owner.lease,
+      'interactive',
+      'write',
+      async (path) => acquireOperationalStateDatabase(path),
+    );
+    try {
+      database.database.exec(`
+        CREATE TEMP TRIGGER workhub_assignment_rollback BEFORE INSERT ON session_messages
+        WHEN NEW.session_id = 'maka_workhub_coordination'
+          AND json_extract(NEW.record_json, '$.kind') = 'delegation_assigned'
+        BEGIN SELECT RAISE(ABORT, 'workhub_assignment_rollback'); END;
+      `);
+      await assert.rejects(store.assignWorkHubMessage(request), /workhub_assignment_rollback/);
+      assert.equal(await store.readWorkHubAssignment(base.assignment.actionId), undefined);
+      assert.equal(
+        (await store.probeStableSessionCreate('new-target', request.create!.requestFingerprint))
+          .kind,
+        'absent',
+      );
+      assert.deepEqual(await store.listMessageAdmissions('new-target'), []);
+      assert.deepEqual(
+        (await store.listHeaders()).map((header) => header.id),
+        [WORKHUB_COORDINATION_SESSION_ID],
+      );
+      database.database.exec('DROP TRIGGER workhub_assignment_rollback');
+      assert.equal((await store.assignWorkHubMessage(request)).kind, 'assigned');
+      assert.equal((await store.assignWorkHubMessage(request)).kind, 'existing');
+      assert.deepEqual(
+        await store.readWorkHubAssignment(base.assignment.actionId),
+        request.assignment,
+      );
+      assert.deepEqual(await store.listMessageAdmissions('new-target'), [request.admission]);
+    } finally {
+      database.database.exec('DROP TRIGGER IF EXISTS workhub_assignment_rollback');
+      database.close();
+    }
+  });
+});
+
+test('retained execution contract cannot read or assign after its root lease is closed', async () => {
+  await withComposition(async (storage, root, owner) => {
+    const store = storage.execution.sessionStore;
+    await createCoordinationSession(store, root);
+    await storage.close();
+    await owner.close();
+    const invalidLease = (error: unknown) =>
+      error instanceof StorageRootAuthorityError && error.code === 'invalid_lease';
+    await assert.rejects(store.listHeaders(), invalidLease);
+    await assert.rejects(
+      store.assignWorkHubMessage(assignmentRequest('closed', 'target', 'Payments', 'turn')),
+      invalidLease,
+    );
+  });
+});
+
+async function withComposition(
+  run: (
+    storage: StorageWriterComposition,
+    root: string,
+    owner: InteractiveRootOwner,
+  ) => Promise<void>,
+): Promise<void> {
+  const root = await mkdtemp(join(tmpdir(), 'maka-local-persistence-contract-'));
+  const capability = trackControlDirectory(
+    await resolveStorageRoot({ path: root, kind: 'interactive' }),
+  );
+  const owner = await tryAcquireInteractiveRootOwner(capability);
+  assert.ok(owner);
+  let storage: StorageWriterComposition | undefined;
+  try {
+    storage = await openStorageWriterComposition(owner.lease);
+    await run(storage, root, owner);
+  } finally {
+    await storage?.close();
+    await owner.close();
+    await rm(root, { recursive: true, force: true });
+  }
+}
diff --git a/packages/storage/src/__tests__/local-persistence-dependencies.test.ts b/packages/storage/src/__tests__/local-persistence-dependencies.test.ts
new file mode 100644
index 0000000000..0e5b9f7fb2
--- /dev/null
+++ b/packages/storage/src/__tests__/local-persistence-dependencies.test.ts
@@ -0,0 +1,94 @@
+/*
+ * 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.
+ */
+
+import assert from 'node:assert/strict';
+import { readFile, readdir } from 'node:fs/promises';
+import { test } from 'node:test';
+
+// These are dependency guards, not a replacement for behavioral contract tests.
+// Keep the check independent of TypeScript's version-specific compiler API.
+function dependencies(source: string): string[] {
+  return [
+    ...source.matchAll(/\b(?:from|import)\s*['"]([^'"]+)['"]/gu),
+    ...source.matchAll(/\b(?:import|require)\s*\(\s*['"]([^'"]+)['"]/gu),
+  ].map((match) => match[1]!);
+}
+
+test('Session and Tool persistence contracts do not import concrete storage implementations', async () => {
+  for (const name of ['session-store-contract', 'runtime-event-store-contract']) {
+    const source = await readFile(new URL(`../../src/${name}.ts`, import.meta.url), 'utf8');
+    for (const specifier of dependencies(source)) {
+      assert.ok(
+        specifier.startsWith('@maka/core/') || specifier === './message-admission-store.js',
+        `${name}: implementation dependency ${specifier} must stay behind composition`,
+      );
+    }
+  }
+  const execution = await readFile(
+    new URL('../../src/execution-stores.ts', import.meta.url),
+    'utf8',
+  );
+  assert.doesNotMatch(
+    execution,
+    /from\s*['"]\.\/sqlite-(?:runtime-store|session-metadata-store)\.js['"]/u,
+  );
+});
+
+test('production Runtime and Host use persistence contracts, with writer construction owned by composition', async () => {
+  for (const directory of [
+    new URL('../../../runtime/src/', import.meta.url),
+    new URL('../../../runtime-host/src/server/', import.meta.url),
+  ]) {
+    for (const file of await productionSources(directory)) {
+      const source = await readFile(file, 'utf8');
+      for (const specifier of dependencies(source)) {
+        assert.ok(
+          !/^(?:node:sqlite|sqlite3?|better-sqlite3)$/u.test(specifier) &&
+            !/\/(?:sqlite-[^/]+|session-store|agent-run-store|runtime-event-persistence)(?:\.js)?$/u.test(
+              specifier,
+            ),
+          `${file.pathname}: consume execution-stores, not ${specifier}`,
+        );
+      }
+      assert.doesNotMatch(
+        source,
+        /\b(?:createSqlite\w+|openSqlite\w+|createSessionStore)\b/u,
+        `${file.pathname}: concrete adapter construction belongs to storage composition`,
+      );
+      if (file.pathname.endsWith('/runtime-host/src/server/execution-composition.ts')) continue;
+      assert.doesNotMatch(
+        source,
+        /\b(?:openStorageWriterComposition|openInteractiveExecutionStoresForWrite)\b/u,
+        `${file.pathname}: receive owned writers from composition`,
+      );
+    }
+  }
+});
+
+async function productionSources(directory: URL): Promise<URL[]> {
+  const files: URL[] = [];
+  for (const entry of await readdir(directory, { withFileTypes: true })) {
+    if (entry.name === '__tests__' || entry.name === 'test-only') continue;
+    if (entry.isDirectory())
+      files.push(...(await productionSources(new URL(`${entry.name}/`, directory))));
+    else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts'))
+      files.push(new URL(entry.name, directory));
+  }
+  return files;
+}
diff --git a/packages/storage/src/__tests__/workhub-message-assignment.test.ts b/packages/storage/src/__tests__/workhub-message-assignment.test.ts
index 1faa540c70..d49e00cf5b 100644
--- a/packages/storage/src/__tests__/workhub-message-assignment.test.ts
+++ b/packages/storage/src/__tests__/workhub-message-assignment.test.ts
@@ -26,7 +26,6 @@ import { test } from 'node:test';
 import { messageContentDigest, normalizeMessageContent } from '@maka/core/events';
 import {
   WORKHUB_COORDINATION_SESSION_ID,
-  WORKHUB_COORDINATION_SESSION_ROLE,
   type WorkHubDelegationAssignedMessage,
   type WorkHubDelegationReplacementAbortedMessage,
   type WorkHubDelegationStopRequestedMessage,
@@ -35,6 +34,11 @@ import {
 } from '@maka/core/session';
 import { createSqliteAgentRunStore } from '../agent-run-store.js';
 import { createSessionStore, isSessionNotFoundError } from '../session-store.js';
+import {
+  createCoordinationSession,
+  assignmentRequest,
+  type AssignmentRequest,
+} from './fixtures/workhub-assignment.js';
 
 test('atomically commits one WorkHub assignment and target admission', async () => {
   const root = await mkdtemp(join(tmpdir(), 'maka-workhub-assignment-'));
@@ -688,25 +692,6 @@ test('an unresolved stop claim blocks replacement while not_owned releases the l
   }
 });
 
-async function createCoordinationSession(
-  store: ReturnType<typeof createSessionStore>,
-  root: string,
-): Promise<void> {
-  await store.createStableSession({
-    sessionId: WORKHUB_COORDINATION_SESSION_ID,
-    requestFingerprint: `sha256:${'a'.repeat(64)}`,
-    input: {
-      cwd: root,
-      name: 'WorkHub',
-      role: WORKHUB_COORDINATION_SESSION_ROLE,
-      llmConnectionSlug: 'test',
-      model: 'test',
-      permissionMode: 'explore',
-      toolProfile: 'workhub-coordination-v1',
-    },
-  });
-}
-
 function terminalSuffix(delegationId: string): string {
   return createHash('sha256').update(delegationId, 'utf8').digest('hex').slice(0, 48);
 }
@@ -753,49 +738,3 @@ async function handOffToRootTurn(
     turnId: request.admission.turnId,
   });
 }
-
-type AssignmentRequest = ReturnType<typeof assignmentRequest>;
-
-function assignmentRequest(
-  actionId: string,
-  targetSessionId: string,
-  targetSessionName: string,
-  targetTurnId: string,
-) {
-  const suffix = createHash('sha256').update(actionId, 'utf8').digest('hex').slice(0, 48);
-  const content = normalizeMessageContent({ text: 'Continue payment work' });
-  const assignment: WorkHubDelegationAssignedMessage = {
-    type: 'workhub_coordination',
-    id: `wha_${suffix}`,
-    turnId: actionId,
-    ts: 10,
-    schemaVersion: 1,
-    kind: 'delegation_assigned',
-    actionId,
-    actionFingerprint: `sha256:${'c'.repeat(64)}`,
-    coordinationTurnId: actionId,
-    targetSessionId,
-    targetSessionName,
-    targetTurnId,
-    targetMessageId: `whm_${suffix}`,
-    delegationId: `whd_${suffix}`,
-    disposition: 'delegate_existing',
-    userText: content.text,
-  };
-  return {
-    assignment,
-    admission: {
-      sessionId: targetSessionId,
-      turnId: targetTurnId,
-      runId: `whr_${suffix}`,
-      messageId: assignment.targetMessageId,
-      content,
-      submittedContentDigest: messageContentDigest(content),
-      submittedPlacement: 'current_turn' as const,
-      placement: 'current_turn' as const,
-      disposition: 'steering' as const,
-      skillInvocation: { loaded: [], failed: [], receipts: [] },
-      admittedAt: 10,
-    },
-  };
-}
diff --git a/packages/storage/src/execution-stores.ts b/packages/storage/src/execution-stores.ts
index a85b6d23c5..e98613b670 100644
--- a/packages/storage/src/execution-stores.ts
+++ b/packages/storage/src/execution-stores.ts
@@ -46,7 +46,8 @@ import {
   createConversationOperationalStateStore,
   type ConversationOperationalStateStore,
 } from './conversation-operational-state.js';
-import { createSessionStore, type SessionAuthorityStore } from './session-store.js';
+import { createSessionStore } from './session-store.js';
+import type { SessionAuthorityStore } from './session-store-contract.js';
 import {
   assertStorageRootLease,
   runWithStorageRootLease,
@@ -71,7 +72,7 @@ import type {
   SessionRuntimeEventEntry,
   ToolCommitResult,
   ToolOperationRecord,
-} from './sqlite-runtime-store.js';
+} from './runtime-event-store-contract.js';
 
 const executionStoresWriterBrand: unique symbol = Symbol('ExecutionStoresWriter');
 const executionStoresReaderBrand: unique symbol = Symbol('ExecutionStoresReader');
@@ -84,11 +85,11 @@ export {
   normalizeRootTurnAdmissionPayload,
   rootTurnAdmissionRecordFits,
 } from './agent-run-store.js';
-export { isSessionNotFoundError } from './session-store.js';
+export { isSessionNotFoundError } from './session-store-contract.js';
 export {
   SessionMetadataConflictError,
   SessionMetadataVersionConflictError,
-} from './sqlite-session-metadata-store.js';
+} from './session-store-contract.js';
 
 export type {
   AdmitRootTurnInput,
@@ -117,6 +118,7 @@ export type {
 export { submittedTurnIntentsEqual } from './submitted-turn-intent.js';
 export type { SubmittedTurnIntent } from './submitted-turn-intent.js';
 export type {
+  CreateStableSessionRequest,
   ProbeSessionRemovalResult,
   ExternalSessionImportLookupResult,
   SessionCatalogPageCursor,
@@ -134,7 +136,7 @@ export type {
   SessionTurnContributionPage,
   SessionTurnLandmark,
   SessionTurnLandmarkSnapshot,
-} from './session-store.js';
+} from './session-store-contract.js';
 
 export type ExecutionSessionWriter = SessionAuthorityStore;
 export type {
diff --git a/packages/storage/src/runtime-event-store-contract.ts b/packages/storage/src/runtime-event-store-contract.ts
new file mode 100644
index 0000000000..9ea5b99ae4
--- /dev/null
+++ b/packages/storage/src/runtime-event-store-contract.ts
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+import type { RuntimeEvent, ToolRecoveryMode } from '@maka/core/runtime-event';
+
+/** T1/T2 transactions keep their runtime fact and recovery journal inseparable. */
+export interface CommitToolPreparedInput {
+  operationId: string;
+  journalEventId: string;
+  runtimeEvent: RuntimeEvent;
+  dispatchRuntimeEvent: RuntimeEvent;
+  providerToolCallId: string;
+  toolName: string;
+  canonicalArgsHash: string;
+  recoveryMode: ToolRecoveryMode;
+  committedAt: number;
+}
+
+export interface CommitToolOutcomeInput {
+  operationId: string;
+  journalEventId: string;
+  runtimeEvent: RuntimeEvent;
+  committedAt: number;
+}
+
+export interface ToolCommitResult {
+  created: boolean;
+  runtimeEventSeq: number;
+}
+
+/** Storage-owned, immutable append position for an Event within one Session. */
+export interface SessionRuntimeEventEntry {
+  readonly ordinal: number;
+  readonly event: RuntimeEvent;
+}
+
+export interface ToolOperationRecord {
+  operationId: string;
+  invocationId: string;
+  runId: string;
+  turnId: string;
+  providerToolCallId: string;
+  toolName: string;
+  canonicalArgsHash: string;
+  recoveryMode: ToolRecoveryMode;
+  currentState: 'prepared' | 'outcome_committed' | 'recovery_completed' | 'recovery_parked';
+  callEventId: string;
+  dispatchEventId?: string;
+  resultEventId?: string;
+  version: number;
+}
diff --git a/packages/storage/src/session-store-contract.ts b/packages/storage/src/session-store-contract.ts
new file mode 100644
index 0000000000..e2cfa8582f
--- /dev/null
+++ b/packages/storage/src/session-store-contract.ts
@@ -0,0 +1,516 @@
+/*
+ * 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.
+ */
+
+import type {
+  AgentGraphOperatorProvisionRequest,
+  AgentGraphOperatorProvisionResult,
+} from '@maka/core/agent-graph-topology';
+import type {
+  CreateSandboxBoundaryRequest,
+  ExecutionBoundary,
+  SandboxBoundaryRequest,
+  SandboxBoundarySettlement,
+  SettleSandboxBoundaryRequest,
+} from '@maka/core/sandbox-boundary';
+import type { CreateSessionInput, SessionListFilter } from '@maka/core/runtime-inputs';
+import type {
+  SessionHeader,
+  SessionHeaderPatch,
+  SessionConversationCopy,
+  SessionExternalOrigin,
+  SessionSummary,
+  SessionRole,
+  StoredMessage,
+  TurnRecord,
+  TurnStateMessage,
+  AssistantMessage,
+  UserMessage,
+  WorkHubDelegationAssignedMessage,
+  WorkHubDelegationReplacementAbortedMessage,
+  WorkHubDelegationReplacementRequestedMessage,
+  WorkHubActionClaim,
+  WorkHubActionClaimOutcome,
+  WorkHubDelegationStopRequestedMessage,
+  WorkHubDelegationStopResolvedMessage,
+  WorkHubDelegationSupersededMessage,
+} from '@maka/core/session';
+import type { MessageAdmissionStore, PendingMessageAdmission } from './message-admission-store.js';
+
+/**
+ * Local Session persistence contract. Implementations own atomic domain writes;
+ * consumers do not receive a database handle or a generic transaction callback.
+ * This is the live-state boundary, not the immutable checkpoint Repository.
+ */
+
+export interface VersionedSessionIdentity {
+  readonly sessionId: string;
+  readonly expectedVersion: number;
+}
+
+export interface SessionConfigurationMetadataUpdate {
+  readonly expectedVersion: number;
+  readonly configuration: {
+    readonly backend: SessionHeader['backend'];
+    readonly llmConnectionId: string;
+    readonly llmConnectionSlug: string;
+    readonly connectionLocked: boolean;
+    readonly model: string;
+    readonly thinkingLevel: SessionHeader['thinkingLevel'];
+    readonly permissionMode: SessionHeader['permissionMode'];
+    readonly collaborationMode: NonNullable<SessionHeader['collaborationMode']>;
+    readonly orchestrationMode: NonNullable<SessionHeader['orchestrationMode']>;
+    readonly labels: readonly string[];
+  };
+  readonly lifecycle:
+    | { readonly kind: 'preserve' }
+    | {
+        readonly kind: 'clear_connection_block';
+        readonly statusUpdatedAt: number;
+      };
+}
+
+export class SessionMetadataConflictError extends Error {
+  readonly name: string = 'SessionMetadataConflictError';
+}
+
+export class SessionMetadataVersionConflictError extends SessionMetadataConflictError {
+  readonly name = 'SessionMetadataVersionConflictError';
+
+  constructor(
+    readonly sessionId: string,
+    readonly expectedVersion: number,
+    readonly actualVersion: number,
+  ) {
+    super(
+      `Session metadata version conflict for ${sessionId}: expected ${expectedVersion}, found ${actualVersion}`,
+    );
+  }
+}
+
+const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+
+export function isSafeSessionId(sessionId: string): boolean {
+  return SESSION_ID_PATTERN.test(sessionId);
+}
+
+export function assertSafeSessionId(sessionId: string): void {
+  if (!isSafeSessionId(sessionId)) throw new Error(`Invalid Session id: ${sessionId}`);
+}
+export class SessionNotFoundError extends Error {
+  readonly name = 'SessionNotFoundError';
+  readonly code = 'session_not_found';
+
+  constructor(readonly sessionId: string) {
+    super(`Session metadata not found: ${sessionId}`);
+  }
+}
+
+export function isSessionNotFoundError(error: unknown): error is SessionNotFoundError {
+  return error instanceof SessionNotFoundError;
+}
+
+export interface SessionHeaderSnapshot {
+  readonly header: SessionHeader;
+  readonly revision: number;
+  readonly committedAt: number;
+}
+
+export type ProbeSessionRemovalResult =
+  | { readonly kind: 'present'; readonly record: SessionHeaderSnapshot }
+  | { readonly kind: 'removed' }
+  | { readonly kind: 'absent' };
+
+export interface SessionCatalogRecord extends SessionHeaderSnapshot {
+  readonly activityAt: number;
+  readonly summary: SessionSummary;
+}
+
+export interface SessionCatalogPageCursor {
+  readonly activityAt: number;
+  readonly sessionId: string;
+}
+
+export const EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_SOURCE_IDS = 256;
+export const EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_RECENT_SESSION_IDS = 16;
+
+export interface ExternalSessionImportLookupResult {
+  readonly sourceSessionId: string;
+  readonly livePublishedImportCount: number;
+  readonly recentSessionIds: readonly string[];
+}
+
+export type SessionCatalogPageResult =
+  | {
+      readonly kind: 'page';
+      readonly revision: `sha256:${string}`;
+      readonly records: readonly SessionCatalogRecord[];
+      readonly hasMore: boolean;
+    }
+  | {
+      readonly kind: 'revision_changed';
+      readonly expectedRevision: `sha256:${string}`;
+      readonly actualRevision: `sha256:${string}`;
+    };
+
+export interface CreateStableSessionRequest {
+  readonly sessionId: string;
+  readonly requestFingerprint: string;
+  readonly input: StableSessionCreateInput;
+}
+
+export interface WorkHubMessageAssignmentRequest {
+  readonly assignment: WorkHubDelegationAssignedMessage;
+  readonly admission: PendingMessageAdmission;
+  /** Present exactly when this assignment atomically supersedes an earlier link. */
+  readonly supersession?: WorkHubDelegationSupersededMessage;
+  /** Present exactly when the assignment creates its target Session. */
+  readonly create?: CreateStableSessionRequest;
+}
+
+export interface WorkHubMessageAssignmentResult {
+  readonly kind: 'assigned' | 'existing';
+  readonly targetCreated: boolean;
+  readonly assignment: WorkHubDelegationAssignedMessage;
+}
+
+export type StableSessionCreateInput = CreateSessionInput & {
+  readonly conversationCopy?: SessionConversationCopy;
+  readonly role?: SessionRole;
+};
+
+export type CreateStableSessionResult =
+  | { readonly kind: 'created'; readonly record: SessionHeaderSnapshot }
+  | { readonly kind: 'existing'; readonly record: SessionHeaderSnapshot }
+  | {
+      readonly kind: 'conflict';
+      readonly reason: 'identity_mismatch' | 'removed';
+    };
+
+export type ProbeStableSessionCreateResult =
+  | { readonly kind: 'absent' }
+  | { readonly kind: 'existing'; readonly record: SessionHeaderSnapshot }
+  | {
+      readonly kind: 'conflict';
+      readonly reason: 'identity_mismatch' | 'removed';
+    };
+
+export type UpdateSessionConfigurationRequest = SessionConfigurationMetadataUpdate;
+
+export interface SessionTranscriptStorageFragment {
+  readonly sequence: number;
+  readonly byteOffset: number;
+  readonly totalBytes: number;
+  readonly payloadDigest: `sha256:${string}` | null;
+  readonly data: Buffer;
+}
+
+export interface SessionTranscriptMessageLookupRequest {
+  readonly messageIds: readonly string[];
+  readonly throughSequence: number | null;
+  readonly maxBytes: number;
+  readonly maxMessages: number;
+}
+
+/**
+ * One page of a Session's legacy rows, for the converter that lifts history onto
+ * the ledger and for coordination facts merged with Runtime history through the
+ * WorkHub transcript index.
+ */
+export interface SessionMessageScanRequest {
+  /** Exclusive lower bound; omit to start at the first row. */
+  readonly afterSequence?: number;
+  /**
+   * Walk towards older rows instead, from this exclusive upper bound. Records
+   * then come back newest first, so the byte budget truncates at the older end,
+   * which is the end the walk is heading for. Pass at most one bound.
+   */
+  readonly beforeSequence?: number;
+  readonly maxStoredBytes: number;
+  readonly maxMessages: number;
+}
+
+export interface SessionMessageScanRecord {
+  readonly sequence: number;
+  readonly message: StoredMessage;
+}
+
+export interface SessionMessageScanPage {
+  readonly records: readonly SessionMessageScanRecord[];
+  /**
+   * The Session's last legacy sequence. It rides along with every page so the
+   * converter can place a turn relative to the whole transcript without a read
+   * that is proportional to it.
+   */
+  readonly highWaterSequence: number | null;
+}
+
+export interface SessionTranscriptPageRequest {
+  readonly direction: 'older' | 'newer';
+  /** Inclusive durable high-water mark. Omit only for the first read. */
+  readonly throughSequence?: number | null;
+  /** Inclusive sequence position for this read. Defaults to the watermark edge. */
+  readonly position?: number;
+  /** Continuation byte offset within position. */
+  readonly byteOffset?: number;
+  readonly maxBytes: number;
+  readonly maxMessages: number;
+}
+
+export interface SessionTranscriptStoragePage {
+  readonly throughSequence: number | null;
+  /** Returned in traversal order for the requested direction. */
+  readonly fragments: readonly SessionTranscriptStorageFragment[];
+  readonly rawBytes: number;
+  readonly next: {
+    readonly position: number;
+    readonly byteOffset: number | null;
+  } | null;
+}
+
+export interface SessionTranscriptRecordScanRequest {
+  readonly direction: 'older' | 'newer';
+  readonly throughSequence?: number | null;
+  readonly position?: number;
+  readonly maxStoredBytes: number;
+  readonly maxMessages: number;
+}
+
+export interface SessionTranscriptRecordScanPage {
+  readonly throughSequence: number | null;
+  readonly records: readonly { readonly sequence: number; readonly message: StoredMessage }[];
+  readonly nextPosition: number | null;
+}
+
+export interface SessionTurnContribution {
+  readonly turnId: string;
+  readonly firstSequence: number;
+  readonly latestState: {
+    readonly sequence: number;
+    readonly message: TurnStateMessage;
+  } | null;
+  readonly userPromptPreview: string | null;
+}
+
+export interface SessionTurnContributionPage {
+  readonly throughSequence: number | null;
+  readonly contributions: readonly SessionTurnContribution[];
+  readonly nextPosition: number | null;
+}
+
+export interface SessionTurnLandmark {
+  readonly turnId: string;
+  readonly sequence: number;
+  readonly label: string;
+}
+
+export interface SessionTurnLandmarkSnapshot {
+  readonly throughSequence: number | null;
+  readonly landmarks: readonly SessionTurnLandmark[];
+}
+
+export interface SessionStore {
+  create(input: CreateSessionInput, initialBoundary?: ExecutionBoundary): Promise<SessionHeader>;
+  list(filter?: SessionListFilter): Promise<SessionSummary[]>;
+  /** Enumerate durable metadata without reading transcript bodies. */
+  listHeaders(): Promise<SessionHeader[]>;
+  listForRecovery(): Promise<SessionHeader[]>;
+  /** Read only the durable header without triggering connection-lock self-healing. */
+  readHeaderSnapshot(sessionId: string): Promise<SessionHeader>;
+  readMessagesSnapshot(sessionId: string): Promise<StoredMessage[]>;
+  readTranscriptHighWaterSnapshot(sessionId: string): Promise<number | null>;
+  listTurnsSnapshot(sessionId: string): Promise<TurnRecord[]>;
+  readHeader(sessionId: string): Promise<SessionHeader>;
+  readMessages(sessionId: string): Promise<StoredMessage[]>;
+  readMessagesAfter(
+    sessionId: string,
+    request: SessionMessageScanRequest,
+  ): Promise<SessionMessageScanPage>;
+  listTurns(sessionId: string): Promise<TurnRecord[]>;
+  appendMessage(sessionId: string, message: StoredMessage): Promise<void>;
+  appendMessages(sessionId: string, messages: StoredMessage[]): Promise<void>;
+  /** Commit the Session-list facts a durable message carries. */
+  commitMessageCatalogProjection(
+    sessionId: string,
+    message: UserMessage | AssistantMessage,
+  ): Promise<void>;
+  updateHeader(sessionId: string, patch: SessionHeaderPatch): Promise<SessionHeader>;
+  setFlagged(sessionId: string, isFlagged: boolean): Promise<void>;
+  rename(sessionId: string, name: string): Promise<void>;
+  setGeneratedTitleIfAbsent(sessionId: string, title: string): Promise<SessionHeader | null>;
+  remove(sessionId: string): Promise<void>;
+  close?(): Promise<void>;
+}
+
+/** Rebuildable ordering only; the message body remains in its original store. */
+export interface CoordinationTranscriptReference {
+  readonly source: 'legacy' | 'runtime';
+  readonly sourceSequence: number;
+}
+export interface CoordinationTranscriptIndexRecord extends CoordinationTranscriptReference {
+  readonly sequence: number;
+}
+export interface CoordinationTranscriptIndexState {
+  readonly highWater: number | null;
+  readonly legacy: number | null;
+  readonly runtime: number | null;
+}
+
+export interface SessionAuthorityStore extends SessionStore, MessageAdmissionStore {
+  readCoordinationTranscriptIndexState(): Promise<CoordinationTranscriptIndexState>;
+  appendCoordinationTranscriptIndex(
+    records: readonly CoordinationTranscriptReference[],
+  ): Promise<void>;
+  readCoordinationTranscriptIndex(request: {
+    direction: 'older' | 'newer';
+    throughSequence: number;
+    position: number;
+    limit: number;
+  }): Promise<readonly CoordinationTranscriptIndexRecord[]>;
+  /** Read a bounded set of durable messages at an inclusive transcript watermark. */
+  readTranscriptMessagesSnapshot(
+    sessionId: string,
+    request: SessionTranscriptMessageLookupRequest,
+  ): Promise<StoredMessage[]>;
+  /** Observe successful durable ledger appends. Listeners must not throw. */
+  subscribeTranscriptChanges(listener: (sessionId: string) => void): () => void;
+  /** Wait until the durable authority is ready for cross-domain transactions. */
+  ready(): Promise<void>;
+  /** Atomically create a Session from already-converted Maka raw messages. */
+  createImportedSession(
+    input: CreateSessionInput,
+    messages: readonly StoredMessage[],
+    externalOrigin: SessionExternalOrigin,
+  ): Promise<SessionHeader>;
+  /** Look up live published imports for a bounded page of source Sessions. */
+  lookupExternalSessionImports(
+    adapterId: string,
+    sourceSessionIds: readonly string[],
+    recentSessionIdLimit: number,
+  ): Promise<readonly ExternalSessionImportLookupResult[]>;
+  createSubagent(
+    input: CreateSessionInput,
+    initialBoundary?: ExecutionBoundary,
+  ): Promise<{ header: SessionHeader; created: boolean }>;
+  createAgentGraphOperator(
+    input: CreateSessionInput,
+    request: AgentGraphOperatorProvisionRequest,
+    expectedRevision: number,
+    initialBoundary?: ExecutionBoundary,
+  ): Promise<{ header: SessionHeader } & AgentGraphOperatorProvisionResult>;
+  readExecutionBoundary(sessionId: string): Promise<ExecutionBoundary>;
+  createSandboxBoundaryRequest(
+    input: CreateSandboxBoundaryRequest,
+  ): Promise<SandboxBoundaryRequest>;
+  readSandboxBoundaryRequest(
+    sessionId: string,
+    requestId: string,
+  ): Promise<SandboxBoundaryRequest | undefined>;
+  listPendingSandboxBoundaryRequests(sessionId: string): Promise<SandboxBoundaryRequest[]>;
+  /** Requests already closed against the user because the host restarted. */
+  listSandboxBoundaryRestartClosures(sessionId: string): Promise<SandboxBoundaryRequest[]>;
+  hasExplicitSandboxBoundaryDenial(
+    identities: readonly { sessionId: string; runId: string; turnId: string }[],
+  ): Promise<boolean>;
+  settleSandboxBoundaryRequest(
+    input: SettleSandboxBoundaryRequest,
+  ): Promise<SandboxBoundarySettlement>;
+  setExecutionBoundaryKind(
+    sessionId: string,
+    kind: 'managed' | 'bypass',
+    projection?: {
+      permissionMode: SessionHeader['permissionMode'];
+      labels?: readonly string[];
+    },
+  ): Promise<ExecutionBoundary>;
+  probeStableSessionCreate(
+    sessionId: string,
+    requestFingerprint: string,
+  ): Promise<ProbeStableSessionCreateResult>;
+  createStableSession(
+    request: CreateStableSessionRequest,
+    initialBoundary?: ExecutionBoundary,
+  ): Promise<CreateStableSessionResult>;
+  /**
+   * Commit the coordination linkage, target admission and optional target creation
+   * as one durable fact. Retry of the same operation returns its original result;
+   * conflicting identity reuse fails without changing either Session.
+   * Callers may dispatch the target only after this operation succeeds.
+   */
+  assignWorkHubMessage(
+    request: WorkHubMessageAssignmentRequest,
+  ): Promise<WorkHubMessageAssignmentResult>;
+  readWorkHubAssignment(actionId: string): Promise<WorkHubDelegationAssignedMessage | undefined>;
+  /** Newest active assignment first, across every requested target. */
+  readActiveWorkHubAssignmentsByTarget(
+    targetSessionIds: readonly string[],
+    maxAssignmentsPerTarget?: number,
+  ): Promise<readonly WorkHubDelegationAssignedMessage[]>;
+  readWorkHubReplacement(
+    delegationId: string,
+  ): Promise<WorkHubDelegationReplacementRequestedMessage | undefined>;
+  readWorkHubReplacementAbort(
+    delegationId: string,
+  ): Promise<WorkHubDelegationReplacementAbortedMessage | undefined>;
+  readWorkHubSupersession(
+    delegationId: string,
+  ): Promise<WorkHubDelegationSupersededMessage | undefined>;
+  readWorkHubStopRequest(
+    delegationId: string,
+  ): Promise<WorkHubDelegationStopRequestedMessage | undefined>;
+  readWorkHubStopResolution(
+    delegationId: string,
+  ): Promise<WorkHubDelegationStopResolvedMessage | undefined>;
+  /**
+   * Durably binds one action identity to one exact WorkHub operation before its
+   * effect. Survives removal of the target Session so a committed destructive
+   * claim can still converge afterwards.
+   */
+  claimWorkHubAction(claim: WorkHubActionClaim): Promise<WorkHubActionClaimOutcome>;
+  readWorkHubActionClaim(actionId: string): Promise<WorkHubActionClaim | undefined>;
+  discardStableConversationCopy(sessionId: string, requestFingerprint: string): Promise<boolean>;
+  listCatalogPage(
+    filter: SessionListFilter | undefined,
+    cursor: SessionCatalogPageCursor | undefined,
+    limit: number,
+    expectedRevision?: `sha256:${string}`,
+  ): Promise<SessionCatalogPageResult>;
+  readHeaderRecordSnapshot(sessionId: string): Promise<SessionHeaderSnapshot>;
+  readCatalogRecord(sessionId: string): Promise<SessionCatalogRecord>;
+  updateHeaderVersioned(
+    sessionId: string,
+    patch: SessionHeaderPatch,
+    expectedRevision: number,
+  ): Promise<SessionHeaderSnapshot>;
+  updateSessionConfiguration(
+    sessionId: string,
+    input: UpdateSessionConfigurationRequest,
+  ): Promise<SessionHeaderSnapshot>;
+  probeSessionRemoval(sessionId: string): Promise<ProbeSessionRemovalResult>;
+  setSessionsArchivedVersioned(
+    sessions: readonly VersionedSessionIdentity[],
+    isArchived: boolean,
+  ): Promise<SessionHeaderSnapshot[]>;
+  removeSessionsVersioned(
+    sessions: readonly VersionedSessionIdentity[],
+    archiveSessions?: readonly VersionedSessionIdentity[],
+  ): Promise<string[]>;
+  reconcileOrphanedAgentGraphRetirements(): Promise<string[]>;
+  listPendingSessionRetirementCleanupIds(sessionId?: string): Promise<string[]>;
+  completeSessionRetirementCleanup(sessionId: string): Promise<void>;
+}
diff --git a/packages/storage/src/session-store.ts b/packages/storage/src/session-store.ts
index 45810704c0..45f1c78dd4 100644
--- a/packages/storage/src/session-store.ts
+++ b/packages/storage/src/session-store.ts
@@ -17,18 +17,82 @@
  * under the License.
  */
 
+import {
+  type VersionedSessionIdentity,
+  SessionMetadataVersionConflictError,
+  isSafeSessionId,
+  assertSafeSessionId,
+  type SessionHeaderSnapshot,
+  type ProbeSessionRemovalResult,
+  type SessionCatalogRecord,
+  type SessionCatalogPageCursor,
+  EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_SOURCE_IDS,
+  EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_RECENT_SESSION_IDS,
+  type ExternalSessionImportLookupResult,
+  type SessionCatalogPageResult,
+  type CreateStableSessionRequest,
+  type WorkHubMessageAssignmentRequest,
+  type WorkHubMessageAssignmentResult,
+  type CreateStableSessionResult,
+  type ProbeStableSessionCreateResult,
+  type UpdateSessionConfigurationRequest,
+  type SessionTranscriptMessageLookupRequest,
+  type SessionMessageScanRequest,
+  type SessionMessageScanPage,
+  type CoordinationTranscriptReference,
+  type CoordinationTranscriptIndexRecord,
+  type CoordinationTranscriptIndexState,
+  type SessionAuthorityStore,
+} from './session-store-contract.js';
+export {
+  isSafeSessionId,
+  assertSafeSessionId,
+  SessionNotFoundError,
+  isSessionNotFoundError,
+  type SessionHeaderSnapshot,
+  type ProbeSessionRemovalResult,
+  type SessionCatalogRecord,
+  type SessionCatalogPageCursor,
+  EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_SOURCE_IDS,
+  EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_RECENT_SESSION_IDS,
+  type ExternalSessionImportLookupResult,
+  type SessionCatalogPageResult,
+  type CreateStableSessionRequest,
+  type WorkHubMessageAssignmentRequest,
+  type WorkHubMessageAssignmentResult,
+  type StableSessionCreateInput,
+  type CreateStableSessionResult,
+  type ProbeStableSessionCreateResult,
+  type UpdateSessionConfigurationRequest,
+  type SessionTranscriptStorageFragment,
+  type SessionTranscriptMessageLookupRequest,
+  type SessionMessageScanRequest,
+  type SessionMessageScanRecord,
+  type SessionMessageScanPage,
+  type SessionTranscriptPageRequest,
+  type SessionTranscriptStoragePage,
+  type SessionTranscriptRecordScanRequest,
+  type SessionTranscriptRecordScanPage,
+  type SessionTurnContribution,
+  type SessionTurnContributionPage,
+  type SessionTurnLandmark,
+  type SessionTurnLandmarkSnapshot,
+  type SessionStore,
+  type CoordinationTranscriptReference,
+  type CoordinationTranscriptIndexRecord,
+  type CoordinationTranscriptIndexState,
+  type SessionAuthorityStore,
+} from './session-store-contract.js';
+
 import { join } from 'node:path';
 import { createHash, randomUUID } from 'node:crypto';
 import {
   createSqliteSessionMetadataStore,
-  type SessionConfigurationMetadataUpdate,
   type SessionCatalogRevisionState,
   type SessionMetadataRecord,
   type SessionRemovalProbe,
-  SessionMetadataVersionConflictError,
   type SqliteSessionMetadataStore,
   type StableSessionCreateProbe,
-  type VersionedSessionIdentity,
 } from './sqlite-session-metadata-store.js';
 import { isDiscardableConversationCopy } from './session-conversation-copy.js';
 import {
@@ -81,7 +145,6 @@ import {
   type SessionRole,
   type StoredMessage,
   type TurnRecord,
-  type TurnStateMessage,
   type AssistantMessage,
   type UserMessage,
   type WorkHubDelegationAssignedMessage,
@@ -95,419 +158,11 @@ import {
 } from '@maka/core/session';
 import type {
   MarkMessagesHandedOffInput,
-  MessageAdmissionStore,
   PendingMessageAdmission,
 } from './message-admission-store.js';
 import { projectSessionCatalogMessages } from './session-message-projection.js';
 export { projectSessionCatalogMessages };
 
-const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
-
-export function isSafeSessionId(sessionId: string): boolean {
-  return SESSION_ID_PATTERN.test(sessionId);
-}
-
-export function assertSafeSessionId(sessionId: string): void {
-  if (!isSafeSessionId(sessionId)) throw new Error(`Invalid Session id: ${sessionId}`);
-}
-export class SessionNotFoundError extends Error {
-  readonly name = 'SessionNotFoundError';
-  readonly code = 'session_not_found';
-
-  constructor(readonly sessionId: string) {
-    super(`Session metadata not found: ${sessionId}`);
-  }
-}
-
-export function isSessionNotFoundError(error: unknown): error is SessionNotFoundError {
-  return error instanceof SessionNotFoundError;
-}
-
-export interface SessionHeaderSnapshot {
-  readonly header: SessionHeader;
-  readonly revision: number;
-  readonly committedAt: number;
-}
-
-export type ProbeSessionRemovalResult =
-  | { readonly kind: 'present'; readonly record: SessionHeaderSnapshot }
-  | { readonly kind: 'removed' }
-  | { readonly kind: 'absent' };
-
-export interface SessionCatalogRecord extends SessionHeaderSnapshot {
-  readonly activityAt: number;
-  readonly summary: SessionSummary;
-}
-
-export interface SessionCatalogPageCursor {
-  readonly activityAt: number;
-  readonly sessionId: string;
-}
-
-export const EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_SOURCE_IDS = 256;
-export const EXTERNAL_SESSION_IMPORT_LOOKUP_MAX_RECENT_SESSION_IDS = 16;
-
-export interface ExternalSessionImportLookupResult {
-  readonly sourceSessionId: string;
-  readonly livePublishedImportCount: number;
-  readonly recentSessionIds: readonly string[];
-}
-
-export type SessionCatalogPageResult =
-  | {
-      readonly kind: 'page';
-      readonly revision: `sha256:${string}`;
-      readonly records: readonly SessionCatalogRecord[];
-      readonly hasMore: boolean;
-    }
-  | {
-      readonly kind: 'revision_changed';
-      readonly expectedRevision: `sha256:${string}`;
-      readonly actualRevision: `sha256:${string}`;
-    };
-
-export interface CreateStableSessionRequest {
-  readonly sessionId: string;
-  readonly requestFingerprint: string;
-  readonly input: StableSessionCreateInput;
-}
-
-export interface WorkHubMessageAssignmentRequest {
-  readonly assignment: WorkHubDelegationAssignedMessage;
-  readonly admission: PendingMessageAdmission;
-  /** Present exactly when this assignment atomically supersedes an earlier link. */
-  readonly supersession?: WorkHubDelegationSupersededMessage;
-  /** Present exactly when the assignment creates its target Session. */
-  readonly create?: CreateStableSessionRequest;
-}
-
-export interface WorkHubMessageAssignmentResult {
-  readonly kind: 'assigned' | 'existing';
-  readonly targetCreated: boolean;
-  readonly assignment: WorkHubDelegationAssignedMessage;
-}
-
-export type StableSessionCreateInput = CreateSessionInput & {
-  readonly conversationCopy?: SessionConversationCopy;
-  readonly role?: SessionRole;
-};
-
-export type CreateStableSessionResult =
-  | { readonly kind: 'created'; readonly record: SessionHeaderSnapshot }
-  | { readonly kind: 'existing'; readonly record: SessionHeaderSnapshot }
-  | {
-      readonly kind: 'conflict';
-      readonly reason: 'identity_mismatch' | 'removed';
-    };
-
-export type ProbeStableSessionCreateResult =
-  | { readonly kind: 'absent' }
-  | { readonly kind: 'existing'; readonly record: SessionHeaderSnapshot }
-  | {
-      readonly kind: 'conflict';
-      readonly reason: 'identity_mismatch' | 'removed';
-    };
-
-export type UpdateSessionConfigurationRequest = SessionConfigurationMetadataUpdate;
-
-export interface SessionTranscriptStorageFragment {
-  readonly sequence: number;
-  readonly byteOffset: number;
-  readonly totalBytes: number;
-  readonly payloadDigest: `sha256:${string}` | null;
-  readonly data: Buffer;
-}
-
-export interface SessionTranscriptMessageLookupRequest {
-  readonly messageIds: readonly string[];
-  readonly throughSequence: number | null;
-  readonly maxBytes: number;
-  readonly maxMessages: number;
-}
-
-/**
- * One page of a Session's legacy rows, for the converter that lifts them onto
- * the ledger and for the WorkHub Coordination Session, whose transcript no run
- * produces and so has no ledger to read.
- */
-export interface SessionMessageScanRequest {
-  /** Exclusive lower bound; omit to start at the first row. */
-  readonly afterSequence?: number;
-  /**
-   * Walk towards older rows instead, from this exclusive upper bound. Records
-   * then come back newest first, so the byte budget truncates at the older end,
-   * which is the end the walk is heading for. Pass at most one bound.
-   */
-  readonly beforeSequence?: number;
-  readonly maxStoredBytes: number;
-  readonly maxMessages: number;
-}
-
-export interface SessionMessageScanRecord {
-  readonly sequence: number;
-  readonly message: StoredMessage;
-}
-
-export interface SessionMessageScanPage {
-  readonly records: readonly SessionMessageScanRecord[];
-  /**
-   * The Session's last legacy sequence. It rides along with every page so the
-   * converter can place a turn relative to the whole transcript without a read
-   * that is proportional to it.
-   */
-  readonly highWaterSequence: number | null;
-}
-
-export interface SessionTranscriptPageRequest {
-  readonly direction: 'older' | 'newer';
-  /** Inclusive durable high-water mark. Omit only for the first read. */
-  readonly throughSequence?: number | null;
-  /** Inclusive sequence position for this read. Defaults to the watermark edge. */
-  readonly position?: number;
-  /** Continuation byte offset within position. */
-  readonly byteOffset?: number;
-  readonly maxBytes: number;
-  readonly maxMessages: number;
-}
-
-export interface SessionTranscriptStoragePage {
-  readonly throughSequence: number | null;
-  /** Returned in traversal order for the requested direction. */
-  readonly fragments: readonly SessionTranscriptStorageFragment[];
-  readonly rawBytes: number;
-  readonly next: {
-    readonly position: number;
-    readonly byteOffset: number | null;
-  } | null;
-}
-
-export interface SessionTranscriptRecordScanRequest {
-  readonly direction: 'older' | 'newer';
-  readonly throughSequence?: number | null;
-  readonly position?: number;
-  readonly maxStoredBytes: number;
-  readonly maxMessages: number;
-}
-
-export interface SessionTranscriptRecordScanPage {
-  readonly throughSequence: number | null;
-  readonly records: readonly { readonly sequence: number; readonly message: StoredMessage }[];
-  readonly nextPosition: number | null;
-}
-
-export interface SessionTurnContribution {
-  readonly turnId: string;
-  readonly firstSequence: number;
-  readonly latestState: {
-    readonly sequence: number;
-    readonly message: TurnStateMessage;
-  } | null;
-  readonly userPromptPreview: string | null;
-}
-
-export interface SessionTurnContributionPage {
-  readonly throughSequence: number | null;
-  readonly contributions: readonly SessionTurnContribution[];
-  readonly nextPosition: number | null;
-}
-
-export interface SessionTurnLandmark {
-  readonly turnId: string;
-  readonly sequence: number;
-  readonly label: string;
-}
-
-export interface SessionTurnLandmarkSnapshot {
-  readonly throughSequence: number | null;
-  readonly landmarks: readonly SessionTurnLandmark[];
-}
-
-export interface SessionStore {
-  create(input: CreateSessionInput, initialBoundary?: ExecutionBoundary): Promise<SessionHeader>;
-  list(filter?: SessionListFilter): Promise<SessionSummary[]>;
-  /** Enumerate durable metadata without reading transcript bodies. */
-  listHeaders(): Promise<SessionHeader[]>;
-  listForRecovery(): Promise<SessionHeader[]>;
-  /** Read only the durable header without triggering connection-lock self-healing. */
-  readHeaderSnapshot(sessionId: string): Promise<SessionHeader>;
-  readMessagesSnapshot(sessionId: string): Promise<StoredMessage[]>;
-  readTranscriptHighWaterSnapshot(sessionId: string): Promise<number | null>;
-  listTurnsSnapshot(sessionId: string): Promise<TurnRecord[]>;
-  readHeader(sessionId: string): Promise<SessionHeader>;
-  readMessages(sessionId: string): Promise<StoredMessage[]>;
-  readMessagesAfter(
-    sessionId: string,
-    request: SessionMessageScanRequest,
-  ): Promise<SessionMessageScanPage>;
-  listTurns(sessionId: string): Promise<TurnRecord[]>;
-  appendMessage(sessionId: string, message: StoredMessage): Promise<void>;
-  appendMessages(sessionId: string, messages: StoredMessage[]): Promise<void>;
-  /** Commit the Session-list facts a durable message carries. */
-  commitMessageCatalogProjection(
-    sessionId: string,
-    message: UserMessage | AssistantMessage,
-  ): Promise<void>;
-  updateHeader(sessionId: string, patch: SessionHeaderPatch): Promise<SessionHeader>;
-  setFlagged(sessionId: string, isFlagged: boolean): Promise<void>;
-  rename(sessionId: string, name: string): Promise<void>;
-  setGeneratedTitleIfAbsent(sessionId: string, title: string): Promise<SessionHeader | null>;
-  remove(sessionId: string): Promise<void>;
-  close?(): Promise<void>;
-}
-
-/** Rebuildable ordering only; the message body remains in its original store. */
-export interface CoordinationTranscriptReference {
-  readonly source: 'legacy' | 'runtime';
-  readonly sourceSequence: number;
-}
-export interface CoordinationTranscriptIndexRecord extends CoordinationTranscriptReference {
-  readonly sequence: number;
-}
-export interface CoordinationTranscriptIndexState {
-  readonly highWater: number | null;
-  readonly legacy: number | null;
-  readonly runtime: number | null;
-}
-
-export interface SessionAuthorityStore extends SessionStore, MessageAdmissionStore {
-  readCoordinationTranscriptIndexState(): Promise<CoordinationTranscriptIndexState>;
-  appendCoordinationTranscriptIndex(
-    records: readonly CoordinationTranscriptReference[],
-  ): Promise<void>;
-  readCoordinationTranscriptIndex(request: {
-    direction: 'older' | 'newer';
-    throughSequence: number;
-    position: number;
-    limit: number;
-  }): Promise<readonly CoordinationTranscriptIndexRecord[]>;
-  /** Read a bounded set of durable messages at an inclusive transcript watermark. */
-  readTranscriptMessagesSnapshot(
-    sessionId: string,
-    request: SessionTranscriptMessageLookupRequest,
-  ): Promise<StoredMessage[]>;
-  /** Observe successful durable ledger appends. Listeners must not throw. */
-  subscribeTranscriptChanges(listener: (sessionId: string) => void): () => void;
-  /** Wait until the SQLite authority is ready for cross-domain transactions. */
-  ready(): Promise<void>;
-  /** Atomically create a Session from already-converted Maka raw messages. */
-  createImportedSession(
-    input: CreateSessionInput,
-    messages: readonly StoredMessage[],
-    externalOrigin: SessionExternalOrigin,
-  ): Promise<SessionHeader>;
-  /** Look up live published imports for a bounded page of source Sessions. */
-  lookupExternalSessionImports(
-    adapterId: string,
-    sourceSessionIds: readonly string[],
-    recentSessionIdLimit: number,
-  ): Promise<readonly ExternalSessionImportLookupResult[]>;
-  createSubagent(
-    input: CreateSessionInput,
-    initialBoundary?: ExecutionBoundary,
-  ): Promise<{ header: SessionHeader; created: boolean }>;
-  createAgentGraphOperator(
-    input: CreateSessionInput,
-    request: AgentGraphOperatorProvisionRequest,
-    expectedRevision: number,
-    initialBoundary?: ExecutionBoundary,
-  ): Promise<{ header: SessionHeader } & AgentGraphOperatorProvisionResult>;
-  readExecutionBoundary(sessionId: string): Promise<ExecutionBoundary>;
-  createSandboxBoundaryRequest(
-    input: CreateSandboxBoundaryRequest,
-  ): Promise<SandboxBoundaryRequest>;
-  readSandboxBoundaryRequest(
-    sessionId: string,
-    requestId: string,
-  ): Promise<SandboxBoundaryRequest | undefined>;
-  listPendingSandboxBoundaryRequests(sessionId: string): Promise<SandboxBoundaryRequest[]>;
-  /** Requests already closed against the user because the host restarted. */
-  listSandboxBoundaryRestartClosures(sessionId: string): Promise<SandboxBoundaryRequest[]>;
-  hasExplicitSandboxBoundaryDenial(
-    identities: readonly { sessionId: string; runId: string; turnId: string }[],
-  ): Promise<boolean>;
-  settleSandboxBoundaryRequest(
-    input: SettleSandboxBoundaryRequest,
-  ): Promise<SandboxBoundarySettlement>;
-  setExecutionBoundaryKind(
-    sessionId: string,
-    kind: 'managed' | 'bypass',
-    projection?: {
-      permissionMode: SessionHeader['permissionMode'];
-      labels?: readonly string[];
-    },
-  ): Promise<ExecutionBoundary>;
-  probeStableSessionCreate(
-    sessionId: string,
-    requestFingerprint: string,
-  ): Promise<ProbeStableSessionCreateResult>;
-  createStableSession(
-    request: CreateStableSessionRequest,
-    initialBoundary?: ExecutionBoundary,
-  ): Promise<CreateStableSessionResult>;
-  /** Atomically persist a WorkHub linkage and the target Message admission. */
-  assignWorkHubMessage(
-    request: WorkHubMessageAssignmentRequest,
-  ): Promise<WorkHubMessageAssignmentResult>;
-  readWorkHubAssignment(actionId: string): Promise<WorkHubDelegationAssignedMessage | undefined>;
-  /** Newest active assignment first, across every requested target. */
-  readActiveWorkHubAssignmentsByTarget(
-    targetSessionIds: readonly string[],
-    maxAssignmentsPerTarget?: number,
-  ): Promise<readonly WorkHubDelegationAssignedMessage[]>;
-  readWorkHubReplacement(
-    delegationId: string,
-  ): Promise<WorkHubDelegationReplacementRequestedMessage | undefined>;
-  readWorkHubReplacementAbort(
-    delegationId: string,
-  ): Promise<WorkHubDelegationReplacementAbortedMessage | undefined>;
-  readWorkHubSupersession(
-    delegationId: string,
-  ): Promise<WorkHubDelegationSupersededMessage | undefined>;
-  readWorkHubStopRequest(
-    delegationId: string,
-  ): Promise<WorkHubDelegationStopRequestedMessage | undefined>;
-  readWorkHubStopResolution(
-    delegationId: string,
-  ): Promise<WorkHubDelegationStopResolvedMessage | undefined>;
-  /**
-   * Durably binds one action identity to one exact WorkHub operation before its
-   * effect. Survives removal of the target Session so a committed destructive
-   * claim can still converge afterwards.
-   */
-  claimWorkHubAction(claim: WorkHubActionClaim): Promise<WorkHubActionClaimOutcome>;
-  readWorkHubActionClaim(actionId: string): Promise<WorkHubActionClaim | undefined>;
-  discardStableConversationCopy(sessionId: string, requestFingerprint: string): Promise<boolean>;
-  listCatalogPage(
-    filter: SessionListFilter | undefined,
-    cursor: SessionCatalogPageCursor | undefined,
-    limit: number,
-    expectedRevision?: `sha256:${string}`,
-  ): Promise<SessionCatalogPageResult>;
-  readHeaderRecordSnapshot(sessionId: string): Promise<SessionHeaderSnapshot>;
-  readCatalogRecord(sessionId: string): Promise<SessionCatalogRecord>;
-  updateHeaderVersioned(
-    sessionId: string,
-    patch: SessionHeaderPatch,
-    expectedRevision: number,
-  ): Promise<SessionHeaderSnapshot>;
-  updateSessionConfiguration(
-    sessionId: string,
-    input: UpdateSessionConfigurationRequest,
-  ): Promise<SessionHeaderSnapshot>;
-  probeSessionRemoval(sessionId: string): Promise<ProbeSessionRemovalResult>;
-  setSessionsArchivedVersioned(
-    sessions: readonly VersionedSessionIdentity[],
-    isArchived: boolean,
-  ): Promise<SessionHeaderSnapshot[]>;
-  removeSessionsVersioned(
-    sessions: readonly VersionedSessionIdentity[],
-    archiveSessions?: readonly VersionedSessionIdentity[],
-  ): Promise<string[]>;
-  reconcileOrphanedAgentGraphRetirements(): Promise<string[]>;
-  listPendingSessionRetirementCleanupIds(sessionId?: string): Promise<string[]>;
-  completeSessionRetirementCleanup(sessionId: string): Promise<void>;
-}
-
 export function createSessionStore(workspaceRoot: string): SessionAuthorityStore {
   return new SqliteSessionStore(workspaceRoot);
 }
diff --git a/packages/storage/src/sqlite-runtime-store.ts b/packages/storage/src/sqlite-runtime-store.ts
index 292090846a..80985e6339 100644
--- a/packages/storage/src/sqlite-runtime-store.ts
+++ b/packages/storage/src/sqlite-runtime-store.ts
@@ -17,6 +17,21 @@
  * under the License.
  */
 
+import type {
+  CommitToolPreparedInput,
+  CommitToolOutcomeInput,
+  ToolCommitResult,
+  SessionRuntimeEventEntry,
+  ToolOperationRecord,
+} from './runtime-event-store-contract.js';
+export type {
+  CommitToolPreparedInput,
+  CommitToolOutcomeInput,
+  ToolCommitResult,
+  SessionRuntimeEventEntry,
+  ToolOperationRecord,
+} from './runtime-event-store-contract.js';
+
 import { createHash } from 'node:crypto';
 import { mkdirSync } from 'node:fs';
 import { createRequire } from 'node:module';
@@ -204,61 +219,15 @@ export interface SqliteRuntimeStoreOptions {
   databaseLease?: OperationalStateDatabaseLease;
 }
 
-export interface CommitToolPreparedInput {
-  operationId: string;
-  journalEventId: string;
-  runtimeEvent: RuntimeEvent;
-  dispatchRuntimeEvent: RuntimeEvent;
-  providerToolCallId: string;
-  toolName: string;
-  canonicalArgsHash: string;
-  recoveryMode: ToolRecoveryMode;
-  committedAt: number;
-}
-
-export interface CommitToolOutcomeInput {
-  operationId: string;
-  journalEventId: string;
-  runtimeEvent: RuntimeEvent;
-  committedAt: number;
-}
-
-export interface ToolCommitResult {
-  created: boolean;
-  runtimeEventSeq: number;
-}
-
 export interface RuntimeEventBatchImportResult {
   created: boolean[];
 }
 
-/** Storage-owned, immutable append position for an Event within one Session. */
-export interface SessionRuntimeEventEntry {
-  readonly ordinal: number;
-  readonly event: RuntimeEvent;
-}
-
 export interface ToolProjectionRebuildResult {
   operations: number;
   journalEvents: number;
 }
 
-export interface ToolOperationRecord {
-  operationId: string;
-  invocationId: string;
-  runId: string;
-  turnId: string;
-  providerToolCallId: string;
-  toolName: string;
-  canonicalArgsHash: string;
-  recoveryMode: ToolRecoveryMode;
-  currentState: 'prepared' | 'outcome_committed' | 'recovery_completed' | 'recovery_parked';
-  callEventId: string;
-  dispatchEventId?: string;
-  resultEventId?: string;
-  version: number;
-}
-
 export interface ToolJournalEventRecord {
   journalEventId: string;
   operationId: string;
diff --git a/packages/storage/src/sqlite-session-metadata-store.ts b/packages/storage/src/sqlite-session-metadata-store.ts
index 5b31404958..d7de86b845 100644
--- a/packages/storage/src/sqlite-session-metadata-store.ts
+++ b/packages/storage/src/sqlite-session-metadata-store.ts
@@ -17,6 +17,19 @@
  * under the License.
  */
 
+import {
+  SessionMetadataConflictError,
+  SessionMetadataVersionConflictError,
+  type VersionedSessionIdentity,
+  type SessionConfigurationMetadataUpdate,
+} from './session-store-contract.js';
+export {
+  SessionMetadataConflictError,
+  SessionMetadataVersionConflictError,
+  type VersionedSessionIdentity,
+  type SessionConfigurationMetadataUpdate,
+} from './session-store-contract.js';
+
 import { createRequire } from 'node:module';
 import { createHash } from 'node:crypto';
 import { dirname, resolve } from 'node:path';
@@ -121,6 +134,7 @@ import {
   messageContentDigest,
   messageContentsEqual,
   normalizeMessageContent,
+  type MessageContent,
 } from '@maka/core/events';
 import {
   type AgentGraphIntentAdmissionSnapshot,
@@ -138,8 +152,6 @@ import {
 import { type SessionListFilter } from '@maka/core/runtime-inputs';
 import {
   assertSafeSessionId,
-  decodePersistedSessionHeader,
-  normalizeSessionHeader,
   SessionNotFoundError,
   type ExternalSessionImportLookupResult,
   type CoordinationTranscriptReference,
@@ -149,7 +161,8 @@ import {
   type SessionMessageScanRecord,
   type SessionMessageScanRequest,
   type SessionTranscriptMessageLookupRequest,
-} from './session-store.js';
+} from './session-store-contract.js';
+import { decodePersistedSessionHeader, normalizeSessionHeader } from './session-store.js';
 import {
   isDiscardableConversationCopy,
   isValidConversationCopyTransition,
@@ -336,11 +349,6 @@ export interface SessionAuthoritySnapshot {
   boundary: ExecutionBoundary;
 }
 
-export interface VersionedSessionIdentity {
-  readonly sessionId: string;
-  readonly expectedVersion: number;
-}
-
 export type SessionRemovalProbe =
   | { readonly kind: 'present'; readonly record: SessionMetadataRecord }
   | { readonly kind: 'removed' }
@@ -386,37 +394,11 @@ export type StableSessionMetadataCreateResult =
       readonly reason: 'identity_mismatch' | 'removed';
     };
 
-export interface SessionConfigurationMetadataUpdate {
-  readonly expectedVersion: number;
-  readonly configuration: {
-    readonly backend: SessionHeader['backend'];
-    readonly llmConnectionId: string;
-    readonly llmConnectionSlug: string;
-    readonly connectionLocked: boolean;
-    readonly model: string;
-    readonly thinkingLevel: SessionHeader['thinkingLevel'];
-    readonly permissionMode: SessionHeader['permissionMode'];
-    readonly collaborationMode: NonNullable<SessionHeader['collaborationMode']>;
-    readonly orchestrationMode: NonNullable<SessionHeader['orchestrationMode']>;
-    readonly labels: readonly string[];
-  };
-  readonly lifecycle:
-    | { readonly kind: 'preserve' }
-    | {
-        readonly kind: 'clear_connection_block';
-        readonly statusUpdatedAt: number;
-      };
-}
-
 export interface IdempotentAgentGraphOperatorMetadataResult
   extends AgentGraphOperatorProvisionResult {
   record: SessionMetadataRecord;
 }
 
-export class SessionMetadataConflictError extends Error {
-  readonly name: string = 'SessionMetadataConflictError';
-}
-
 export class StoredSessionMessageIncompatibleError extends Error {
   readonly name = 'StoredSessionMessageIncompatibleError';
   readonly code = 'stored_session_message_incompatible';
@@ -430,20 +412,6 @@ export class StoredSessionMessageIncompatibleError extends Error {
   }
 }
 
-export class SessionMetadataVersionConflictError extends SessionMetadataConflictError {
-  readonly name = 'SessionMetadataVersionConflictError';
-
-  constructor(
-    readonly sessionId: string,
-    readonly expectedVersion: number,
-    readonly actualVersion: number,
-  ) {
-    super(
-      `Session metadata version conflict for ${sessionId}: expected ${expectedVersion}, found ${actualVersion}`,
-    );
-  }
-}
-
 export class AgentGraphIntentClaimConflictError extends SessionMetadataConflictError {
   readonly name = 'AgentGraphIntentClaimConflictError';
 }
@@ -1763,10 +1731,7 @@ export class SqliteSessionMetadataStore {
       assignment.id !== `wha_${suffix}` ||
       assignment.targetMessageId !== `whm_${suffix}` ||
       assignment.delegationId !== `whd_${suffix}` ||
-      !messageContentsEqual(
-        admission.content,
-        normalizeMessageContent({ text: assignment.userText }),
-      ) ||
+      !workHubAssignmentContentMatches(assignment, admission.content) ||
       admission.submittedContentDigest !== messageContentDigest(admission.content) ||
       admission.submittedPlacement !== 'current_turn' ||
       admission.placement !== 'current_turn' ||
@@ -6523,6 +6488,43 @@ function isWorkHubActionOperation(value: unknown): value is WorkHubActionOperati
   );
 }
 
+/**
+ * The Host copies selected artifacts before the transaction. The coordination
+ * fact retains the source references; the admission must carry the same ordered
+ * attachment metadata, now owned by the target. Only the storage reference is
+ * allowed to change. The Artifact authority validates/copies the actual bytes.
+ */
+function workHubAssignmentContentMatches(
+  assignment: WorkHubDelegationAssignedMessage,
+  content: MessageContent,
+): boolean {
+  const source = assignment.attachments ?? [];
+  const target = content.attachments ?? [];
+  if (source.length !== target.length) return false;
+  for (let index = 0; index < source.length; index++) {
+    const from = source[index]!;
+    const to = target[index]!;
+    if (
+      from.ref.kind !== 'session_file' ||
+      from.ref.sessionId !== WORKHUB_COORDINATION_SESSION_ID ||
+      to.ref.kind !== 'session_file' ||
+      to.ref.sessionId !== assignment.targetSessionId
+    ) {
+      return false;
+    }
+  }
+  return messageContentsEqual(
+    content,
+    normalizeMessageContent({
+      text: assignment.userText,
+      attachments: source.map((attachment, index) => ({
+        ...attachment,
+        ref: target[index]!.ref,
+      })),
+    }),
+  );
+}
+
 function sameWorkHubAssignmentRequest(
   existing: WorkHubDelegationAssignedMessage,
   requested: WorkHubDelegationAssignedMessage,
@@ -6535,6 +6537,7 @@ function sameWorkHubAssignmentRequest(
       targetSessionId: existing.targetSessionId,
       disposition: existing.disposition,
       userText: existing.userText,
+      attachments: existing.attachments ?? [],
       create: existing.create,
       replacesActionId: existing.replacesActionId,
       replacesDelegationId: existing.replacesDelegationId,
@@ -6546,6 +6549,7 @@ function sameWorkHubAssignmentRequest(
       targetSessionId: requested.targetSessionId,
       disposition: requested.disposition,
       userText: requested.userText,
+      attachments: requested.attachments ?? [],
       create: requested.create,
       replacesActionId: requested.replacesActionId,
       replacesDelegationId: requested.replacesDelegationId,


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