Skip to content

Commit 367ff3c

Browse files
authored
feat(sqlite): migrate persisted media to canonical facts and stop legacy writes (#113695)
* feat(sqlite): migrate persisted media to canonical facts and stop legacy writes PR 3 of the media legacy retirement program — the operator-approved canonical cutover. - openclaw doctor --fix owns one idempotent migration: active transcript_events rows canonicalize to __openclaw.media (facts-first gap-fill, bare legacy kinds to fact.kind, transcribed indexes and workspace dirs onto per-fact fields) via the transcript replacement owner; cold plain/.zst archives rewrite through temp-file + codec readback + event/id verification + atomic replace; trajectory runtime snapshots canonicalize IN PLACE (telemetry preserved, never row deletion). Invalid JSON, genuinely ambiguous legacy-only sparse alignment, or a changed source aborts that owner without partial work; reruns are no-ops. - Per-agent schema advances to v16 as a pure downgrade guard (main independently took v15 for board/session-sharing tables; no columns/tables/indexes change here, shared-state DB untouched). v15 databases repair canonical indexes before the version assertion so repairable installations never strand. - The user-turn builder stops writing top-level legacy Media* fields; shouldPersistStructuredMediaEntries and the aligned projection mode are deleted; the generic transcript append boundary canonicalizes every message role so SDK/mirror writers cannot mint new legacy rows. - Internal persisted-reader legacy fallbacks are removed; the public SDK projection stays until retirement PR 4's window expires. Hardening from three adversarial review rounds, each with fixture regressions: in-place trajectory canonicalization instead of row deletion; repair-before-assert on the v15 path; all-roles append canonicalization; duplicate-preserving exact row rewrites; v0-v15 reopen guards; complete canonical facts bypass compact legacy projections (PR-1 dual-write rows migrate cleanly); SQLite LIKE underscore escaped so populated foreign databases are never claimed. * fix(sqlite): align schema-support metadata and gates with the v16 cutover package.json agent schema support advances to 16; verifier and board parity fixtures run doctor migration before steady-state access (the production guards were correct); two test-only exports removed; the migration module registered in the doctor raw-SQLite allowlist.
1 parent 97c5758 commit 367ff3c

55 files changed

Lines changed: 2627 additions & 663 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"openclaw": {
55
"schemaVersions": {
66
"state": 6,
7-
"agent": 15
7+
"agent": 16
88
}
99
},
1010
"description": "Multi-channel AI gateway with extensible messaging integrations",

‎scripts/check-kysely-guardrails.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ const rawSqliteAllowPathGroups = {
102102
"src/infra/state-migrations.meeting-transcripts-detection.ts",
103103
"src/infra/state-migrations.meeting-transcripts-files.ts",
104104
"src/infra/state-migrations.meeting-transcripts-verify.ts",
105+
"src/infra/state-migrations.media-persistence.ts",
105106
],
106107
"shared database stores with direct DatabaseSync access": ["src/proxy-capture/store.sqlite.ts"],
107108
"Kysely-backed stores that own a DatabaseSync boundary": [

‎src/agents/agent-command.live-model-switch.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3572,10 +3572,11 @@ describe("agentCommand – LiveSessionModelSwitchError retry", () => {
35723572
expect(attempt.userTurnTranscriptRecorder?.message).toMatchObject({
35733573
role: "user",
35743574
content: "",
3575-
MediaPath: "/media/inbound/image-1.png",
3576-
MediaPaths: ["/media/inbound/image-1.png"],
3577-
MediaType: "image/png",
3578-
MediaTypes: ["image/png"],
3575+
__openclaw: {
3576+
media: [
3577+
expect.objectContaining({ path: "/media/inbound/image-1.png", contentType: "image/png" }),
3578+
],
3579+
},
35793580
});
35803581
});
35813582

‎src/agents/cli-runner.reliability.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3618,8 +3618,9 @@ describe("runCliAgent reliability", () => {
36183618
expect.objectContaining({
36193619
role: "user",
36203620
content: "recorder display prompt",
3621-
MediaPath: "/tmp/image.png",
3622-
MediaType: "image/png",
3621+
__openclaw: {
3622+
media: [expect.objectContaining({ path: "/tmp/image.png", contentType: "image/png" })],
3623+
},
36233624
timestamp: 123,
36243625
idempotencyKey: "cli-recorder:user",
36253626
}),

‎src/agents/command/attempt-execution.cli.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1612,10 +1612,14 @@ describe("CLI attempt execution", () => {
16121612
expect.objectContaining({
16131613
role: "user",
16141614
content: "",
1615-
MediaPath: "/media/inbound/image-1.png",
1616-
MediaPaths: ["/media/inbound/image-1.png"],
1617-
MediaType: "image/png",
1618-
MediaTypes: ["image/png"],
1615+
__openclaw: {
1616+
media: [
1617+
expect.objectContaining({
1618+
path: "/media/inbound/image-1.png",
1619+
contentType: "image/png",
1620+
}),
1621+
],
1622+
},
16191623
}),
16201624
);
16211625
});

‎src/agents/embedded-agent-runner/replay-history.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ describe("normalizeAssistantReplayContent", () => {
107107
legacyOnly,
108108
]);
109109

110-
expect(out).toEqual([blankString, { ...blankArray, content: "" }, urlOnly, legacyOnly]);
110+
expect(out).toEqual([blankString, { ...blankArray, content: "" }, urlOnly]);
111111
});
112112

113113
it("converts mid-turn assistant content: [] to a non-empty sentinel text block when stopReason is error", () => {

‎src/agents/embedded-agent-runner/run/attempt-finalize.media.test.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { finalizeEmbeddedAttempt } from "./attempt-finalize.js";
33
import type { EmbeddedRunAttemptResult } from "./types.js";
44

55
describe("finalizeEmbeddedAttempt media trajectory capture", () => {
6-
it("records facts-only message snapshots with canonical conflict precedence", () => {
6+
it("records canonical message snapshots without reprojecting them", () => {
77
const recordEvent = vi.fn();
88
const result = {
99
terminal: { kind: "ok" },
@@ -20,8 +20,6 @@ describe("finalizeEmbeddedAttempt media trajectory capture", () => {
2020
{
2121
role: "user",
2222
content: "inspect",
23-
MediaPath: "/media/legacy.png",
24-
MediaType: "image/png",
2523
__openclaw: {
2624
media: [{ path: "/media/canonical.png", contentType: "image/png" }],
2725
},

‎src/agents/embedded-agent-runner/run/attempt-finalize.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { formatErrorMessage } from "../../../infra/errors.js";
2-
import { projectPersistedMessageMediaFacts } from "../../../media/media-facts.js";
32
import { buildTrajectoryArtifacts } from "../../../trajectory/metadata.js";
43
import { projectAgentRunAttemptTerminal } from "../../agent-run-terminal-outcome.js";
54
import {
@@ -71,9 +70,7 @@ export function finalizeEmbeddedAttempt(
7170
compactionCount: result.compactionCount,
7271
assistantTexts: result.assistantTexts,
7372
finalPromptText: result.finalPromptText,
74-
messagesSnapshot: result.messagesSnapshot.map((message) =>
75-
projectPersistedMessageMediaFacts(message),
76-
),
73+
messagesSnapshot: result.messagesSnapshot,
7774
});
7875
trajectoryRecorder?.recordEvent(
7976
"trace.artifacts",

‎src/agents/embedded-agent-runner/run/attempt-prompt-execution-prepare.test.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -183,11 +183,6 @@ describe("prepareEmbeddedAttemptPromptExecution", () => {
183183
});
184184

185185
it.each([
186-
{
187-
name: "legacy-only",
188-
message: { MediaPath: "/tmp/legacy.png", MediaType: "image/png" },
189-
expectedPath: "/tmp/legacy.png",
190-
},
191186
{
192187
name: "facts-only",
193188
message: { __openclaw: { media: [{ path: "/tmp/fact.png", contentType: "image/png" }] } },
@@ -231,7 +226,7 @@ describe("prepareEmbeddedAttemptPromptExecution", () => {
231226
},
232227
expectedPath: "/tmp/media-only.png",
233228
},
234-
])("hydrates $name persisted rows through facts-first media", async (testCase) => {
229+
])("hydrates $name persisted rows through canonical media", async (testCase) => {
235230
const base = createInput();
236231
const persistedMessage = {
237232
role: "user" as const,

‎src/agents/embedded-agent-runner/run/attempt-prompt-execution-prepare.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** Prepares prompt-lock ownership and prompt-local images for submission. */
22
import { MAX_IMAGE_BYTES } from "@openclaw/media-core/constants";
33
import type { OwnedSessionTranscriptCacheSnapshot } from "../../../config/sessions/transcript-write-context.js";
4-
import { readPersistedMediaFactsWithLegacyFallback } from "../../../media/media-facts.js";
4+
import { readPersistedMediaFacts } from "../../../media/media-facts.js";
55
import { resolveImageSanitizationLimits } from "../../image-sanitization.js";
66
import type { SandboxContext } from "../../sandbox/types.js";
77
import type { AgentSession } from "../../sessions/index.js";
@@ -71,9 +71,7 @@ export async function prepareEmbeddedAttemptPromptExecution(input: {
7171
const persistedMessage =
7272
attempt.userTurnTranscriptRecorder?.message ??
7373
(await attempt.userTurnTranscriptRecorder?.resolveMessage());
74-
const persistedMedia = persistedMessage
75-
? (readPersistedMediaFactsWithLegacyFallback(persistedMessage) ?? [])
76-
: [];
74+
const persistedMedia = persistedMessage ? (readPersistedMediaFacts(persistedMessage) ?? []) : [];
7775

7876
return await detectAndLoadPromptImages({
7977
prompt: input.prompt,

0 commit comments

Comments
 (0)