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

(maka) 05/06: refactor(runtime): move runtime notes onto the ledger and retire the rest

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

Astro-Han pushed a commit to branch refactor/4791-single-transcript-authority
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 38330078576dd692f1c4dec6776e8e8d7dda4684
Author: AstroHan <le...@outlook.com>
AuthorDate: Sun Sep 6 03:10:45 2026 +0800

    refactor(runtime): move runtime notes onto the ledger and retire the rest
    
    A system note stated one of two things. The ones that describe what
    happened inside an invocation — compaction, context pressure, the step
    cap — are facts of that invocation, and now live where its facts live:
    the RuntimeEvent ledger, through `AgentRun.recordSystemNote` and a
    `recordSystemNote` hook the backend reaches like its other recorders.
    They stay `modelVisibility: 'hidden'`, so the reader sees them and the
    provider never replays them.
    
    The others said something that already had an owner. The Session header
    carries the mode, the model and the copy lineage; the invocation's
    opening fact carries its own configuration; the terminal event carries
    the abort and its source. `session_start`, `session_resume`,
    `mode_change`, `model_change`, `error` and `abort` only wrote those
    facts a second time, into rows nothing rendered. Their write sites are
    gone; the kinds stay decodable so legacy transcripts still read.
    
    Two readers depended on `session_start` as a position marker for "this
    revision copy admitted a turn of its own". The admission ledger answers
    that directly — a copy clones history but never admissions — and the
    Host revision coordinator, which already reads it, settles every
    `preparing` copy at recovery before SessionManager's duplicate check
    ever ran.
    
    Generated-by: Claude Code
---
 packages/cli/src/pi-transcript.ts                  |  15 +--
 packages/core/src/runtime-event.ts                 |   8 +-
 packages/core/src/session.ts                       |  74 ++++++---------
 .../session-revision-two-client-uds.test.ts        |   2 +-
 .../src/server/execution-model-composition.ts      |   3 +
 .../src/server/session-revision-coordinator.ts     |  73 ++------------
 .../__tests__/mid-turn-capacity-backend.test.ts    |  11 +++
 .../__tests__/overflow-reactive-recovery.test.ts   |  11 +++
 .../__tests__/runtime-kernel-interaction.test.ts   |  10 --
 .../runtime/src/__tests__/session-manager.test.ts  |  38 ++------
 packages/runtime/src/agent-run.ts                  |  40 ++++----
 packages/runtime/src/ai-sdk-backend.ts             |  12 ++-
 packages/runtime/src/ai-sdk-turn.ts                | 105 +++++++--------------
 packages/runtime/src/runtime-event-backfill.ts     |   4 +-
 packages/runtime/src/runtime-kernel.ts             |  37 ++------
 packages/runtime/src/session-manager.ts            | 104 ++++----------------
 16 files changed, 174 insertions(+), 373 deletions(-)

diff --git a/packages/cli/src/pi-transcript.ts b/packages/cli/src/pi-transcript.ts
index d32a711b72..d7af4da7df 100644
--- a/packages/cli/src/pi-transcript.ts
+++ b/packages/cli/src/pi-transcript.ts
@@ -31,6 +31,7 @@ import type {
 } from '@maka/core/events';
 import {
   deriveTurnRecords,
+  isRuntimeSystemNoteKind,
   STEP_LIMIT_NOTICE_TEXT,
   type StoredMessage,
   type SystemNoteMessage,
@@ -1344,14 +1345,10 @@ function tokenDelta(before: number | undefined, after: number | undefined): numb
 }
 
 function systemNoteText(message: SystemNoteMessage): string | undefined {
+  // Retired kinds are still decoded off legacy transcript rows, and none of
+  // them ever had a line here worth reading.
+  if (!isRuntimeSystemNoteKind(message.kind)) return undefined;
   switch (message.kind) {
-    case 'session_start':
-    case 'session_resume':
-      return undefined;
-    case 'mode_change':
-      return 'Permission mode changed.';
-    case 'model_change':
-      return 'Model changed.';
     case 'context_compacted':
       return 'Context compacted to keep this task within the model window.';
     case 'context_compaction_failed_open':
@@ -1408,10 +1405,6 @@ function systemNoteText(message: SystemNoteMessage): string | undefined {
     }
     case 'step_limit':
       return STEP_LIMIT_NOTICE_TEXT;
-    case 'error':
-      return 'Session recorded an error.';
-    case 'abort':
-      return 'Session was stopped.';
   }
 }
 
diff --git a/packages/core/src/runtime-event.ts b/packages/core/src/runtime-event.ts
index 3344b310e0..863679e82e 100644
--- a/packages/core/src/runtime-event.ts
+++ b/packages/core/src/runtime-event.ts
@@ -62,9 +62,9 @@ import {
 } from './orchestration.js';
 import { isToolMode, type ToolMode } from './tool-mode.js';
 import {
-  isTurnScopedSystemNoteKind,
+  isRuntimeSystemNoteKind,
   type PersistedBackendKind,
-  type TurnScopedSystemNoteKind,
+  type RuntimeSystemNoteKind,
 } from './session.js';
 import { decodeTurnOrigin, type TurnOrigin } from './turn-origin.js';
 import type { UserQuestionRequest } from './user-question.js';
@@ -232,7 +232,7 @@ export interface RuntimeEventFunctionResponseContent {
  */
 export interface RuntimeEventSystemNoteContent {
   kind: 'system_note';
-  note: TurnScopedSystemNoteKind;
+  note: RuntimeSystemNoteKind;
   /** Shape depends on `note`, exactly as it does on the transcript row. */
   data?: unknown;
 }
@@ -1058,7 +1058,7 @@ function isRuntimeEventContent(value: unknown): value is RuntimeEventContent {
       return (
         hasExactShape(value, SYSTEM_NOTE_CONTENT_SHAPE) &&
         typeof value.note === 'string' &&
-        isTurnScopedSystemNoteKind(value.note)
+        isRuntimeSystemNoteKind(value.note)
       );
     case 'invocation_opened':
       return isRuntimeInvocationOpened(value);
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index 936ac762c4..a40de3d654 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -789,20 +789,15 @@ export function userFacingText(message: Pick<UserMessage, 'text' | 'displayText'
   return message.displayText ?? message.text;
 }
 
-const USER_VISIBLE_SESSION_SYSTEM_NOTES = new Set([
-  'context_compacted',
-  'context_compaction_failed_open',
-  'context_provider_dropping',
-  'context_window_suggestion',
-  'context_window_overrun',
-  'context_reported_window_exceeded',
-  'context_overflow_after_compaction',
-  'step_limit',
-]);
-
-/** Closed policy for system notes that are part of the user-visible transcript. */
+/**
+ * Closed policy for system notes that are part of the user-visible transcript.
+ *
+ * It is the same list as the notes the runtime writes, and that is the point: a
+ * note exists to tell the reader something happened to their turn. One nothing
+ * rendered was a fact with an owner elsewhere, written twice.
+ */
 export function isUserVisibleSessionSystemNote(kind: string): boolean {
-  return USER_VISIBLE_SESSION_SYSTEM_NOTES.has(kind);
+  return isRuntimeSystemNoteKind(kind);
 }
 
 export interface AssistantMessage {
@@ -1148,14 +1143,10 @@ export interface TurnRecord {
 }
 
 /**
- * Every note kind a transcript can carry.
- *
- * The list is split by who owns the fact, not by how it renders. A turn-scoped
- * note is part of what one invocation did, so the RuntimeEvent ledger records
- * it; a session-scoped note happens between turns, where there is no invocation
- * to belong to, and the Session transcript records it.
+ * The notes the runtime writes: things that happened inside one invocation and
+ * are part of what that invocation did. Their record is its RuntimeEvent ledger.
  */
-export const TURN_SCOPED_SYSTEM_NOTE_KINDS = [
+export const RUNTIME_SYSTEM_NOTE_KINDS = [
   'context_compacted',
   'context_compaction_failed_open',
   'context_provider_dropping',
@@ -1164,30 +1155,35 @@ export const TURN_SCOPED_SYSTEM_NOTE_KINDS = [
   'context_reported_window_exceeded',
   'context_overflow_after_compaction',
   'step_limit',
-  'error',
-  'abort',
 ] as const;
 
-export const SESSION_SCOPED_SYSTEM_NOTE_KINDS = [
+/**
+ * Notes only legacy transcripts carry, still decoded so those rows stay
+ * readable. Each stated a fact that already had an owner — the Session header
+ * and the invocation's own opening fact hold the mode, the model and the copy
+ * lineage; the terminal event holds the abort and its source — so writing them
+ * a second time bought a row nothing rendered.
+ */
+export const RETIRED_SYSTEM_NOTE_KINDS = [
   'session_start',
   'session_resume',
   'mode_change',
   'model_change',
+  'error',
+  'abort',
 ] as const;
 
-export type TurnScopedSystemNoteKind = (typeof TURN_SCOPED_SYSTEM_NOTE_KINDS)[number];
-export type SystemNoteKind =
-  | TurnScopedSystemNoteKind
-  | (typeof SESSION_SCOPED_SYSTEM_NOTE_KINDS)[number];
+export type RuntimeSystemNoteKind = (typeof RUNTIME_SYSTEM_NOTE_KINDS)[number];
+export type SystemNoteKind = RuntimeSystemNoteKind | (typeof RETIRED_SYSTEM_NOTE_KINDS)[number];
 
-export function isTurnScopedSystemNoteKind(kind: string): kind is TurnScopedSystemNoteKind {
-  return (TURN_SCOPED_SYSTEM_NOTE_KINDS as readonly string[]).includes(kind);
+export function isRuntimeSystemNoteKind(kind: string): kind is RuntimeSystemNoteKind {
+  return (RUNTIME_SYSTEM_NOTE_KINDS as readonly string[]).includes(kind);
 }
 
 export interface SystemNoteMessage {
   type: 'system_note';
   id: string;
-  /** Session-level notes omit turnId. */
+  /** Retired session-level notes omit turnId. */
   turnId?: string;
   ts: number;
   kind: SystemNoteKind;
@@ -1425,21 +1421,9 @@ const ASSISTANT_THINKING_SHAPE = defineObjectShape<AssistantThinking>()(
   ['text'],
   ['signature', 'providerOptions', 'parts'],
 );
-const SYSTEM_NOTE_KINDS = new Set([
-  'session_start',
-  'session_resume',
-  'mode_change',
-  'model_change',
-  'context_compacted',
-  'context_compaction_failed_open',
-  'context_provider_dropping',
-  'context_window_suggestion',
-  'context_window_overrun',
-  'context_reported_window_exceeded',
-  'context_overflow_after_compaction',
-  'step_limit',
-  'error',
-  'abort',
+const SYSTEM_NOTE_KINDS = new Set<string>([
+  ...RUNTIME_SYSTEM_NOTE_KINDS,
+  ...RETIRED_SYSTEM_NOTE_KINDS,
 ]);
 
 export function decodeCanonicalMessage(value: unknown): StoredMessage {
diff --git a/packages/runtime-host/src/__tests__/session-revision-two-client-uds.test.ts b/packages/runtime-host/src/__tests__/session-revision-two-client-uds.test.ts
index 8e039340ca..790ba8ba68 100644
--- a/packages/runtime-host/src/__tests__/session-revision-two-client-uds.test.ts
+++ b/packages/runtime-host/src/__tests__/session-revision-two-client-uds.test.ts
@@ -1712,7 +1712,7 @@ async function verifyDurableBranch(
     // projects the copied turn as ended, exactly as the source reads.
     assert.deepEqual(
       messages.map((message) => message.type),
-      ['user', 'assistant', 'tool_call', 'tool_result', 'system_note', 'turn_state'],
+      ['user', 'assistant', 'tool_call', 'tool_result', 'turn_state'],
     );
     const user = messages.find((message) => message.type === 'user');
     assert.ok(user?.attachments?.[0]);
diff --git a/packages/runtime-host/src/server/execution-model-composition.ts b/packages/runtime-host/src/server/execution-model-composition.ts
index f06cb71872..b2812d74e1 100644
--- a/packages/runtime-host/src/server/execution-model-composition.ts
+++ b/packages/runtime-host/src/server/execution-model-composition.ts
@@ -346,6 +346,9 @@ async function buildHostAiSdkBackend(
         appendMessage:
           input.context.appendMessage ??
           ((message) => input.context.store.appendMessage(input.context.sessionId, message)),
+        ...(input.context.recordSystemNote
+          ? { recordSystemNote: input.context.recordSystemNote }
+          : {}),
         readExecutionBoundary: () =>
           input.context.store.readExecutionBoundary(input.context.sessionId),
         ...(input.context.store.createSandboxBoundaryRequest
diff --git a/packages/runtime-host/src/server/session-revision-coordinator.ts b/packages/runtime-host/src/server/session-revision-coordinator.ts
index 3972b9baf8..829872cc8c 100644
--- a/packages/runtime-host/src/server/session-revision-coordinator.ts
+++ b/packages/runtime-host/src/server/session-revision-coordinator.ts
@@ -611,10 +611,6 @@ export class HostSessionRevisionCoordinator {
       if (copiedMessages.length > 0) {
         await this.#stores.sessionStore.appendMessages(input.targetSessionId, [...copiedMessages]);
       }
-      await this.#stores.sessionStore.appendMessage(
-        input.targetSessionId,
-        conversationCopyStartNote(kind, input, createInput),
-      );
       await this.#stores.sessionStore.updateHeader(input.targetSessionId, {
         conversationCopy: {
           ...createInput.conversationCopy!,
@@ -890,25 +886,15 @@ export class HostSessionRevisionCoordinator {
     );
   }
 
+  /**
+   * A revision copy that admitted a turn of its own. The admission ledger is
+   * the whole answer: a copy clones the source's history but never its
+   * admissions, so every row it holds was admitted on this session.
+   */
   async #hasAdmittedRevisionTurn(sessionId: string): Promise<boolean> {
-    if (
+    return (
       (await this.#stores.agentRunStore.listRootTurnAdmissionsForRecovery(sessionId)).length > 0
-    ) {
-      return true;
-    }
-    const messages = await this.#stores.sessionStore.readMessagesForRecovery(sessionId);
-    let boundary = -1;
-    for (let index = 0; index < messages.length; index += 1) {
-      const message = messages[index]!;
-      if (
-        message.type === 'system_note' &&
-        message.kind === 'session_start' &&
-        isRevisionStartData(message.data)
-      ) {
-        boundary = index;
-      }
-    }
-    return boundary >= 0 && messages.slice(boundary + 1).some((message) => message.type === 'user');
+    );
   }
 
   async #hasCommittedConversationCopyDependent(sessionId: string): Promise<boolean> {
@@ -948,42 +934,6 @@ function conversationCopyFingerprint(
   return `sha256:${createHash('sha256').update(JSON.stringify(identity)).digest('hex')}`;
 }
 
-function conversationCopyStartNote(
-  kind: ConversationCopySemanticKind,
-  input: SessionConversationCopyInput,
-  createInput: ConversationCopyCreateInput,
-): StoredMessage {
-  const base = {
-    type: 'system_note' as const,
-    id: randomUUID(),
-    ts: Date.now(),
-    kind: 'session_start' as const,
-  };
-  if (kind !== 'revision') {
-    // Empty copies record provenance without a branch turn.
-    return {
-      ...base,
-      data: {
-        parentSessionId: input.sourceSessionId,
-        ...(input.sourceTurnId === undefined ? {} : { branchOfTurnId: input.sourceTurnId }),
-      },
-    };
-  }
-  if (input.sourceTurnId === undefined) {
-    throw new Error('Session revision copy requires a turn boundary');
-  }
-  return {
-    ...base,
-    data: {
-      revisionRootSessionId: createInput.revisionRootSessionId,
-      revisionParentSessionId: input.sourceSessionId,
-      revisionOfTurnId: input.sourceTurnId,
-      revisionIndex: createInput.revisionIndex,
-      revisionState: 'preparing',
-    },
-  };
-}
-
 function conversationCopySemanticKind(
   kind: ConversationCopyKind,
   input: SessionConversationCopyInput,
@@ -995,15 +945,6 @@ function persistedConversationCopyKind(kind: ConversationCopySemanticKind): Conv
   return kind === 'revision' ? 'revision' : 'branch';
 }
 
-function isRevisionStartData(value: unknown): boolean {
-  return (
-    !!value &&
-    typeof value === 'object' &&
-    !Array.isArray(value) &&
-    'revisionRootSessionId' in value
-  );
-}
-
 function collectArchivedToolResultPlaceholders(
   events: readonly RuntimeEvent[],
   messages: readonly StoredMessage[],
diff --git a/packages/runtime/src/__tests__/mid-turn-capacity-backend.test.ts b/packages/runtime/src/__tests__/mid-turn-capacity-backend.test.ts
index 8e0eff790d..a1f9df154b 100644
--- a/packages/runtime/src/__tests__/mid-turn-capacity-backend.test.ts
+++ b/packages/runtime/src/__tests__/mid-turn-capacity-backend.test.ts
@@ -471,6 +471,17 @@ function buildFixture(options: MidTurnFixtureOptions = {}): MidTurnFixture {
     appendMessage: async (message) => {
       messages.push(message);
     },
+    // A note is a runtime event now. The fixture records it in the shape the
+    // read model projects back, so these assertions still read the row a
+    // transcript would show.
+    recordSystemNote: async (kind, turnId, data) => {
+      messages.push({
+        type: 'system_note',
+        kind,
+        turnId,
+        ...(data !== undefined ? { data } : {}),
+      });
+    },
     connection: {
       ...connection(),
       ...(options.providerNative
diff --git a/packages/runtime/src/__tests__/overflow-reactive-recovery.test.ts b/packages/runtime/src/__tests__/overflow-reactive-recovery.test.ts
index 36a3b8e2e9..f8de7b5087 100644
--- a/packages/runtime/src/__tests__/overflow-reactive-recovery.test.ts
+++ b/packages/runtime/src/__tests__/overflow-reactive-recovery.test.ts
@@ -587,6 +587,17 @@ function buildReactiveFixture(options: ReactiveFixtureOptions): ReactiveFixture
       if (!options.slowAppendMessage) return;
       for (let i = 0; i < 5; i += 1) await flushMacrotask();
     },
+    // A note is a runtime event now. The fixture records it in the shape the
+    // read model projects back, so these assertions still read the row a
+    // transcript would show.
+    recordSystemNote: async (kind, turnId, data) => {
+      messages.push({
+        type: 'system_note',
+        kind,
+        turnId,
+        ...(data !== undefined ? { data } : {}),
+      });
+    },
     connection: {
       ...connection(),
       ...(options.providerNative
diff --git a/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts b/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts
index 2216a52160..4bfb344305 100644
--- a/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts
+++ b/packages/runtime/src/__tests__/runtime-kernel-interaction.test.ts
@@ -260,11 +260,6 @@ describe('RuntimeKernel Interaction close cleanup', () => {
       ).length,
       1,
     );
-    assert.equal(
-      messages.filter((message) => message.type === 'system_note' && message.kind === 'abort')
-        .length,
-      1,
-    );
 
     const blockedActivation = fixture.kernel
       .startTurn(SESSION_ID, { turnId: 'turn-before-runner-settled', text: 'must not send' })
@@ -376,11 +371,6 @@ describe('RuntimeKernel Interaction close cleanup', () => {
       ).length,
       1,
     );
-    assert.equal(
-      firstMessages.filter((message) => message.type === 'system_note' && message.kind === 'abort')
-        .length,
-      1,
-    );
 
     const second = kernel
       .startTurn(SESSION_ID, { turnId: 'turn-generation-2', text: 'second' })
diff --git a/packages/runtime/src/__tests__/session-manager.test.ts b/packages/runtime/src/__tests__/session-manager.test.ts
index 577e640b15..78aa131334 100644
--- a/packages/runtime/src/__tests__/session-manager.test.ts
+++ b/packages/runtime/src/__tests__/session-manager.test.ts
@@ -2932,7 +2932,9 @@ describe('SessionManager child-session runtime primitive', () => {
       runtimeEventStore: runStore,
       backends,
       childTools: [testTool('Read'), testTool('Glob'), testTool('Grep')],
-      newId: nextId(),
+      // Its own id space: a restarted host mints fresh ids, it does not replay
+      // the sequence the dead process was on.
+      newId: nextId('restarted'),
       now: nextNow(196),
     });
     await drain(
@@ -3453,7 +3455,7 @@ describe('SessionManager manual compaction and quiescent session changes', () =>
     if (complete?.type !== 'complete') throw new Error('expected complete');
     assert.strictEqual(complete.contextCompactionOutcome?.kind, 'compacted');
 
-    const messages = await store.readMessages(session.id);
+    const messages = await manager.getMessages(session.id);
     assert.strictEqual(
       messages.some((message) => message.type === 'user' && message.text.includes('compact')),
       false,
@@ -3618,7 +3620,7 @@ describe('SessionManager manual compaction and quiescent session changes', () =>
     await drain(manager.sendMessage(session.id, { turnId: 'turn-1', text: 'hello' }));
     await drain(manager.compactSession(session.id, { turnId: 'turn-compact' }));
 
-    const warnings = (await store.readMessages(session.id)).filter(
+    const warnings = (await manager.getMessages(session.id)).filter(
       (message) =>
         message.type === 'system_note' &&
         message.turnId === 'turn-compact' &&
@@ -4591,13 +4593,6 @@ describe('SessionManager permission mode updates', () => {
     assert.strictEqual(summary.permissionMode, 'ask');
     assert.deepStrictEqual(summary.labels, ['kept']);
     assert.deepStrictEqual((await store.readHeader(session.id)).labels, ['kept']);
-
-    const messages = await store.readMessages(session.id);
-    const modeNote = messages.find(
-      (message) => message.type === 'system_note' && message.kind === 'mode_change',
-    );
-    if (modeNote?.type !== 'system_note') throw new Error('mode_change note was not written');
-    assert.deepStrictEqual(modeNote.data, { from: 'explore', to: 'ask' });
   });
 
   test('starts a new turn without workspace identity when safety inspection fails', async () => {
@@ -9446,11 +9441,6 @@ describe('SessionManager permission mode updates', () => {
 
     assert.strictEqual(backend?.stopCalls, 1);
     const messages = await store.readMessages(session.id);
-    assert.strictEqual(
-      messages.filter((message) => message.type === 'system_note' && message.kind === 'abort')
-        .length,
-      1,
-    );
     assert.strictEqual(
       messages.filter(
         (message) =>
@@ -9649,7 +9639,7 @@ describe('SessionManager permission mode updates', () => {
       [Symbol.asyncIterator]();
     await turn.next();
     store.failAfterNextAppendMessage = (message) =>
-      message.type === 'system_note' && message.kind === 'abort';
+      message.type === 'turn_state' && message.status === 'aborted';
 
     await expectRejects(
       manager.stopSession(session.id, { source: 'stop_button' }),
@@ -9668,11 +9658,6 @@ describe('SessionManager permission mode updates', () => {
       ).length,
       1,
     );
-    assert.strictEqual(
-      messages.filter((message) => message.type === 'system_note' && message.kind === 'abort')
-        .length,
-      1,
-    );
     sendGate.release();
     while (!(await turn.next()).done) {}
   });
@@ -9723,11 +9708,6 @@ describe('SessionManager permission mode updates', () => {
       ).length,
       1,
     );
-    assert.strictEqual(
-      messages.filter((message) => message.type === 'system_note' && message.kind === 'abort')
-        .length,
-      1,
-    );
   });
 
   test('agent projections list catalog definitions separately from child runs and read output artifacts by child turn', async () => {
@@ -10616,12 +10596,6 @@ describe('SessionManager permission mode updates', () => {
     const [turn] = await store.listTurns(session.id);
     assert.strictEqual(turn?.status, 'aborted');
     assert.strictEqual(turn?.abortSource, 'renderer.stop_button');
-    const abortNote = (await store.readMessages(session.id)).find(
-      (message) => message.type === 'system_note' && message.kind === 'abort',
-    );
-    assert.strictEqual(abortNote?.type, 'system_note');
-    if (abortNote?.type !== 'system_note') throw new Error('abort note missing');
-    assert.deepStrictEqual(abortNote.data, { source: 'renderer.stop_button' });
   });
 
   test('stopSession persists abortSource on a terminal RuntimeEvent emitted during backend stop', async () => {
diff --git a/packages/runtime/src/agent-run.ts b/packages/runtime/src/agent-run.ts
index ff919edf1d..b63db06080 100644
--- a/packages/runtime/src/agent-run.ts
+++ b/packages/runtime/src/agent-run.ts
@@ -59,8 +59,8 @@ import type {
   SessionHeader,
   SessionHeaderPatch,
   SessionStatus,
+  RuntimeSystemNoteKind,
   StoredMessage,
-  SystemNoteMessage,
   TurnRecord,
   UserMessage,
 } from '@maka/core/session';
@@ -843,10 +843,29 @@ export class AgentRun {
     };
   }
 
-  async recordStoredSessionEvent(ev: SessionEvent): Promise<void> {
-    if (ev.type === 'token_usage') {
-      await this.input.store.appendMessage(this.sessionId, { ...ev } satisfies StoredMessage);
-    }
+  /**
+   * Record something the runtime needs to tell the reader about this turn.
+   *
+   * It is a fact of the invocation, so it goes where the invocation's facts go.
+   * Never model-visible: the note describes what happened to the conversation,
+   * it is not part of it.
+   */
+  async recordSystemNote(kind: RuntimeSystemNoteKind, data?: unknown): Promise<void> {
+    await this.recordRuntimeEvents([
+      {
+        id: this.input.newId(),
+        invocationId: this.invocationId,
+        runId: this.runId,
+        sessionId: this.sessionId,
+        turnId: this.turnId,
+        ts: this.input.now(),
+        partial: false,
+        role: 'system',
+        author: 'system',
+        modelVisibility: 'hidden',
+        content: { kind: 'system_note', note: kind, ...(data !== undefined ? { data } : {}) },
+      },
+    ]);
   }
 
   async recordSessionEvent(
@@ -1084,17 +1103,6 @@ export class AgentRun {
     } catch {
       // The user-visible turn already completed; preserve existing behavior.
     }
-    if (this.sawCompletion) {
-      await this.input.store
-        .appendMessage(this.sessionId, {
-          type: 'system_note',
-          id: this.input.newId(),
-          turnId: this.turnId,
-          ts: lastTs,
-          kind: 'session_resume',
-        } satisfies SystemNoteMessage)
-        .catch(() => {});
-    }
     await this.finishRun(this.finalStatus, lastTs);
   }
 
diff --git a/packages/runtime/src/ai-sdk-backend.ts b/packages/runtime/src/ai-sdk-backend.ts
index 2a065fffb2..da0cff59f7 100644
--- a/packages/runtime/src/ai-sdk-backend.ts
+++ b/packages/runtime/src/ai-sdk-backend.ts
@@ -25,7 +25,12 @@
  */
 
 import type { SessionEvent } from '@maka/core/events';
-import type { BackendKind, SessionHeader, StoredMessage } from '@maka/core/session';
+import type {
+  BackendKind,
+  RuntimeSystemNoteKind,
+  SessionHeader,
+  StoredMessage,
+} from '@maka/core/session';
 import type {
   AgentBackend,
   BackendCompactHistoryInput,
@@ -173,6 +178,11 @@ export interface AiSdkBackendInput extends AiSdkCompactionCapabilities {
   readChildAgentOutput?: ToolRuntimeInput['readChildAgentOutput'];
   /** Optional diagnostic trace hook for explaining a runtime turn without changing renderer events. */
   recordRunTrace?: RunTraceRecorder;
+  /**
+   * Writes one runtime note — something that happened inside this invocation —
+   * to the invocation's RuntimeEvent ledger, which is where its record lives.
+   */
+  recordSystemNote?: (kind: RuntimeSystemNoteKind, turnId: string, data?: unknown) => Promise<void>;
   /**
    * Commits one settled provider request: the canonical attempt and, when it
    * is the completed main call, the derived latest-context row it authorises.
diff --git a/packages/runtime/src/ai-sdk-turn.ts b/packages/runtime/src/ai-sdk-turn.ts
index c501a66ac7..c0e34b7e14 100644
--- a/packages/runtime/src/ai-sdk-turn.ts
+++ b/packages/runtime/src/ai-sdk-turn.ts
@@ -43,8 +43,8 @@ import type {
   AssistantMessage,
   AssistantStepContentKind,
   AssistantThinkingPart,
+  RuntimeSystemNoteKind,
   SessionHeader,
-  SystemNoteMessage,
   TokenUsageMessage,
 } from '@maka/core/session';
 import type { BackendSendInput } from '@maka/core/backend-types';
@@ -852,6 +852,20 @@ export class AiSdkTurn {
     };
   }
 
+  /**
+   * A note about what happened inside this invocation, written to the
+   * invocation's own ledger. Fail-open: the note explains a turn, it is not
+   * what the turn did, so losing it must never end a send that is otherwise
+   * fine.
+   */
+  private async recordSystemNote(
+    kind: RuntimeSystemNoteKind,
+    turnId: string,
+    data?: unknown,
+  ): Promise<void> {
+    await this.deps.backend.recordSystemNote?.(kind, turnId, data).catch(() => {});
+  }
+
   // --------------------------------------------------------------------------
   // manual history compaction
   // --------------------------------------------------------------------------
@@ -1669,15 +1683,10 @@ export class AiSdkTurn {
                       : stepUsage.inputTokens <= priorInput)
                   ) {
                     this.deps.session.contextProviderDroppingReported = true;
-                    const note: SystemNoteMessage = {
-                      type: 'system_note',
-                      id: this.deps.newId(),
-                      turnId,
-                      ts: this.deps.now(),
-                      kind: 'context_provider_dropping',
-                      data: { inputTokens: stepUsage.inputTokens, priorInputTokens: priorInput },
-                    };
-                    await this.deps.backend.appendMessage(note).catch(() => {});
+                    await this.recordSystemNote('context_provider_dropping', turnId, {
+                      inputTokens: stepUsage.inputTokens,
+                      priorInputTokens: priorInput,
+                    });
                   }
                   // Fail closed: reset on every step boundary so a missing final
                   // step's usage does not leave a stale value from an earlier step.
@@ -1698,18 +1707,10 @@ export class AiSdkTurn {
                     stepUsage.inputTokens + stepUsage.outputTokens > midTurnState.capacity
                   ) {
                     contextWindowOverrunNoteWritten = true;
-                    const note: SystemNoteMessage = {
-                      type: 'system_note',
-                      id: this.deps.newId(),
-                      turnId,
-                      ts: this.deps.now(),
-                      kind: 'context_window_overrun',
-                      data: {
-                        usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
-                        declaredContextWindow: midTurnState.capacity,
-                      },
-                    };
-                    await this.deps.backend.appendMessage(note).catch(() => {});
+                    await this.recordSystemNote('context_window_overrun', turnId, {
+                      usedTokens: stepUsage.inputTokens + stepUsage.outputTokens,
+                      declaredContextWindow: midTurnState.capacity,
+                    });
                   }
                   // Nothing declared, and the provider accepted a request past
                   // the window this model reports. Every other signal in this
@@ -1751,15 +1752,10 @@ export class AiSdkTurn {
                       (previousTotal === undefined || previousTotal <= reported);
                     if (reported !== undefined && crossedNow) {
                       contextReportedWindowNoteWritten = true;
-                      const note: SystemNoteMessage = {
-                        type: 'system_note',
-                        id: this.deps.newId(),
-                        turnId,
-                        ts: this.deps.now(),
-                        kind: 'context_reported_window_exceeded',
-                        data: { usedTokens: used, reportedContextWindow: reported },
-                      };
-                      await this.deps.backend.appendMessage(note).catch(() => {});
+                      await this.recordSystemNote('context_reported_window_exceeded', turnId, {
+                        usedTokens: used,
+                        reportedContextWindow: reported,
+                      });
                     }
                   }
                   lastStepInputTokens = stepUsage?.inputTokens;
@@ -2078,20 +2074,12 @@ export class AiSdkTurn {
                 (midTurnState.capacity === undefined || acceptedTotal < midTurnState.capacity)
               ) {
                 contextWindowSuggestionNoteWritten = true;
-                const note: SystemNoteMessage = {
-                  type: 'system_note',
-                  id: this.deps.newId(),
-                  turnId,
-                  ts: this.deps.now(),
-                  kind: 'context_window_suggestion',
-                  data: {
-                    suggestedContextWindow: acceptedTotal,
-                    ...(midTurnState.capacity !== undefined
-                      ? { declaredContextWindow: midTurnState.capacity }
-                      : {}),
-                  },
-                };
-                await this.deps.backend.appendMessage(note).catch(() => {});
+                await this.recordSystemNote('context_window_suggestion', turnId, {
+                  suggestedContextWindow: acceptedTotal,
+                  ...(midTurnState.capacity !== undefined
+                    ? { declaredContextWindow: midTurnState.capacity }
+                    : {}),
+                });
               }
               // A folded projection was selected in this send and the provider
               // still rejects the request. That is worth saying, because the
@@ -2107,14 +2095,7 @@ export class AiSdkTurn {
                 midTurnState?.compactionAppliedThisSend === true
               ) {
                 contextOverflowAfterCompactionNoteWritten = true;
-                const note: SystemNoteMessage = {
-                  type: 'system_note',
-                  id: this.deps.newId(),
-                  turnId,
-                  ts: this.deps.now(),
-                  kind: 'context_overflow_after_compaction',
-                };
-                await this.deps.backend.appendMessage(note).catch(() => {});
+                await this.recordSystemNote('context_overflow_after_compaction', turnId);
               }
               const idleWatchdogRecovery =
                 settledWatchdogTimeout?.phase === 'idle' &&
@@ -2494,28 +2475,14 @@ export class AiSdkTurn {
               shouldAppendContextCompactionFailedOpenNote(contextBudgetForUsage)
             ) {
               contextCompactionFailedOpenNoteWritten = true;
-              const note: SystemNoteMessage = {
-                type: 'system_note',
-                id: this.deps.newId(),
-                turnId,
-                ts: this.deps.now(),
-                kind: 'context_compaction_failed_open',
-              };
-              await this.deps.backend.appendMessage(note).catch(() => {});
+              await this.recordSystemNote('context_compaction_failed_open', turnId);
             }
             if (
               !contextCompactedNoteWritten &&
               shouldAppendContextCompactedNote(contextBudgetForUsage)
             ) {
               contextCompactedNoteWritten = true;
-              const note: SystemNoteMessage = {
-                type: 'system_note',
-                id: this.deps.newId(),
-                turnId,
-                ts: this.deps.now(),
-                kind: 'context_compacted',
-              };
-              await this.deps.backend.appendMessage(note).catch(() => {});
+              await this.recordSystemNote('context_compacted', turnId);
             }
             queue.push({
               type: 'token_usage',
diff --git a/packages/runtime/src/runtime-event-backfill.ts b/packages/runtime/src/runtime-event-backfill.ts
index a48b0c5e98..4c33befd1f 100644
--- a/packages/runtime/src/runtime-event-backfill.ts
+++ b/packages/runtime/src/runtime-event-backfill.ts
@@ -19,7 +19,7 @@
 
 import type { RuntimeInvocationOutcome } from '@maka/core/runtime-invocation';
 import type { RunIdentity } from './terminal-run-commit.js';
-import { isTurnScopedSystemNoteKind } from '@maka/core/session';
+import { isRuntimeSystemNoteKind } from '@maka/core/session';
 import type {
   PermissionDecisionMessage,
   StoredMessage,
@@ -365,7 +365,7 @@ export function backfillRuntimeEventsFromStoredMessages(
       // something about the Session, and the Session transcript keeps it.
       case 'system_note':
         if (conversationTextOnly) break;
-        if (!isTurnScopedSystemNoteKind(message.kind)) {
+        if (!isRuntimeSystemNoteKind(message.kind)) {
           diagnostics.push({
             code: 'skipped_high_risk_message',
             message:
diff --git a/packages/runtime/src/runtime-kernel.ts b/packages/runtime/src/runtime-kernel.ts
index d18cce8d65..358b314dbd 100644
--- a/packages/runtime/src/runtime-kernel.ts
+++ b/packages/runtime/src/runtime-kernel.ts
@@ -46,7 +46,6 @@ import type {
   SessionHeaderPatch,
   SessionStatus,
   StoredMessage,
-  SystemNoteMessage,
   TurnRecord,
   TurnStateMessage,
 } from '@maka/core/session';
@@ -332,8 +331,6 @@ interface StopOperation {
       projected: boolean;
     }
   >;
-  abortNote: SystemNoteMessage;
-  abortNoteProjected: boolean;
   targets: Map<number, StopTarget>;
   queue: Promise<void>;
 }
@@ -1085,24 +1082,18 @@ export class RuntimeKernel implements RuntimeKernelLike {
         runId: run.runId,
         turnId: run.turnId,
       });
+      // Ahead of the usage row, because the ledger seals on its terminal fact:
+      // a note queued behind one this compaction may already own would be
+      // refused, and the reader would never learn the summary was skipped.
+      if (result.outcome.kind === 'failed') {
+        await run.recordSystemNote('context_compaction_failed_open').catch(() => {});
+      }
       await run.acceptMappedEvent(
         tokenUsageEvent,
         mapSessionEventToRuntimeEvent(tokenUsageEvent, eventContext),
         { requireTerminalWrite: true },
       );
       if (run.isStopped()) return;
-      await run.recordStoredSessionEvent(tokenUsageEvent);
-      if (run.isStopped()) return;
-      if (result.outcome.kind === 'failed') {
-        const note: SystemNoteMessage = {
-          type: 'system_note',
-          id: this.deps.newId(),
-          turnId: run.turnId,
-          ts: this.deps.now(),
-          kind: 'context_compaction_failed_open',
-        };
-        await this.deps.store.appendMessage(sessionId, note).catch(() => {});
-      }
       yield tokenUsageEvent;
       if (run.isStopped()) return;
       await run.acceptMappedEvent(
@@ -1847,14 +1838,6 @@ export class RuntimeKernel implements RuntimeKernelLike {
       ts,
       statusProjected: false,
       turnProjections: new Map(),
-      abortNote: {
-        type: 'system_note',
-        id: this.deps.newId(),
-        ts,
-        kind: 'abort',
-        ...(abortSource ? { data: { source: abortSource } } : {}),
-      },
-      abortNoteProjected: false,
       targets: new Map(),
       queue: Promise.resolve(),
     };
@@ -1948,10 +1931,6 @@ export class RuntimeKernel implements RuntimeKernelLike {
       await this.appendStopProjection(sessionId, projection.message);
       projection.projected = true;
     }
-    if (!operation.abortNoteProjected) {
-      await this.appendStopProjection(sessionId, operation.abortNote);
-      operation.abortNoteProjected = true;
-    }
     // The Session projection above now reads as aborted. The ledger has to say
     // the same thing before this stop reports success: a Run left non-terminal
     // here stays that way, because the stream that would have finalized it is
@@ -1977,7 +1956,6 @@ export class RuntimeKernel implements RuntimeKernelLike {
     }
     const completed =
       operation.statusProjected &&
-      operation.abortNoteProjected &&
       [...operation.turnProjections.values()].every((projection) => projection.projected) &&
       [...operation.targets.values()].every(
         (target) =>
@@ -2298,6 +2276,7 @@ export class RuntimeKernel implements RuntimeKernelLike {
   }): Pick<
     BackendFactoryContext,
     | 'recordRunTrace'
+    | 'recordSystemNote'
     | 'recordModelCallAttempt'
     | 'recordRunComposition'
     | 'loadHistoryCompactCheckpoint'
@@ -2316,6 +2295,8 @@ export class RuntimeKernel implements RuntimeKernelLike {
       recordRunTrace: (event) => {
         runFor(event.turnId)?.recordRunTrace(event);
       },
+      recordSystemNote: (kind, turnId, data) =>
+        runFor(turnId)?.recordSystemNote(kind, data) ?? Promise.resolve(),
       ...(this.deps.runStore
         ? {
             // Resolved by runId rather than turnId: the canonical record names
diff --git a/packages/runtime/src/session-manager.ts b/packages/runtime/src/session-manager.ts
index 408e8b2a11..ddfbcddb9e 100644
--- a/packages/runtime/src/session-manager.ts
+++ b/packages/runtime/src/session-manager.ts
@@ -52,11 +52,11 @@ import type {
   SessionStatus,
   SessionSummary,
   StoredMessage,
+  RuntimeSystemNoteKind,
   SubagentSessionParent,
   TurnRecord,
   UserMessage,
   PermissionDecisionMessage,
-  SystemNoteMessage,
   PersistedBackendKind,
 } from '@maka/core/session';
 import type {
@@ -697,6 +697,11 @@ export interface BackendFactoryContext {
    * provider call, including metering and its prepared-request observation.
    */
   recordModelCallAttempt?: (commit: ModelCallCommit<ModelCallAttempt>) => Promise<void>;
+  /**
+   * Writes one runtime note — something that happened inside the running
+   * invocation — to that invocation's RuntimeEvent ledger.
+   */
+  recordSystemNote?: (kind: RuntimeSystemNoteKind, turnId: string, data?: unknown) => Promise<void>;
   /** Immutable Run policy snapshot; provider dispatch waits for this durable commit. */
   recordRunComposition?: (runId: string, snapshot: RunCompositionSnapshot) => Promise<void>;
   loadHistoryCompactCheckpoint?: () => Promise<HistoryCompactCheckpoint | undefined>;
@@ -1478,15 +1483,10 @@ export class SessionManager {
         messagesReadable = false;
       }
 
-      if (session.revisionState === 'preparing' && messagesReadable) {
-        if (hasRevisionUserMessage(messages)) {
-          await recoverOr(policy, () => this.commitRevisionVersion(session.id), undefined);
-        } else {
-          await recoverOr(policy, () => this.remove(session.id), undefined);
-          recovered.add(session.id);
-          continue;
-        }
-      }
+      // A revision copy still `preparing` is settled by the Host's revision
+      // coordinator, which reads the admission ledger and runs before this
+      // recovery. Deciding it a second time here — off a transcript scan, and
+      // ending in `remove()` — could only ever contradict it.
 
       let continuationClaimRecovered = false;
       const continuationAuthority = runtimeContinuationAuthority(this.deps.runtimeEventStore);
@@ -1638,15 +1638,6 @@ export class SessionManager {
     });
     const next = await this.deps.store.readHeader(sessionId);
     this.runtimeKernel.updateCachedHeader(sessionId, next);
-    await this.deps.store
-      .appendMessage(sessionId, {
-        type: 'system_note',
-        id: this.deps.newId(),
-        ts: this.deps.now(),
-        kind: 'mode_change',
-        data: { from: previous.permissionMode, to: mode },
-      } satisfies SystemNoteMessage)
-      .catch(() => undefined);
     return headerToSummary(next);
   }
 
@@ -1863,13 +1854,6 @@ export class SessionManager {
     const next = await this.deps.store.updateHeader(sessionId, {
       collaborationMode: mode,
     });
-    await this.deps.store.appendMessage(sessionId, {
-      type: 'system_note',
-      id: this.deps.newId(),
-      ts: this.deps.now(),
-      kind: 'mode_change',
-      data: { dimension: 'collaboration', from, to: mode },
-    } satisfies SystemNoteMessage);
     this.runtimeKernel.updateCachedHeader(sessionId, next);
     await this.runtimeKernel.disposeBackend(sessionId);
     return headerToSummary(next);
@@ -1886,13 +1870,6 @@ export class SessionManager {
       throw new Error('Cannot change orchestration mode while a tool call awaits confirmation.');
     }
     const next = await this.deps.store.updateHeader(sessionId, { orchestrationMode: mode });
-    await this.deps.store.appendMessage(sessionId, {
-      type: 'system_note',
-      id: this.deps.newId(),
-      ts: this.deps.now(),
-      kind: 'mode_change',
-      data: { dimension: 'orchestration', from, to: mode },
-    } satisfies SystemNoteMessage);
     this.runtimeKernel.updateCachedHeader(sessionId, next);
     return headerToSummary(next);
   }
@@ -1935,7 +1912,7 @@ export class SessionManager {
     }
     if (!replay) await this.runtimeKernel.disposeBackend(sessionId);
     const result = await this.requirePlanStore().abandonProposal(input);
-    await this.finalizePlanAbandonment(sessionId, operationId, replay);
+    await this.finalizePlanAbandonment(sessionId);
     return result;
   }
 
@@ -4206,41 +4183,13 @@ export class SessionManager {
     this.runtimeKernel.updateCachedHeader(sessionId, next);
   }
 
-  private async finalizePlanAbandonment(
-    sessionId: string,
-    operationId: string | undefined,
-    replay: boolean,
-  ): Promise<void> {
+  private async finalizePlanAbandonment(sessionId: string): Promise<void> {
     const header = await this.deps.store.readHeader(sessionId);
-    const from = header.collaborationMode ?? 'agent';
-    const changed = from !== 'agent';
-    const next = changed
-      ? await this.deps.store.updateHeader(sessionId, { collaborationMode: 'agent' })
-      : header;
+    const next =
+      (header.collaborationMode ?? 'agent') === 'agent'
+        ? header
+        : await this.deps.store.updateHeader(sessionId, { collaborationMode: 'agent' });
     this.runtimeKernel.updateCachedHeader(sessionId, next);
-
-    if (!changed && !replay) return;
-    if (!operationId) {
-      await this.deps.store.appendMessage(sessionId, {
-        type: 'system_note',
-        id: this.deps.newId(),
-        ts: this.deps.now(),
-        kind: 'mode_change',
-        data: { dimension: 'collaboration', from, to: 'agent' },
-      } satisfies SystemNoteMessage);
-      return;
-    }
-
-    const noteId = planAbandonmentNoteId(operationId);
-    const messages = await this.deps.store.readMessages(sessionId);
-    if (messages.some((message) => message.id === noteId)) return;
-    await this.deps.store.appendMessage(sessionId, {
-      type: 'system_note',
-      id: noteId,
-      ts: this.deps.now(),
-      kind: 'mode_change',
-      data: { dimension: 'collaboration', from: 'plan', to: 'agent' },
-    } satisfies SystemNoteMessage);
   }
 
   private requirePlanStore(): PlanStore {
@@ -4711,10 +4660,6 @@ export class SessionManager {
   }
 }
 
-function planAbandonmentNoteId(operationId: string): string {
-  return `plan-abandonment-${createHash('sha256').update(operationId).digest('hex')}`;
-}
-
 function resumeFeatureDisabledPlan(): SafeBoundaryContinuationPlan {
   return {
     disposition: 'park',
@@ -5188,23 +5133,6 @@ interface InterruptedTurnRecovery {
   >;
 }
 
-function hasRevisionUserMessage(messages: readonly StoredMessage[]): boolean {
-  let boundary = -1;
-  for (let index = 0; index < messages.length; index += 1) {
-    const message = messages[index]!;
-    if (
-      message.type === 'system_note' &&
-      message.kind === 'session_start' &&
-      message.data &&
-      typeof message.data === 'object' &&
-      'revisionRootSessionId' in message.data
-    ) {
-      boundary = index;
-    }
-  }
-  return boundary >= 0 && messages.slice(boundary + 1).some((message) => message.type === 'user');
-}
-
 function interruptedTurnRecoveries(messages: readonly StoredMessage[]): InterruptedTurnRecovery[] {
   const byTurn = new Map<
     string,


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